<?php

declare(strict_types=1);

session_start();

require_once '../config.php';

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

$subjects = examsGetSubjects($conn); $classes = examsGetClasses($conn); $teachers = examsGetTeachers($conn);

$papers = [];

$result = $conn->query("SELECT id, title, class_name FROM exam_papers WHERE status = 'published' ORDER BY title");

while ($result && $row = $result->fetch_assoc()) { $papers[] = $row; }

$month = (int) date('n'); $year = (int) date('Y');

?>

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Exams - Schedule</title>

<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/font-awesome/6.4.0/css/all.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"><style>.calendar-grid{display:grid;grid-template-columns:repeat(7,1fr);gap:8px}.day-cell{background:#fff;border:1px solid #dee2e6;border-radius:10px;min-height:100px;padding:8px}.day-label{font-size:.8rem;color:#6c757d}</style></head><body><div class="wrapper"><nav id="sidebar" class="sidebar"><?php if (!defined('EDUTRACK_MODULES')) require_once __DIR__ . '/../module_definitions.php'; echo buildSidebar('exams_generator/' . 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">Exams - Schedule</h4><div class="text-muted small">Manage exam dates, venues, invigilators, and clashes.</div></div><button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#scheduleModal"><i class="fas fa-plus me-1"></i>Schedule Exam</button></header><main class="container-fluid py-4"><?= examsRenderTabs('schedules') ?><div class="card shadow-sm border-0 mb-4"><div class="card-body"><h6 class="mb-3"><?= date('F Y') ?></h6><div class="calendar-grid" id="calendarGrid"></div></div></div><div class="card shadow-sm border-0"><div class="card-body"><table id="scheduleTable" class="table table-striped align-middle"><thead><tr><th>Date</th><th>Time</th><th>Class</th><th>Paper Title</th><th>Subject</th><th>Venue</th><th>Invigilator</th><th>Status</th><th>Actions</th></tr></thead><tbody></tbody></table></div></div></main></div></div>

<div class="modal fade" id="scheduleModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><form id="scheduleForm"><div class="modal-header"><h5 class="modal-title">Schedule Exam</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><input type="hidden" name="id" id="schedule_id" value="0"><div class="mb-3"><label class="form-label">Paper</label><select class="form-select" name="paper_id" id="paper_id"><?php foreach($papers as $paper): ?><option value="<?= (int)$paper['id'] ?>" data-class="<?= htmlspecialchars((string)$paper['class_name']) ?>"><?= htmlspecialchars((string)$paper['title']) ?></option><?php endforeach; ?></select></div><div class="mb-3"><label class="form-label">Class</label><select class="form-select" name="class_name" id="schedule_class_name"><option value="">— Select class —</option><?php foreach($classes as $cls): ?><option value="<?= htmlspecialchars($cls) ?>"><?= htmlspecialchars($cls) ?></option><?php endforeach; ?></select></div><div class="row g-3"><div class="col-md-6"><label class="form-label">Date</label><input type="date" class="form-control" name="exam_date" id="exam_date" required></div><div class="col-md-6"><label class="form-label">Venue</label><input type="text" class="form-control" name="venue" id="venue"></div><div class="col-md-6"><label class="form-label">Start Time</label><input type="time" class="form-control" name="start_time" id="start_time" required></div><div class="col-md-6"><label class="form-label">End Time</label><input type="time" class="form-control" name="end_time" id="end_time" required></div><div class="col-md-6"><label class="form-label">Invigilator</label><select class="form-select" name="invigilator_id" id="invigilator_id"><option value="0">Select</option><?php foreach($teachers as $t): ?><option value="<?= (int)$t['id'] ?>"><?= htmlspecialchars((string)$t['full_name']) ?></option><?php endforeach; ?></select></div><div class="col-md-6"><label class="form-label">Status</label><select class="form-select" name="status" id="schedule_status"><option value="scheduled">Scheduled</option><option value="ongoing">Ongoing</option><option value="completed">Completed</option><option value="cancelled">Cancelled</option></select></div></div></div><div class="modal-footer"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" type="submit">Save Schedule</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>

