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

// --- LIVE POLLING ENDPOINT ---
if (isset($_GET['action']) && $_GET['action'] === 'poll_updates') {
    header('Content-Type: application/json');
    $count = $pdo->query("SELECT COUNT(*) FROM timetable_requests WHERE status = 'pending'")->fetchColumn();
    echo json_encode(['pending_count' => $count]);
    exit;
}

// 1. PERMISSION & SETTINGS
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
if (empty(array_intersect($user_roles, ['admin', 'timetable_coord', 'principal', 'assistant']))) {
    header("Location: dashboard.php"); exit;
}

// FETCH 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));
$days_count     = intval(getSetting('school_days_count', 5));

$upper_forms = [4, 5, 6];

$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 = intval(getSetting('week_start_day', 1)) + $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) {
    $duration = ($period_counter == $s_recess_lower || $period_counter == $s_recess_upper) ? $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
    ];
    $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; 
}

// 3. FETCH DATA
$filter_class = $_GET['f_class'] ?? '';
$filter_teacher = $_GET['f_teacher'] ?? '';

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

// --- UPDATED: Fetch 'subjects' column (matches profile.php) ---
$teachers = $pdo->query("SELECT id, full_name, subjects FROM users WHERE role LIKE '%teacher%' ORDER BY full_name")->fetchAll();

$subjects = $pdo->query("SELECT subject_code, subject_name, type FROM subjects ORDER BY subject_name")->fetchAll();

$req_sql = "SELECT tr.*, u.full_name as teacher_name, c.class_name FROM timetable_requests tr JOIN users u ON tr.teacher_id = u.id JOIN classes c ON tr.class_id = c.id WHERE tr.status = 'pending' ORDER BY tr.created_at DESC";
$pending_requests = $pdo->query($req_sql)->fetchAll();

// Map Subject Codes
$subject_map = [];
foreach($subjects as $sub) $subject_map[$sub['subject_name']] = $sub['subject_code'];

$mapped_slots = [];
$current_class_level = 0;

if ($filter_class || $filter_teacher) {
    if ($filter_class) {
        foreach($classes as $c) { if($c['id'] == $filter_class) $current_class_level = $c['form_level']; }
    }

    $sql = "SELECT t.*, c.class_name, u.full_name as teacher_name, s.subject_code, s.type as subject_type
            FROM timetable t 
            JOIN classes c ON t.class_id = c.id 
            JOIN users u ON t.teacher_id = u.id 
            LEFT JOIN subjects s ON t.subject = s.subject_name 
            WHERE 1=1";
    
    $params = [];
    if ($filter_class) { $sql .= " AND t.class_id = ?"; $params[] = $filter_class; }
    if ($filter_teacher) { $sql .= " AND t.teacher_id = ?"; $params[] = $filter_teacher; }
    
    $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;
    }
}

// 4. WORKLOAD CALCULATION
$workload_sql = "SELECT u.full_name, 
                 ROUND(COALESCE(SUM(TIMESTAMPDIFF(MINUTE, t.start_time, t.end_time)), 0) / ?) as total_periods 
                 FROM users u 
                 LEFT JOIN timetable t ON u.id = t.teacher_id 
                 WHERE u.role LIKE '%teacher%' 
                 GROUP BY u.id 
                 ORDER BY total_periods DESC, u.full_name ASC";

