<?php

declare(strict_types=1);



session_start();

require_once '../../config.php';

requireModule('timetable');

require_once __DIR__ . '/helpers.php';



if (!isset($_SESSION['user_id'])) {

    header('Location: ../../login.php');

    exit;

}



$conn = getDBConnection();

if (!$conn instanceof mysqli) {

    http_response_code(500);

    exit('Database connection failed.');

}



// For tutor role: pre-select their own staff record

$auto_teacher_id = 0;

if (($_SESSION['role'] ?? '') === 'tutor' && isset($_SESSION['user_id'])) {

    $atStmt = $conn->prepare("SELECT id FROM staff WHERE user_id = ? LIMIT 1");

    $atStmt->bind_param('i', $_SESSION['user_id']);

    $atStmt->execute();

    $atRow = $atStmt->get_result()->fetch_assoc();

    $atStmt->close();

    $auto_teacher_id = (int) ($atRow['id'] ?? 0);

}



$teachers    = timetableGetTeachers($conn);

$periods     = timetableGetPeriods($conn);

$terms       = timetableTerms();

$defaultTerm = timetableGetCurrentTerm($conn);

$defaultYear = timetableGetCurrentYear($conn);

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Teacher Timetable View</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <link rel="stylesheet" href="../../css/style.css">

    <style>

        .tt td,.tt th{vertical-align:top;min-width:150px}

        .tt thead th{white-space:nowrap;text-align:center}

        .break-row td{background:#f1f3f5;font-weight:700;text-align:center}

    </style>

</head>

<body>

<div class="wrapper">

    <nav id="sidebar" class="sidebar">

        <?php echo buildSidebar('modules/timetable/' . basename($_SERVER['PHP_SELF'])); ?>

        </nav>



    <div id="content" class="content">

        <header class="top-navbar d-flex justify-content-between align-items-center flex-wrap gap-2">

            <div>

                <h4 class="mb-1">Teacher Timetable View</h4>

                <div class="text-muted small">Weekly teaching load and per-day summary for a selected teacher.</div>

            </div>

            <button class="btn btn-outline-success" id="printBtn"><i class="fas fa-print me-1"></i>Print My Timetable</button>

        </header>



        <main class="container-fluid py-4">

            <div class="card shadow-sm border-0 mb-4">

                <div class="card-body">

                    <div class="row g-2 align-items-end">

                        <div class="col-md-4" <?= $auto_teacher_id ? 'style="display:none"' : '' ?>>

                            <label class="form-label">Teacher</label>

                            <select id="teacher_id" class="form-select">

                                <option value="">Select teacher</option>

                                <?php foreach ($teachers as $teacher): ?>

                                    <option value="<?= (int) $teacher['id'] ?>" <?= ($auto_teacher_id === (int) $teacher['id']) ? 'selected' : '' ?>><?= htmlspecialchars($teacher['full_name']) ?></option>

                                <?php endforeach; ?>

                            </select>

                        </div>

                        <div class="col-md-2">

                            <label class="form-label">Term</label>

                            <select id="term" class="form-select">

                                <?php foreach ($terms as $term): ?>

                                    <option value="<?= htmlspecialchars($term) ?>" <?= $term === $defaultTerm ? 'selected' : '' ?>><?= htmlspecialchars($term) ?></option>

                                <?php endforeach; ?>

                            </select>

                        </div>

                        <div class="col-md-2">

                            <label class="form-label">Academic Year</label>

                            <input type="text" id="academic_year" class="form-control" value="<?= htmlspecialchars($defaultYear) ?>">

                        </div>

                        <div class="col-md-2">

                            <button class="btn btn-primary w-100" id="loadBtn"><i class="fas fa-sync-alt me-1"></i>Load</button>

                        </div>

                    </div>

                </div>

            </div>



            <div class="card shadow-sm border-0 mb-4">

                <div class="card-body">

                    <div class="table-responsive">

                        <table class="table table-bordered tt mb-0">

                            <thead class="table-light">

                                <tr><th style="width:210px">Period</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>

                            </thead>

                            <tbody id="teacherBody">

                                <tr><td colspan="7" class="text-center py-5 text-muted">Select a teacher and load the timetable.</td></tr>

                            </tbody>

                        </table>

                    </div>

                </div>

            </div>



            <div class="card shadow-sm border-0">

                <div class="card-body">

                    <h6 class="mb-3">Teaching Summary</h6>

                    <div class="row g-2 align-items-stretch" id="summaryRow"></div>

                </div>

            </div>

        </main>

    </div>

</div>



<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>

const PERIODS = <?= json_encode($periods, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

const DAYS = ['Mon','Tue','Wed','Thu','Fri','Sat'];

let slots = [];

const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));



