<?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.');

}



$teachers = timetableGetTeachers($conn);

$classes = timetableGetClasses($conn);

$periods = timetableGetPeriods($conn);

$filterDate = trim((string) ($_GET['substitution_date'] ?? ''));

$filterClass = trim((string) ($_GET['class_name'] ?? ''));



$sql = "SELECT tsb.substitution_date, ts.class_name, tp.period_name, s.subject_name,

               ot.full_name AS original_teacher, st.full_name AS substitute_teacher,

               tsb.reason, u.username AS recorded_by, ts.period_id, ts.id AS slot_id

        FROM timetable_substitutions tsb

        INNER JOIN timetable_slots ts ON tsb.slot_id = ts.id

        INNER JOIN timetable_periods tp ON ts.period_id = tp.id

        LEFT JOIN subjects s ON ts.subject_id = s.id

        LEFT JOIN staff ot ON tsb.original_teacher_id = ot.id

        LEFT JOIN staff st ON tsb.substitute_teacher_id = st.id

        LEFT JOIN users u ON tsb.recorded_by = u.id

        WHERE (? = '' OR tsb.substitution_date = ?)

          AND (? = '' OR ts.class_name = ?)

        ORDER BY tsb.substitution_date DESC, tp.order_no ASC";

$stmt = $conn->prepare($sql);

$stmt->bind_param('ssss', $filterDate, $filterDate, $filterClass, $filterClass);

$stmt->execute();

$result = $stmt->get_result();

$rows = [];

while ($row = $result->fetch_assoc()) {

    $rows[] = $row;

}

$stmt->close();

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Timetable Substitutions</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="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css">

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

</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">Substitution Log</h4>

                <div class="text-muted small">Track teacher substitutions against timetable slots.</div>

            </div>

            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#subModal"><i class="fas fa-plus me-1"></i>Add Substitution</button>

        </header>



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

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

                <div class="card-body">

                    <form class="row g-2 align-items-end" method="get">

                        <div class="col-md-3"><label class="form-label">Date</label><input type="date" name="substitution_date" class="form-control" value="<?= htmlspecialchars($filterDate) ?>"></div>

                        <div class="col-md-3"><label class="form-label">Class</label><select name="class_name" class="form-select"><option value="">All classes</option><?php foreach ($classes as $className): ?><option value="<?= htmlspecialchars($className) ?>" <?= $filterClass === $className ? 'selected' : '' ?>><?= htmlspecialchars($className) ?></option><?php endforeach; ?></select></div>

                        <div class="col-md-2"><button class="btn btn-primary w-100"><i class="fas fa-filter me-1"></i>Filter</button></div>

                    </form>

                </div>

            </div>



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

                <div class="card-body">

                    <div class="table-responsive">

                        <table class="table table-striped align-middle" id="subTable">

                            <thead><tr><th>Date</th><th>Class</th><th>Period</th><th>Subject</th><th>Original Teacher</th><th>Substitute</th><th>Reason</th><th>Recorded By</th></tr></thead>

                            <tbody>

                                <?php foreach ($rows as $row): ?>

                                    <tr>

                                        <td><?= htmlspecialchars((string) $row['substitution_date']) ?></td>

                                        <td><?= htmlspecialchars((string) $row['class_name']) ?></td>

                                        <td><?= htmlspecialchars((string) $row['period_name']) ?></td>

                                        <td><?= htmlspecialchars((string) ($row['subject_name'] ?? '')) ?></td>

                                        <td><?= htmlspecialchars((string) ($row['original_teacher'] ?? '')) ?></td>

                                        <td><?= htmlspecialchars((string) ($row['substitute_teacher'] ?? '')) ?></td>

                                        <td><?= htmlspecialchars((string) ($row['reason'] ?? '')) ?></td>

                                        <td><?= htmlspecialchars((string) ($row['recorded_by'] ?? '')) ?></td>

                                    </tr>

                                <?php endforeach; ?>

                            </tbody>

                        </table>

                    </div>

                </div>

            </div>

        </main>

    </div>