$stmt = $pdo->prepare($workload_sql);
$stmt->execute([$s_dur]); 
$workload_data = $stmt->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>Manage 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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.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: 20px; 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; }
        .tt-day-cell { background: #e0f2fe; color: #0284c7; border-radius: 12px; writing-mode: vertical-lr; text-align: center; padding: 10px 5px; font-weight: 800; text-transform: uppercase; font-size: 0.7rem; transform: rotate(180deg); width: 40px; }
        
        .tt-cell { 
            background: white; border: 1px dashed #cbd5e1; border-radius: 10px; height: 85px; 
            vertical-align: top; padding: 3px; font-size: 0.75rem; color: #94a3b8; 
            cursor: pointer; transition: 0.2s; position: relative;
        }
        .tt-cell:hover { background: #f8fafc; border-color: #94a3b8; }
        .tt-cell.recess { background: #f0fdf4; border: 1px solid #bbf7d0; color: #166534; pointer-events: none; vertical-align: middle; text-align: center; }
        .tt-cell.closed { background: #f1f5f9; border: 1px solid #e2e8f0; cursor: default; opacity: 0.5; pointer-events: none; }
        
        .slot-badge {
            display: block; font-size: 0.7rem; padding: 4px 6px; margin-bottom: 3px;
            border-radius: 6px; cursor: pointer; text-align: left;
            overflow: hidden; white-space: nowrap; text-overflow: ellipsis;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05); border: 1px solid rgba(0,0,0,0.05);
        }
        .slot-core { background: #f3e8ff; color: #6b21a8; border-left: 3px solid #9333ea; }
        .slot-elective { background: #fce7f3; color: #be185d; border-left: 3px solid #db2777; }
        .slot-badge:active { transform: scale(0.98); }
        .cell-meta { font-size: 0.65rem; opacity: 0.8; }
        
        .workload-row { display: flex; justify-content: space-between; padding: 10px 15px; border-bottom: 1px solid #f1f5f9; transition: 0.1s; }
        .workload-row:hover { background: #f8f9fd; }
        .load-badge { font-weight: 800; font-size: 0.8rem; padding: 4px 10px; border-radius: 8px; background: #f1f5f9; color: #475569; }
       /* 
        .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; } */
        #liveBadge { display: none; position: fixed; top: 120px; right: 20px; z-index: 1050; box-shadow: 0 10px 20px rgba(0,0,0,0.2); }
    </style>
</head>
<body>
    <div class="app-header"><div class="d-flex justify-content-between align-items-center mb-3"><a href="admin_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">Manage Schedules</div></div>
    
    <a href="admin_timetable.php" id="liveBadge" class="btn btn-warning rounded-pill fw-bold animate__animated animate__bounceIn">
        <i class="bi bi-bell-fill me-2"></i> New Request!
    </a>

    <div class="floating-card">
        
        <?php if(!empty($pending_requests)): ?>
        <div class="card border-warning border-2 shadow-sm rounded-4 mb-3">
            <div class="card-header bg-warning bg-opacity-10 text-dark fw-bold border-0"><i class="bi bi-bell-fill me-2"></i>Pending Teacher Requests</div>
            <div class="list-group list-group-flush">
                <?php foreach($pending_requests as $req): 
                    $rtype = $req['request_type'] == 'add' ? '<span class="badge bg-success">Add</span>' : '<span class="badge bg-danger">Del</span>';
                ?>
                <div class="list-group-item d-flex justify-content-between align-items-center">
                    <div>
                        <small class="text-muted d-block"><?= htmlspecialchars($req['teacher_name']) ?> &bull; <?= htmlspecialchars($req['class_name']) ?></small>
                        <div class="fw-bold"><?= $rtype ?> <?= htmlspecialchars($req['subject']) ?></div>
                        <small><?= $days_map[$req['day_of_week']] ?>, <?= substr($req['start_time'],0,5) ?></small>
                    </div>
                    <div class="d-flex gap-1">
                        <button onclick="handleRequest(<?= $req['id'] ?>, 'approve_request')" class="btn btn-success btn-sm rounded-circle"><i class="bi bi-check-lg"></i></button>
                        <button onclick="handleRequest(<?= $req['id'] ?>, 'reject_request')" class="btn btn-outline-danger btn-sm rounded-circle"><i class="bi bi-x-lg"></i></button>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <form method="GET" class="row g-2">
            <div class="col-6"><select name="f_class" class="form-select fw-bold bg-light border-0" onchange="document.getElementsByName('f_teacher')[0].value=''; this.form.submit()"><option value="">Select Class...</option><?php foreach($classes as $c): ?><option value="<?= $c['id'] ?>" <?= $filter_class==$c['id']?'selected':'' ?>><?= htmlspecialchars($c['class_name']) ?></option><?php endforeach; ?></select></div>
            <div class="col-6"><select name="f_teacher" class="form-select fw-bold bg-light border-0" onchange="document.getElementsByName('f_class')[0].value=''; this.form.submit()"><option value="">Select Teacher...</option><?php foreach($teachers as $t): ?><option value="<?= $t['id'] ?>" <?= $filter_teacher==$t['id']?'selected':'' ?>><?= htmlspecialchars($t['full_name']) ?></option><?php endforeach; ?></select></div>
        </form>
    </div>
    
    <div class="px-3 pb-4">
        <?php if(empty($filter_class) && empty($filter_teacher)): ?>
            <div class="text-center py-5 text-muted small opacity-50"><i class="bi bi-grid-3x3-gap display-1"></i><br>Select target to view grid.</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 ($filter_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'><i class='bi bi-cup-hot me-1'></i>RE</td>"; $i++; continue; }

                            $key = $day . '_' . $ts['start'];
                            $slots_in_cell = $mapped_slots[$key] ?? [];
                            
                            $colspan = 1;
                            foreach($slots_in_cell as $s) $colspan = max($colspan, $s['span']);
                            
                            echo "<td class='tt-cell' colspan='$colspan' onclick=\"openAdd($day, $i)\">";
                            
                            if (!empty($slots_in_cell)) {
                                foreach($slots_in_cell as $slot) {
                                    $json = htmlspecialchars(json_encode($slot), ENT_QUOTES, 'UTF-8');
                                    $badge_class = ($slot['subject_type'] === 'elective') ? 'slot-elective' : 'slot-core';
                                    $display_code = $slot['subject_code'] ?: substr($slot['subject'],0,8);
                                    $meta = $filter_class ? explode(' ', trim($slot['teacher_name']))[0] : $slot['class_name'];
                                    
                                    echo "<div class='slot-badge $badge_class' onclick='event.stopPropagation(); openEdit($json, $i)'>";
                                    echo "<strong>$display_code</strong> <span class='cell-meta'>$meta</span>";
                                    echo "</div>";
                                }
                            }
                            echo "</td>";
                            
                            $i += ($colspan > 1) ? $colspan : 1; 
                        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">
                <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" type="button" data-bs-toggle="collapse" data-bs-target="#workloadTable">
                    <span><i class="bi bi-bar-chart-line-fill me-2 text-primary"></i>Teacher Workload</span>
                    <i class="bi bi-chevron-down"></i>
                </button>
                <div class="collapse mt-2" id="workloadTable">
                    <div class="card border-0 shadow-sm rounded-4 overflow-hidden p-2">
                        <div class="mb-2">
                            <input type="text" id="workloadSearch" class="form-control form-control-sm rounded-pill bg-light border-0 px-3" placeholder="?? Search teacher..." onkeyup="filterWorkload()">
                        </div>
                        <div id="workloadList" style="max-height: 400px; overflow-y: auto;">
                            <?php foreach($workload_data as $wd): ?>
                            <div class="workload-row rounded-3">
                                <div class="fw-bold text-dark small teacher-name"><?= htmlspecialchars($wd['full_name']) ?></div>
                                <div class="load-badge"><?= intval($wd['total_periods']) ?> Periods</div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </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">Edit Slot</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><form method="POST"><input type="hidden" name="action" value="admin_save_slot"><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">Subject</label><select name="subject" id="inp_subject" class="form-select" required><option value="">Select...</option><?php foreach($subjects as $sub): ?><option value="<?=$sub['subject_name']?>"><?=$sub['subject_name']?></option><?php endforeach; ?></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><?php foreach($classes 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">Teacher</label><select name="teacher_id" id="inp_teacher" class="form-select" required><?php foreach($teachers as $t): ?><option value="<?=$t['id']?>"><?=$t['full_name']?></option><?php endforeach; ?></select></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 shadow-sm">Delete</button><button type="submit" class="btn btn-primary fw-bold rounded-pill px-4 flex-grow-1 shadow-sm">Save</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>
        const modal = new bootstrap.Modal(document.getElementById('slotModal'));
        const fClass = "<?= $filter_class ?>";
        const fTeacher = "<?= $filter_teacher ?>";
        
        // --- 1. DATA PREP (Subjects from Profile) ---
        const teacherSubjects = {};
        const allTeachers = [];

        <?php 
            foreach($teachers as $t) {
                // Read from 'subjects' column (comma separated)
                $subs = array_map('trim', explode(',', $t['subjects'] ?? ''));
                echo "teacherSubjects[{$t['id']}] = " . json_encode($subs) . ";\n";
                echo "allTeachers.push({id: {$t['id']}, name: " . json_encode($t['full_name']) . "});\n";
            }
        ?>

        // --- 2. SMART FILTER (Expert Logic) ---
        document.getElementById('inp_subject').addEventListener('change', function() {
            const selectedSubj = this.value;
            const teacherSelect = document.getElementById('inp_teacher');
            const currentVal = teacherSelect.value;
            
            teacherSelect.innerHTML = '<option value="">Select...</option>';
            
            const experts = [];
            const others = [];

            // Sort: Check if teacher has this subject in their profile
            allTeachers.forEach(t => {
                const mySubjects = teacherSubjects[t.id] || [];
                if (selectedSubj && mySubjects.includes(selectedSubj)) {
                    experts.push(t);
                } else {
                    others.push(t);
                }
            });

            // Add Experts (Bold Blue Star)
            experts.forEach(t => {
                const opt = document.createElement('option');
                opt.value = t.id;
                opt.innerHTML = "&#9733; " + t.name;
                opt.style.fontWeight = "bold";
                opt.style.color = "#0d6efd"; 
                teacherSelect.appendChild(opt);
            });

            // Separator
            if (experts.length > 0 && others.length > 0) {
                const sep = document.createElement('option');
                sep.disabled = true;
                sep.innerText = "--------------";
                teacherSelect.appendChild(sep);
            }

            // Add Others
            others.forEach(t => {
                const opt = document.createElement('option');
                opt.value = t.id;
                opt.innerText = t.name;
                teacherSelect.appendChild(opt);
            });

            if(currentVal) teacherSelect.value = currentVal;
        });

        // --- EXISTING JS ---
        function filterWorkload() {
            const input = document.getElementById('workloadSearch').value.toLowerCase();
            const rows = document.querySelectorAll('.workload-row');
            rows.forEach(row => {
                const name = row.querySelector('.teacher-name').innerText.toLowerCase();
                row.style.display = name.includes(input) ? '' : 'none';
            });
        }

        async function callApi(action, formData) {
            formData.append('action', action);
            try {
                const res = await fetch('api_timetable.php', { method: 'POST', body: formData });
                const data = await res.json();
                if (data.success) {
                    alert("? " + data.message);
                    location.reload(); 
                } else {
                    alert("? " + data.message);
                }
            } catch (e) { console.error(e); alert("System Error."); }
        }

        document.querySelector('#slotModal form').addEventListener('submit', function(e) {
            e.preventDefault();
            callApi('admin_save_slot', new FormData(this));
        });

        document.getElementById('btnDelete').addEventListener('click', function(e) {
            e.preventDefault();
            if(!confirm("Delete this slot?")) return;
            const fd = new FormData();
            fd.append('slot_id', document.getElementById('inp_id').value);
            callApi('admin_delete_slot', fd);
        });

        function handleRequest(id, action) {
            const fd = new FormData();
            fd.append('request_id', id);
            callApi(action, fd);
        }

        function openAdd(day, periodNum) {
            document.getElementById('modalTitle').innerText = "Add 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;
            if(fTeacher) document.getElementById('inp_teacher').value = fTeacher;
            
            document.getElementById('inp_subject').value = "";
            document.getElementById('inp_subject').dispatchEvent(new Event('change'));

            document.getElementById('btnDelete').style.display = 'none';
            modal.show();
        }
        function openEdit(slot, periodNum) {
            document.getElementById('modalTitle').innerText = "Edit Slot";
            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;
            
            const subjSelect = document.getElementById('inp_subject');
            subjSelect.value = slot.subject;
            subjSelect.dispatchEvent(new Event('change'));

            document.getElementById('inp_teacher').value = slot.teacher_id;
            document.getElementById('btnDelete').style.display = 'block';
            modal.show();
        }

        setInterval(() => {
            fetch('api_timetable.php?action=poll_updates').then(r => r.json()).then(d => {
                if (d && d.pending_count > <?= count($pending_requests) ?>) {
                    const badge = document.getElementById('liveBadge');
                    badge.style.display = 'inline-block';
                    badge.innerHTML = `<i class="bi bi-bell-fill me-2"></i> ${d.pending_count} New Requests!`;
                }
            });
        }, 5000);
    </script>
</body>
</html>