const TV_PERIOD_META = <?php echo json_encode(timetablePeriodTypes($conn), JSON_UNESCAPED_UNICODE); ?>;

const TV_LESSON_CAPABLE = <?php echo json_encode(timetableLessonCapableTypes()); ?>;



function tvGetPeriodType(p) {

    if (p.period_type && p.period_type !== 'teaching') return p.period_type;

    const n = (p.period_name || '').toLowerCase();

    if (/\bnap\b/.test(n))             return 'nap';

    if (/circle/.test(n))              return 'circle_time';

    if (/assembly/.test(n))            return 'assembly';

    if (/\blunch\b|launch/.test(n))    return 'lunch';

    if (/recess/.test(n))              return 'recess';

    if (/arrival|settling|reporting/.test(n)) return 'arrival';

    if (/routine/.test(n))             return 'routines';

    if (/silent/.test(n))              return 'silent_hour';

    if (/worship/.test(n))             return 'worship';

    if (/closing/.test(n))             return 'closing_time';

    if (Number(p.is_break) === 1)      return 'break';

    return 'teaching';

}



function renderGrid() {

    const body = document.getElementById('teacherBody');

    body.innerHTML = PERIODS.map((p) => {

        const left = `<div class="fw-semibold">${esc(p.period_name)}</div><div class="small text-muted">${String(p.start_time).slice(0,5)} - ${String(p.end_time).slice(0,5)}</div>`;

        const pType = tvGetPeriodType(p);

        const meta = TV_LESSON_CAPABLE.includes(pType) ? null : TV_PERIOD_META[pType];

        if (meta && meta.span) return `<tr class="break-row"><td>${left}</td><td colspan="6">${meta.icon} ${meta.label}</td></tr>`;

        const cells = DAYS.map((day) => {

            const slot = slots.find((s) => Number(s.period_id) === Number(p.id) && s.day_of_week === day);

            if (!slot) {

                if (meta) return `<td class="text-center text-muted small">${meta.icon} ${meta.label}</td>`;

                return '<td class="text-center text-muted">-</td>';

            }

            return `<td><div class="fw-semibold">${esc(slot.subject_name || '')}</div><div class="small">${esc(slot.class_name || '')}</div><div class="small text-muted">${esc(slot.room || 'No room')}</div></td>`;

        }).join('');

        return `<tr><td>${left}</td>${cells}</tr>`;

    }).join('');

}



function renderSummary() {

    const summary = DAYS.map((day) => ({day, count: slots.filter((s) => s.day_of_week === day).length}));

    const weekly = summary.reduce((sum, item) => sum + item.count, 0);

    document.getElementById('summaryRow').innerHTML = summary.map((item) => `<div class="col-md-2"><div class="border rounded p-3 text-center"><div class="small text-muted">${item.day}</div><div class="fw-bold">${item.count}</div></div></div>`).join('') + `<div class="col-md-2"><div class="border rounded p-3 text-center bg-light"><div class="small text-muted">Week Total</div><div class="fw-bold">${weekly}</div></div></div>`;

}



async function loadTeacherTimetable() {

    const teacherId = document.getElementById('teacher_id').value;

    const term = document.getElementById('term').value;

    const academicYear = document.getElementById('academic_year').value;

    if (!teacherId) { return; }

    const response = await fetch('ajax/get_teacher_slots.php', {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:new URLSearchParams({teacher_id:teacherId, term:term, academic_year:academicYear})});

    slots = await response.json();

    renderGrid();

    renderSummary();

}



document.getElementById('loadBtn').addEventListener('click', loadTeacherTimetable);



// Auto-load for tutor role

<?php if ($auto_teacher_id): ?>

document.addEventListener('DOMContentLoaded', () => loadTeacherTimetable());

<?php endif; ?>

document.getElementById('printBtn').addEventListener('click', () => {

    const teacherId = document.getElementById('teacher_id').value;

    if (!teacherId) { return; }

    const params = new URLSearchParams({teacher_id:teacherId, term:document.getElementById('term').value, academic_year:document.getElementById('academic_year').value});

    window.open(`print.php?${params.toString()}`, '_blank');

});

</script>

</body>

</html>

