<?php
// Filename: teacher_timetable.php
require 'config.php';
requireLogin();

$uid = $_SESSION['user_id'];

// 1. SETTINGS
$s_start        = getSetting('start_time', '07:30');
$s_dur          = intval(getSetting('slot_duration', 30));
$s_recess_lower = intval(getSetting('recess_slot', 5));
$s_recess_upper = intval(getSetting('recess_slot_upper', 6));
$s_recess_dur   = intval(getSetting('recess_duration', 20));
$week_start     = intval(getSetting('week_start_day', 1)); 
$days_count     = intval(getSetting('school_days_count', 5));

$upper_forms = [4, 5, 6];
$lower_forms = [1, 2, 3]; 

$days_map = [1=>'Mon', 2=>'Tue', 3=>'Wed', 4=>'Thu', 5=>'Fri', 6=>'Sat', 7=>'Sun'];
$display_days = [];
$day_end_times = [];
$latest_end_str = $s_start;

for($i=0; $i<$days_count; $i++) {
    $d = $week_start + $i;
    if($d > 7) $d -= 7;
    $display_days[] = $d;
    $e_time = getSetting("end_time_$d", '14:30');
    $day_end_times[$d] = $e_time;
    if($e_time > $latest_end_str) $latest_end_str = $e_time;
}

// GENERATE TIME SLOTS
$time_slots = [];
$period_map = []; 
$curr_ts = strtotime($s_start);
$cutoff_ts = strtotime($latest_end_str);
$period_counter = 1;

while($curr_ts < $cutoff_ts) {
    $is_recess = ($period_counter == $s_recess_lower || $period_counter == $s_recess_upper);
    $duration = $is_recess ? $s_recess_dur : $s_dur;
    $end_ts = $curr_ts + ($duration * 60);
    
    $start_str = date('H:i', $curr_ts);
    $end_str = date('H:i', $end_ts);
    
    $label = "<div class='text-primary mb-1' style='font-size:0.8rem;'>#$period_counter</div>" . $start_str . "<br><span class='opacity-50'>" . $end_str . "</span>";
    
    $time_slots[$period_counter] = [
        'start' => $start_str, 
        'end' => $end_str, 
        'label' => $label, 
        'is_recess' => $is_recess,
    ];
    
    $period_map[$period_counter] = [
        'label' => "Period $period_counter ($start_str)",
        'start' => $start_str,
        'end' => $end_str
    ];

    $curr_ts = $end_ts;
    $period_counter++;
    if($period_counter > 25) break; 
}

// 2. DETERMINE VIEW MODE
$view_mode = $_GET['view'] ?? 'my'; 
$target_class_id = $_GET['class_id'] ?? '';

// Dropdown Data
$classes_list = $pdo->query("SELECT id, class_name, form_level FROM classes ORDER BY form_level, class_name")->fetchAll();

// Teacher's Assigned Subjects
$stmt = $pdo->prepare("SELECT subjects FROM users WHERE id = ?");
$stmt->execute([$uid]);
$teacher_subjects_str = $stmt->fetchColumn();
$my_subjects_list = !empty($teacher_subjects_str) ? array_filter(array_map('trim', explode(',', $teacher_subjects_str))) : [];

// Subject Codes
$subjects_all = $pdo->query("SELECT subject_code, subject_name FROM subjects ORDER BY subject_name")->fetchAll();
$subject_map = [];
foreach($subjects_all as $sub) $subject_map[$sub['subject_name']] = $sub['subject_code'];

// Fetch Timetable Data
$mapped_slots = [];
$stats = [];
$total_periods = 0;
$current_class_level = 0;

$sql_base = "SELECT t.*, c.class_name, u.full_name as teacher_name, s.subject_code 
             FROM timetable t 
             LEFT JOIN classes c ON t.class_id = c.id 
             LEFT JOIN users u ON t.teacher_id = u.id 
             LEFT JOIN subjects s ON t.subject = s.subject_name ";