</div>



<div class="modal fade" id="subModal" tabindex="-1" aria-hidden="true">

    <div class="modal-dialog">

        <div class="modal-content">

            <form id="subForm">

                <div class="modal-header"><h5 class="modal-title">Add Substitution</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>

                <div class="modal-body">

                    <input type="hidden" name="slot_id" id="slot_id">

                    <div class="mb-3"><label class="form-label">Date</label><input type="date" name="substitution_date" id="substitution_date" class="form-control" value="<?= htmlspecialchars(date('Y-m-d')) ?>" required></div>

                    <div class="mb-3"><label class="form-label">Class</label><select id="class_name" class="form-select" required><option value="">Select class</option><?php foreach ($classes as $className): ?><option value="<?= htmlspecialchars($className) ?>"><?= htmlspecialchars($className) ?></option><?php endforeach; ?></select></div>

                    <div class="mb-3"><label class="form-label">Period</label><select id="period_id" class="form-select" required><option value="">Select period</option><?php foreach ($periods as $period): ?><option value="<?= (int) $period['id'] ?>"><?= htmlspecialchars((string) $period['period_name']) ?></option><?php endforeach; ?></select></div>

                    <div class="mb-3"><label class="form-label">Original Teacher</label><input type="text" id="original_teacher_label" class="form-control" readonly><input type="hidden" name="original_teacher_id" id="original_teacher_id"></div>

                    <div class="mb-3"><label class="form-label">Substitute Teacher</label><select name="substitute_teacher_id" class="form-select" required><option value="">Select teacher</option><?php foreach ($teachers as $teacher): ?><option value="<?= (int) $teacher['id'] ?>"><?= htmlspecialchars($teacher['full_name']) ?></option><?php endforeach; ?></select></div>

                    <div><label class="form-label">Reason</label><textarea name="reason" class="form-control" rows="3"></textarea></div>

                </div>

                <div class="modal-footer"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary">Save</button></div>

            </form>

        </div>

    </div>

</div>



<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

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

<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>

<script>

new DataTable('#subTable');

const subModal = new bootstrap.Modal(document.getElementById('subModal'));

const currentYear = '<?= htmlspecialchars(timetableGetCurrentYear($conn)) ?>';

const currentTerm = '<?= htmlspecialchars(timetableGetCurrentTerm($conn)) ?>';



async function resolveSlot() {

    const className = document.getElementById('class_name').value;

    const periodId = document.getElementById('period_id').value;

    const dateValue = document.getElementById('substitution_date').value;

    if (!className || !periodId || !dateValue) { return; }

    const day = new Date(dateValue + 'T00:00:00').toLocaleDateString('en-US', {weekday:'short'}).replace('.', '');

    const response = await fetch('ajax/get_timetable.php', {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:new URLSearchParams({class_name:className, academic_year:currentYear, term:currentTerm})});

    const slots = await response.json();

    const slot = slots.find((item) => item.day_of_week === day && Number(item.period_id) === Number(periodId));

    document.getElementById('slot_id').value = slot ? slot.id : '';

    document.getElementById('original_teacher_id').value = slot && slot.teacher_id ? slot.teacher_id : '';

    document.getElementById('original_teacher_label').value = slot ? (slot.teacher_name || '') : 'No slot found';

}



document.getElementById('class_name').addEventListener('change', resolveSlot);

document.getElementById('period_id').addEventListener('change', resolveSlot);

document.getElementById('substitution_date').addEventListener('change', resolveSlot);

document.getElementById('subForm').addEventListener('submit', async (e) => {

    e.preventDefault();

    const fd = new FormData(e.target);

    const response = await fetch('ajax/save_substitution.php', {method:'POST', body:new URLSearchParams(fd)});

    const data = await response.json();

    if (data.success) { window.location.reload(); return; }

    alert(data.message || 'Failed to save substitution.');

});

</script>

</body>

</html>