let scheduleTable,schedules=[];const month=<?= $month ?>, year=<?= $year ?>;function esc(v){return String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));}

function renderCalendar(){const days=new Date(year,month,0).getDate(), grid=document.getElementById('calendarGrid');grid.innerHTML=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'].map(d=>`<div class="fw-semibold text-center">${d}</div>`).join('');const first=new Date(year,month-1,1).getDay();for(let i=0;i<first;i++)grid.innerHTML+='<div></div>';for(let d=1;d<=days;d++){const key=`${year}-${String(month).padStart(2,'0')}-${String(d).padStart(2,'0')}`;const events=schedules.filter(s=>s.exam_date===key);grid.innerHTML+=`<div class="day-cell"><div class="day-label">${d}</div>${events.map(e=>`<div class="badge bg-primary d-block mt-1 text-start">${esc(e.paper_title)}</div>`).join('')}</div>`;}}

async function loadSchedules(){const res=await fetch('ajax/get_schedules.php');schedules=await res.json();scheduleTable.clear();schedules.forEach(s=>scheduleTable.row.add([esc(s.exam_date),`${esc((s.start_time||'').slice(0,5))} - ${esc((s.end_time||'').slice(0,5))}`,esc(s.class_name||s.paper_class_name||''),esc(s.paper_title||''),esc(s.subject_name||''),esc(s.venue||''),esc(s.invigilator_name||''),esc(s.status||''),`<button class="btn btn-sm btn-outline-primary me-1" data-schedule='${encodeURIComponent(JSON.stringify(s))}'>Edit</button><button class="btn btn-sm btn-outline-danger" onclick="deleteSchedule(${s.id})">Delete</button>`]));scheduleTable.draw();$('#scheduleTable button[data-schedule]').each(function(){this.onclick=()=>editSchedule(JSON.parse(decodeURIComponent(this.dataset.schedule)));});renderCalendar();}

function resetSchedule(){document.getElementById('scheduleForm').reset();document.getElementById('schedule_id').value='0';syncClass();}

function syncClass(){const selected=document.querySelector('#paper_id option:checked');const cls=selected?selected.dataset.class:'';const sel=document.getElementById('schedule_class_name');if(cls){const opt=Array.from(sel.options).find(o=>o.value===cls);if(opt){sel.value=cls;}else{const o=new Option(cls,cls);sel.appendChild(o);sel.value=cls;}}else{sel.value='';}}

function editSchedule(s){document.getElementById('schedule_id').value=s.id;document.getElementById('paper_id').value=s.paper_id;document.getElementById('schedule_class_name').value=s.class_name;document.getElementById('exam_date').value=s.exam_date;document.getElementById('start_time').value=(s.start_time||'').slice(0,5);document.getElementById('end_time').value=(s.end_time||'').slice(0,5);document.getElementById('venue').value=s.venue||'';document.getElementById('invigilator_id').value=s.invigilator_id||0;document.getElementById('schedule_status').value=s.status||'scheduled';new bootstrap.Modal(document.getElementById('scheduleModal')).show();}

async function deleteSchedule(id){if(!confirm('Delete this schedule?'))return;const res=await fetch('ajax/delete_schedule.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({id})});const data=await res.json();if(data.success)loadSchedules();}

document.addEventListener('DOMContentLoaded',()=>{scheduleTable=new DataTable('#scheduleTable');document.getElementById('paper_id').addEventListener('change',syncClass);document.getElementById('scheduleForm').addEventListener('submit',async(e)=>{e.preventDefault();const res=await fetch('ajax/save_schedule.php',{method:'POST',body:new URLSearchParams(new FormData(e.target))});const data=await res.json();alert(data.message||'Saved');if(data.success){bootstrap.Modal.getInstance(document.getElementById('scheduleModal')).hide();loadSchedules();}});syncClass();loadSchedules();});

</script></body></html>