if ($view_mode === 'class' && $target_class_id) {
    foreach($classes_list as $c) { if($c['id'] == $target_class_id) $current_class_level = $c['form_level']; }
    $sql = $sql_base . "WHERE t.class_id = ?";
    $params = [$target_class_id];
} else {
    $sql = $sql_base . "WHERE t.teacher_id = ?";
    $params = [$uid];
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

while($row = $stmt->fetch()) {
    $db_start = substr($row['start_time'], 0, 5);
    $db_end   = substr($row['end_time'], 0, 5);

    $span = 0;
    foreach($time_slots as $p => $ts) {
        if($ts['start'] >= $db_start && $ts['end'] <= $db_end) $span++;
    }
    $row['span'] = ($span > 0) ? $span : 1;
    
    $key = $row['day_of_week'] . '_' . $db_start;
    $mapped_slots[$key] = $row;

    if ($view_mode === 'class') {
        $t_name = $row['teacher_name'] ?: 'Unknown';
        if (!isset($stats[$t_name])) $stats[$t_name] = 0;
        $stats[$t_name] += $row['span'];
    } else {
        $total_periods += $row['span'];
    }
}
if ($view_mode === 'class') arsort($stats);

// Fetch Pending Requests
$my_requests = $pdo->prepare("SELECT tr.*, c.class_name FROM timetable_requests tr LEFT JOIN classes c ON tr.class_id = c.id WHERE tr.teacher_id = ? AND tr.status = 'pending' ORDER BY tr.created_at DESC");
$my_requests->execute([$uid]);
$pending_reqs = $my_requests->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>My Timetable</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
       :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }
        .app-header { background: var(--primary-grad); padding: 30px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; text-align: center; }
        .floating-card { background: white; margin: -60px 20px 20px 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        .tt-container { overflow-x: auto; margin-top: 10px; padding-bottom: 10px; }
        .tt-table { width: 100%; min-width: 900px; border-collapse: separate; border-spacing: 4px; }
        .tt-head-cell { text-align: center; background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 8px 4px; font-size: 0.7rem; font-weight: 700; color: #64748b; line-height: 1.3; min-width: 65px; }
        
        /* FIXED: Force Upright Text (Stacking) */
        .tt-day-cell { 
            background: #e0f2fe; 
            color: #0284c7; 
            border-radius: 12px; 
            writing-mode: vertical-lr; /* Vertical column */
            text-orientation: upright; /* Letters stand straight up */
            text-align: center; 
            padding: 5px 2px;
            font-weight: 800; 
            text-transform: uppercase; 
            font-size: 0.65rem; /* Slightly smaller to fit stacking */
            width: 40px; 
            letter-spacing: -1px; /* Tighter spacing for vertical stack */
        }

        .tt-cell { background: white; border: 1px dashed #cbd5e1; border-radius: 10px; height: 75px; vertical-align: middle; text-align: center; font-size: 0.75rem; color: #94a3b8; position: relative; transition: 0.2s; }
        .edit-mode .tt-cell:not(.filled):not(.recess):not(.closed) { cursor: pointer; background: #f8fafc; }
        .tt-cell.filled { background: #f3e8ff; border: 1px solid #d8b4fe; color: #6b21a8; border-left: 4px solid #9333ea; }
        .tt-cell.recess { background: #f0fdf4; border: 1px solid #bbf7d0; color: #166534; pointer-events: none; }
        .tt-cell.closed { background: #f1f5f9; border: 1px solid #e2e8f0; cursor: default; opacity: 0.5; pointer-events: none; }
        .cell-content { display: flex; flex-direction: column; justify-content: center; height: 100%; padding: 4px; overflow: hidden; }
        .cell-subj { font-weight: 800; font-size: 0.8rem; margin-bottom: 2px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
        .cell-meta { font-size: 0.65rem; opacity: 0.8; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
        .summary-row { display: flex; justify-content: space-between; padding: 10px 15px; border-bottom: 1px solid #f1f5f9; align-items: center; }
        .load-badge { background: #f1f5f9; color: #475569; font-weight: 700; border-radius: 8px; padding: 4px 10px; font-size: 0.75rem; }
        .form-switch .form-check-input { width: 3em; height: 1.5em; cursor: pointer; }
        .form-switch .form-check-input:checked { background-color: #8B5CF6; border-color: #8B5CF6; }
        .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: white; padding: 10px 30px 18px 30px; display: flex; justify-content: space-between; border-radius: 30px 30px 0 0; box-shadow: 0 -5px 20px rgba(0,0,0,0.05); z-index: 100; }
        .nav-btn { display: flex; flex-direction: column; align-items: center; color: #94a3b8; text-decoration: none; font-size: 0.7rem; font-weight: 600; }
        .nav-btn.active { color: #8B5CF6; }
        .nav-btn i { font-size: 1.4rem; margin-bottom: 4px; }
        
        .request-card-header { cursor: pointer; transition: 0.2s; }
        .request-card-header:hover { background-color: rgba(255, 193, 7, 0.2) !important; }
        .scrollable-list { max-height: 200px; overflow-y: auto; scrollbar-width: thin; }
    </style>
</head>
<body>
    <div class="app-header"><div class="d-flex justify-content-between align-items-center mb-3"><a href="dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a><div class="fw-bold fs-5">Timetable</div><div style="width: 24px;"></div></div><div class="opacity-75 small">Weekly Schedule</div></div>
    <div class="floating-card">
        
        <?php if(!empty($pending_reqs)): ?>
        <div class="card border-warning border-2 shadow-sm rounded-4 mb-3 overflow-hidden">
            <div class="card-header bg-warning bg-opacity-10 text-dark fw-bold border-0 d-flex justify-content-between align-items-center request-card-header" data-bs-toggle="collapse" data-bs-target="#requestList" aria-expanded="false">
                <span>
                    <i class="bi bi-bell-fill me-2 text-warning"></i>
                    Pending Requests 
                    <span class="badge bg-dark rounded-pill ms-1"><?= count($pending_reqs) ?></span>
                </span>
                <i class="bi bi-chevron-down small"></i>
            </div>
            <div id="requestList" class="collapse show">
                <div class="list-group list-group-flush scrollable-list">
                    <?php foreach($pending_reqs as $req): 
                        $rtype = $req['request_type'] == 'add' ? '<span class="badge bg-success" style="font-size:0.6rem">ADD</span>' : '<span class="badge bg-danger" style="font-size:0.6rem">DEL</span>';
                    ?>
                    <div class="list-group-item d-flex justify-content-between align-items-center py-2">
                        <div style="line-height: 1.2;">
                            <div class="fw-bold text-dark small"><?= $rtype ?> <?= htmlspecialchars($req['subject']) ?></div>
                            <small class="text-muted" style="font-size:0.7rem">
                                <?= $days_map[$req['day_of_week']] ?>, <?= substr($req['start_time'],0,5) ?> • <?= htmlspecialchars($req['class_name']) ?>
                            </small>
                        </div>
                        <i class="bi bi-clock-history text-muted opacity-50"></i>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <form method="GET" class="row g-2 align-items-center mb-3">
            <div class="col-4"><select name="view" class="form-select form-select-sm fw-bold border-0 bg-light rounded-pill" onchange="if(this.value=='my') { this.form.class_id.value=''; } this.form.submit()"><option value="my" <?= $view_mode=='my'?'selected':'' ?>>My Schedule</option><option value="class" <?= $view_mode=='class'?'selected':'' ?>>Class View</option></select></div>
            <div class="col-8">
                <?php if($view_mode === 'class'): ?><select name="class_id" class="form-select form-select-sm fw-bold border-0 bg-light rounded-pill" onchange="this.form.submit()"><option value="">Select Class...</option><?php foreach($classes_list as $c): ?><option value="<?= $c['id'] ?>" <?= $target_class_id==$c['id']?'selected':'' ?>><?= htmlspecialchars($c['class_name']) ?></option><?php endforeach; ?></select>
                <?php else: ?><div class="d-flex justify-content-end align-items-center pt-1"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" id="editToggle" onchange="toggleEditMode()"><label class="form-check-label fw-bold small ms-2 text-muted" for="editToggle">Enable Editing</label></div></div><?php endif; ?>
            </div>
        </form>
    </div>
    <div class="px-3 pb-4">
        <?php if($view_mode === 'class' && empty($target_class_id)): ?><div class="text-center py-5 text-muted small opacity-50"><i class="bi bi-search display-1"></i><br>Please select a class.</div><?php else: ?>
            <div class="tt-container" id="gridContainer"><table class="tt-table"><thead><tr><th></th><?php foreach($time_slots as $ts): ?><td class="tt-head-cell"><?= $ts['label'] ?></td><?php endforeach; ?></tr></thead><tbody>
                <?php foreach($display_days as $day): $day_end = $day_end_times[$day]; ?>
                <tr>
                    <td class="tt-day-cell"><?= $days_map[$day] ?></td>
                    <?php 
                        $i = 1;
                        while($i <= count($time_slots)):
                            $ts = $time_slots[$i];
                            if ($ts['start'] >= $day_end) { echo "<td class='tt-cell closed'></td>"; $i++; continue; }
                            
                            $is_active_recess = false;
                            if ($view_mode === 'class') {
                                $is_upper = in_array($current_class_level, $upper_forms);
                                $actual_recess = $is_upper ? $s_recess_upper : $s_recess_lower;
                                if ($i == $actual_recess) $is_active_recess = true;
                            } else { if ($i == $s_recess_lower) $is_active_recess = true; }

                            if ($is_active_recess) { echo "<td class='tt-cell recess'><div class='cell-content'><i class='bi bi-cup-hot mb-1'></i>RE</div></td>"; $i++; continue; }

                            $key = $day . '_' . $ts['start'];
                            $slot = $mapped_slots[$key] ?? null;
                            $data = $slot ? json_encode($slot) : null;
                            
                            $colspan = ($slot && isset($slot['span']) && $slot['span'] > 1) ? $slot['span'] : 1;
                            $display_code = $slot ? ($slot['subject_code'] ?: substr($slot['subject'],0,3)) : '';
                            
                            $dataAttr = $slot ? "onclick='handleSlotClick(".json_encode($slot).", $i)'" : "onclick=\"handleEmptyClick($day, $i)\"";
                    ?>
                        <td class="tt-cell <?= $slot ? 'filled' : '' ?>" colspan="<?= $colspan ?>" <?= $dataAttr ?>>
                            <?php if($slot): ?><div class="cell-content"><div class="cell-subj"><?= htmlspecialchars($display_code) ?></div><div class="cell-meta"><?= ($view_mode === 'class') ? htmlspecialchars($slot['teacher_name']) : htmlspecialchars($slot['class_name']) ?></div></div><?php endif; ?>
                        </td>
                    <?php if($slot) $i += ($colspan - 1); $i++; endwhile; ?>
                </tr>
                <?php endforeach; ?>
            </tbody></table></div>
            
            <div class="mt-4"><button class="btn btn-light w-100 fw-bold d-flex justify-content-between align-items-center py-3 px-3 rounded-4 shadow-sm mb-3" type="button" data-bs-toggle="collapse" data-bs-target="#legendArea"><span><i class="bi bi-info-circle me-2 text-info"></i>Subject Legend</span><i class="bi bi-chevron-down"></i></button><div class="collapse show" id="legendArea"><div class="bg-white p-3 rounded-4 shadow-sm border border-light"><div class="d-flex flex-wrap gap-2"><?php foreach($subject_map as $name => $code): ?><span class="badge bg-light text-dark border"><strong class="text-primary"><?= htmlspecialchars($code ?: substr($name,0,3)) ?></strong> : <?= htmlspecialchars($name) ?></span><?php endforeach; ?></div></div></div></div>
            <div class="mt-3">
                <?php if($view_mode === 'my'): ?>
                    <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
                        <div class="card-body p-4 text-center">
                            <h6 class="text-muted text-uppercase small fw-bold mb-2">My Total Load</h6>
                            <div class="display-4 fw-bold text-primary mb-0"><?= $total_periods ?></div>
                            <div class="small text-muted">periods per week</div>
                        </div>
                    </div>
                <?php elseif(!empty($stats)): ?>
                    <h6 class="fw-bold text-muted ps-2 mb-3 small text-uppercase">Teacher Workload (This Class)</h6>
                    <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
                        <?php foreach($stats as $t_name => $count): ?>
                            <div class="summary-row">
                                <div class="fw-bold text-dark small"><?= htmlspecialchars($t_name) ?></div>
                                <span class="load-badge"><?= $count ?> Periods</span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <div class="modal fade" id="slotModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content border-0 shadow rounded-4"><div class="modal-header border-0 bg-primary text-white py-3"><h6 class="modal-title fw-bold" id="modalTitle">Request Slot</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><form><input type="hidden" name="slot_id" id="inp_id"><div class="modal-body p-4"><div class="row g-2 mb-3"><div class="col-6"><label class="small fw-bold text-muted">Day</label><select name="day_of_week" id="inp_day" class="form-select bg-light fw-bold" required><?php foreach($days_map as $k=>$v): ?><option value="<?=$k?>"><?=$v?></option><?php endforeach; ?></select></div><div class="col-6"><label class="small fw-bold text-muted">Start Period</label><select name="period_num" id="inp_period" class="form-select bg-light fw-bold" required><?php foreach($period_map as $p_num => $p_data): ?><option value="<?= $p_num ?>"><?= $p_data['label'] ?></option><?php endforeach; ?></select></div></div><div class="mb-3"><label class="small fw-bold text-muted">Duration</label><select name="duration" id="inp_duration" class="form-select"><option value="1">1 Period</option><option value="2">2 Periods</option><option value="3">3 Periods</option><option value="4">4 Periods</option></select></div><div class="mb-3"><label class="small fw-bold text-muted">Class</label><select name="class_id" id="inp_class" class="form-select" required><option value="">Select...</option><?php foreach($classes_list as $c): ?><option value="<?=$c['id']?>"><?=$c['class_name']?></option><?php endforeach; ?></select></div><div class="mb-3"><label class="small fw-bold text-muted">Subject</label><select name="subject" id="inp_subject" class="form-select" required><option value="">Select...</option><?php if(empty($my_subjects_list)): ?><option value="" disabled>No subjects assigned.</option><?php else: foreach($my_subjects_list as $s): ?><option value="<?= htmlspecialchars($s) ?>"><?= htmlspecialchars($s) ?></option><?php endforeach; endif; ?></select></div><div class="alert alert-warning small border-0"><i class="bi bi-info-circle me-1"></i> Changes will be submitted for admin approval.</div></div><div class="modal-footer border-0 pt-0"><button type="button" id="btnDelete" class="btn btn-light text-danger fw-bold rounded-pill">Request Delete</button><button type="submit" class="btn btn-primary fw-bold rounded-pill px-4 flex-grow-1">Submit Request</button></div></form></div></div></div>
    
    <?php include 'menu.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let editMode = false;
        const modal = new bootstrap.Modal(document.getElementById('slotModal'));

        function checkEditMode() {
            if (localStorage.getItem('tt_edit_mode') === 'true') {
                document.getElementById('editToggle').checked = true;
                toggleEditMode();
            }
        }
        function toggleEditMode() { 
            editMode = document.getElementById('editToggle').checked; 
            localStorage.setItem('tt_edit_mode', editMode);
            const container = document.getElementById('gridContainer'); 
            if(editMode) container.classList.add('edit-mode'); 
            else container.classList.remove('edit-mode'); 
        }

        document.addEventListener('DOMContentLoaded', checkEditMode);

        // --- API HANDLER ---
        async function submitRequest(action, formData) {
            formData.append('action', action);
            try {
                const res = await fetch('api_timetable.php', { method: 'POST', body: formData });
                
                // Check if response is valid JSON
                const text = await res.text();
                let data;
                try {
                    data = JSON.parse(text);
                } catch (e) {
                    console.error("Server returned non-JSON:", text);
                    alert("System Error: Server returned invalid data.\n\n" + text.substring(0, 100) + "...");
                    return;
                }

                if(data.success) {
                    alert("? " + data.message);
                    location.reload();
                } else {
                    alert("? " + (data.message || "Unknown error"));
                }
            } catch(e) {
                console.error(e); 
                alert("Network or System Error. Check console for details.");
            }
        }

        document.querySelector('form:not([method="GET"])').addEventListener('submit', function(e) {
            e.preventDefault();
            submitRequest('teacher_request_slot', new FormData(this));
        });

        document.getElementById('btnDelete').addEventListener('click', function() {
            if(!confirm("Request to delete this slot?")) return;
            const fd = new FormData();
            fd.append('slot_id', document.getElementById('inp_id').value);
            submitRequest('teacher_request_delete', fd);
        });

        function handleEmptyClick(day, periodNum) { 
            if (!editMode) return; 
            document.getElementById('modalTitle').innerText = "Request New Slot"; 
            document.getElementById('inp_id').value = ""; 
            document.getElementById('inp_day').value = day; 
            document.getElementById('inp_period').value = periodNum; 
            document.getElementById('inp_duration').value = "1"; 
            if(fClass) document.getElementById('inp_class').value = fClass;
            document.getElementById('btnDelete').style.display = 'none'; 
            modal.show(); 
        }
        function handleSlotClick(slot, periodNum) { 
            if (!editMode) return; 
            document.getElementById('modalTitle').innerText = "Edit Slot Request"; 
            document.getElementById('inp_id').value = slot.id; 
            document.getElementById('inp_day').value = slot.day_of_week; 
            document.getElementById('inp_period').value = periodNum; 
            document.getElementById('inp_duration').value = slot.span || 1; 
            document.getElementById('inp_class').value = slot.class_id; 
            document.getElementById('inp_subject').value = slot.subject; 
            document.getElementById('btnDelete').style.display = 'block'; 
            modal.show(); 
        }
        
        const fClass = "<?= $target_class_id ?>";
    </script>
</body>
</html>