<?php
declare(strict_types=1);
require_once __DIR__ . '/Includes.php';
check_login(['admin', 'teacher', 'hop', 'accountant', 'ancillary', 'learner', 'parent']);

$role = (string)($_SESSION['role'] ?? '');
$userId = (int)($_SESSION['user_id'] ?? 0);
$isAdmin = $role === 'admin';
$alerts = [];

$pdo->exec("CREATE TABLE IF NOT EXISTS academic_calendar_events (
  id INT AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(160) NOT NULL,
  event_type ENUM('academic','meeting','sports','holiday','deadline','other') NOT NULL DEFAULT 'academic',
  start_date DATE NOT NULL,
  end_date DATE NOT NULL,
  description TEXT NULL,
  audience ENUM('all','staff','learners','parents') NOT NULL DEFAULT 'all',
  class_id INT NULL,
  created_by INT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_calendar_dates (start_date, end_date),
  INDEX idx_calendar_class (class_id)
)");
$pdo->exec("CREATE TABLE IF NOT EXISTS class_timetable (
  id INT AUTO_INCREMENT PRIMARY KEY,
  class_id INT NOT NULL,
  subject_id INT NULL,
  teacher_id INT NULL,
  day_of_week ENUM('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday') NOT NULL,
  start_time TIME NOT NULL,
  end_time TIME NOT NULL,
  room VARCHAR(80) NULL,
  created_by INT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_timetable_class_day (class_id, day_of_week, start_time),
  INDEX idx_timetable_teacher_day (teacher_id, day_of_week, start_time)
)");

if ($isAdmin && isset($_POST['add_calendar_event'])) {
  $title = trim((string)($_POST['event_title'] ?? ''));
  $eventType = (string)($_POST['event_type'] ?? 'academic');
  $startDate = (string)($_POST['start_date'] ?? '');
  $endDate = (string)($_POST['end_date'] ?? $startDate);
  $audience = (string)($_POST['audience'] ?? 'all');
  $classId = (int)($_POST['event_class_id'] ?? 0);
  $description = trim((string)($_POST['description'] ?? ''));
  $allowedTypes = ['academic', 'meeting', 'sports', 'holiday', 'deadline', 'other'];
  $allowedAudiences = ['all', 'staff', 'learners', 'parents'];

  if ($title === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $startDate) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $endDate)) {
    $alerts[] = ['type' => 'error', 'text' => 'Event title and valid start/end dates are required.'];
  } elseif ($endDate < $startDate || !in_array($eventType, $allowedTypes, true) || !in_array($audience, $allowedAudiences, true)) {
    $alerts[] = ['type' => 'error', 'text' => 'Check the event dates, type, and audience.'];
  } else {
    $stmt = $pdo->prepare("INSERT INTO academic_calendar_events
      (title, event_type, start_date, end_date, description, audience, class_id, created_by)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$title, $eventType, $startDate, $endDate, $description === '' ? null : $description, $audience, $classId > 0 ? $classId : null, $userId]);
    append_system_log($pdo, 'calendar_event_created', 'Created calendar event: ' . $title, $userId, $role, 'academic_calendar_event', (int)$pdo->lastInsertId());
    $alerts[] = ['type' => 'success', 'text' => 'Calendar event added.'];
  }
}

if ($isAdmin && isset($_POST['add_timetable_slot'])) {
  $classId = (int)($_POST['class_id'] ?? 0);
  $subjectId = (int)($_POST['subject_id'] ?? 0);
  $teacherId = (int)($_POST['teacher_id'] ?? 0);
  $day = (string)($_POST['day_of_week'] ?? '');
  $startTime = (string)($_POST['start_time'] ?? '');
  $endTime = (string)($_POST['end_time'] ?? '');
  $room = trim((string)($_POST['room'] ?? ''));
  $days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

  if ($classId <= 0 || !in_array($day, $days, true) || !preg_match('/^\d{2}:\d{2}$/', $startTime) || !preg_match('/^\d{2}:\d{2}$/', $endTime)) {
    $alerts[] = ['type' => 'error', 'text' => 'Choose a class, day, start time, and end time.'];
  } elseif ($endTime <= $startTime) {
    $alerts[] = ['type' => 'error', 'text' => 'A lesson must end after it starts.'];
  } else {
    $conflictSql = "SELECT COUNT(*) FROM class_timetable
      WHERE day_of_week = ? AND start_time < ? AND end_time > ?
        AND (class_id = ?" . ($teacherId > 0 ? " OR teacher_id = ?" : '') . ")";
    $conflictStmt = $pdo->prepare($conflictSql);
    $params = [$day, $endTime, $startTime, $classId];
    if ($teacherId > 0) {
      $params[] = $teacherId;
    }
    $conflictStmt->execute($params);
    if ((int)$conflictStmt->fetchColumn() > 0) {
      $alerts[] = ['type' => 'error', 'text' => 'That class or teacher already has an overlapping timetable entry.'];
    } else {
      $stmt = $pdo->prepare("INSERT INTO class_timetable
        (class_id, subject_id, teacher_id, day_of_week, start_time, end_time, room, created_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
      $stmt->execute([$classId, $subjectId > 0 ? $subjectId : null, $teacherId > 0 ? $teacherId : null, $day, $startTime, $endTime, $room === '' ? null : $room, $userId]);
      append_system_log($pdo, 'timetable_slot_created', "Added {$day} timetable slot.", $userId, $role, 'class_timetable', (int)$pdo->lastInsertId());
      $alerts[] = ['type' => 'success', 'text' => 'Timetable lesson added.'];
    }
  }
}

if ($isAdmin && isset($_POST['delete_calendar_event'])) {
  $eventId = (int)($_POST['event_id'] ?? 0);
  if ($eventId > 0) {
    $stmt = $pdo->prepare("DELETE FROM academic_calendar_events WHERE id = ? LIMIT 1");
    $stmt->execute([$eventId]);
    append_system_log($pdo, 'calendar_event_deleted', 'Deleted a calendar event.', $userId, $role, 'academic_calendar_event', $eventId);
    $alerts[] = ['type' => 'success', 'text' => 'Calendar event removed.'];
  }
}

if ($isAdmin && isset($_POST['delete_timetable_slot'])) {
  $slotId = (int)($_POST['slot_id'] ?? 0);
  if ($slotId > 0) {
    $stmt = $pdo->prepare("DELETE FROM class_timetable WHERE id = ? LIMIT 1");
    $stmt->execute([$slotId]);
    append_system_log($pdo, 'timetable_slot_deleted', 'Deleted a timetable entry.', $userId, $role, 'class_timetable', $slotId);
    $alerts[] = ['type' => 'success', 'text' => 'Timetable lesson removed.'];
  }
}

$permittedClassIds = null;
if ($role === 'teacher') {
  $stmt = $pdo->prepare("SELECT DISTINCT class_id FROM (
      SELECT class_id FROM class_teacher_assignments WHERE teacher_id = ?
      UNION SELECT class_id FROM teacher_subjects WHERE teacher_id = ?
    ) assigned");
  $stmt->execute([$userId, $userId]);
  $permittedClassIds = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));
} elseif ($role === 'learner') {
  $stmt = $pdo->prepare("SELECT class_id FROM learners WHERE id = ? LIMIT 1");
  $stmt->execute([$userId]);
  $classId = (int)$stmt->fetchColumn();
  $permittedClassIds = $classId > 0 ? [$classId] : [];
} elseif ($role === 'parent') {
  $stmt = $pdo->prepare("SELECT DISTINCT l.class_id FROM parent_learner_links pll
    JOIN learners l ON l.id = pll.learner_id WHERE pll.parent_user_id = ?");
  $stmt->execute([$userId]);
  $permittedClassIds = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));
}

$allClasses = $pdo->query("SELECT id, name FROM classes ORDER BY name")->fetchAll();
if (is_array($permittedClassIds)) {
  $allClasses = array_values(array_filter($allClasses, static fn(array $class): bool => in_array((int)$class['id'], $permittedClassIds, true)));
}
$selectedClassId = (int)($_GET['class_id'] ?? ($allClasses[0]['id'] ?? 0));
if (is_array($permittedClassIds) && !in_array($selectedClassId, $permittedClassIds, true)) {
  $selectedClassId = (int)($allClasses[0]['id'] ?? 0);
}

$subjects = $pdo->query("SELECT id, name, class_id FROM subjects ORDER BY name")->fetchAll();
$teachers = $pdo->query("SELECT id, name FROM users WHERE role = 'teacher' ORDER BY name")->fetchAll();

$timetableRows = [];
if ($selectedClassId > 0) {
  $stmt = $pdo->prepare("SELECT ct.*, c.name AS class_name, s.name AS subject_name, u.name AS teacher_name
    FROM class_timetable ct
    JOIN classes c ON c.id = ct.class_id
    LEFT JOIN subjects s ON s.id = ct.subject_id
    LEFT JOIN users u ON u.id = ct.teacher_id
    WHERE ct.class_id = ?
    ORDER BY FIELD(ct.day_of_week,'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'), ct.start_time");
  $stmt->execute([$selectedClassId]);
  $timetableRows = $stmt->fetchAll();
}

$audienceForRole = match ($role) {
  'learner' => 'learners',
  'parent' => 'parents',
  default => 'staff',
};
$eventSql = "SELECT ace.*, c.name AS class_name FROM academic_calendar_events ace
  LEFT JOIN classes c ON c.id = ace.class_id
  WHERE ace.end_date >= (CURRENT_DATE - INTERVAL 7 DAY)
    AND (ace.audience = 'all' OR ace.audience = ?)";
$eventParams = [$audienceForRole];
if ($selectedClassId > 0) {
  $eventSql .= " AND (ace.class_id IS NULL OR ace.class_id = ?)";
  $eventParams[] = $selectedClassId;
} elseif (is_array($permittedClassIds)) {
  $eventSql .= " AND ace.class_id IS NULL";
}
$eventSql .= " ORDER BY ace.start_date, ace.title LIMIT 100";
$stmt = $pdo->prepare($eventSql);
$stmt->execute($eventParams);
$events = $stmt->fetchAll();

$theme = get_school_theme_palette($pdo);
$brand = (string)($theme['brand_navy'] ?? '#2E8B45');
$brandDeep = (string)($theme['brand_navy_deep'] ?? '#1D6A33');
$ink = (string)($theme['ink'] ?? '#173122');
$background = (string)($theme['bg_cream'] ?? '#F7FBF7');
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Academic Planner | Mavela</title>
  <style>
    :root { --brand:<?= h($brand) ?>; --brand-deep:<?= h($brandDeep) ?>; --ink:<?= h($ink) ?>; --bg:<?= h($background) ?>; --line:#dce8df; --panel:#fff; --muted:#607066; }
    * { box-sizing:border-box; }
    body { margin:0; padding:24px; font-family:system-ui,sans-serif; color:var(--ink); background:var(--bg); }
    main { width:min(1380px,100%); margin:auto; }
    .top { display:flex; justify-content:space-between; gap:16px; align-items:center; margin-bottom:22px; }
    h1,h2 { margin-top:0; }
    .top h1 { margin-bottom:5px; }
    .top a { color:var(--brand-deep); font-weight:800; }
    .filters { display:flex; gap:10px; align-items:end; flex-wrap:wrap; margin-bottom:18px; }
    .filters label { min-width:240px; }
    .layout { display:grid; grid-template-columns:minmax(0,1.35fr) minmax(300px,.65fr); gap:20px; }
    .panel { padding:22px; background:var(--panel); border:1px solid var(--line); border-radius:18px; box-shadow:0 12px 36px rgba(15,61,30,.08); }
    .forms { display:grid; grid-template-columns:1fr 1fr; gap:20px; margin-bottom:20px; }
    label { display:grid; gap:6px; margin-bottom:11px; font-weight:700; }
    input,select,textarea { width:100%; padding:10px 11px; border:1px solid var(--line); }
    textarea { min-height:88px; resize:vertical; }
    button,.button { display:inline-flex; justify-content:center; align-items:center; padding:10px 14px; color:#fff; background:var(--brand-deep); border:0; border-radius:10px; font-weight:800; text-decoration:none; cursor:pointer; }
    button.danger { color:#9f1239; background:#fff0f3; }
    .alert { padding:11px 13px; margin-bottom:12px; border-radius:10px; }
    .alert.success { color:#166534; background:#ecfdf3; }
    .alert.error { color:#9f1239; background:#fff1f3; }
    table { width:100%; }
    th,td { padding:11px; border-bottom:1px solid var(--line); text-align:left; }
    .event { padding:15px; margin-bottom:11px; border:1px solid var(--line); border-left:5px solid var(--brand); border-radius:12px; }
    .event h3 { margin:0 0 5px; }
    .event p { margin:5px 0; color:var(--muted); }
    .tag { display:inline-flex; padding:4px 8px; color:var(--brand-deep); background:#eaf5ed; border-radius:999px; font-size:.76rem; font-weight:800; }
    .empty { padding:24px; color:var(--muted); text-align:center; }
    @media(max-width:900px){ body{padding:14px}.layout,.forms{grid-template-columns:1fr}.top{align-items:flex-start;flex-direction:column} }
  </style>
</head>
<body>
<main>
  <header class="top">
    <div><h1>Academic Planner</h1><div>Class timetable and upcoming school events</div></div>
    <a href="<?= h($role === 'admin' ? 'admin.php' : ($role . '.php')) ?>">← Back to dashboard</a>
  </header>
  <?php foreach ($alerts as $alert): ?><div class="alert <?= h($alert['type']) ?>"><?= h($alert['text']) ?></div><?php endforeach; ?>

  <?php if ($isAdmin): ?>
  <div class="forms">
    <section class="panel">
      <h2>Add timetable lesson</h2>
      <form method="post">
        <label>Class<select name="class_id" required><option value="">Choose class</option><?php foreach ($allClasses as $class): ?><option value="<?= h($class['id']) ?>"><?= h($class['name']) ?></option><?php endforeach; ?></select></label>
        <label>Subject<select name="subject_id"><option value="">Unspecified</option><?php foreach ($subjects as $subject): ?><option value="<?= h($subject['id']) ?>"><?= h($subject['name']) ?></option><?php endforeach; ?></select></label>
        <label>Teacher<select name="teacher_id"><option value="">Unassigned</option><?php foreach ($teachers as $teacher): ?><option value="<?= h($teacher['id']) ?>"><?= h($teacher['name']) ?></option><?php endforeach; ?></select></label>
        <label>Day<select name="day_of_week" required><?php foreach (['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] as $day): ?><option><?= h($day) ?></option><?php endforeach; ?></select></label>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px"><label>Starts<input type="time" name="start_time" required></label><label>Ends<input type="time" name="end_time" required></label></div>
        <label>Room / location<input name="room" maxlength="80"></label>
        <button type="submit" name="add_timetable_slot">Add lesson</button>
      </form>
    </section>
    <section class="panel">
      <h2>Add calendar event</h2>
      <form method="post">
        <label>Title<input name="event_title" maxlength="160" required></label>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px"><label>Starts<input type="date" name="start_date" required></label><label>Ends<input type="date" name="end_date" required></label></div>
        <label>Type<select name="event_type"><?php foreach (['academic','meeting','sports','holiday','deadline','other'] as $type): ?><option value="<?= h($type) ?>"><?= h(ucfirst($type)) ?></option><?php endforeach; ?></select></label>
        <label>Audience<select name="audience"><option value="all">Everyone</option><option value="staff">Staff</option><option value="learners">Learners</option><option value="parents">Parents</option></select></label>
        <label>Class (optional)<select name="event_class_id"><option value="">Whole school</option><?php foreach ($allClasses as $class): ?><option value="<?= h($class['id']) ?>"><?= h($class['name']) ?></option><?php endforeach; ?></select></label>
        <label>Description<textarea name="description" maxlength="2000"></textarea></label>
        <button type="submit" name="add_calendar_event">Add event</button>
      </form>
    </section>
  </div>
  <?php endif; ?>

  <form method="get" class="filters">
    <label>View class<select name="class_id"><?php if (!$allClasses): ?><option value="">No assigned classes</option><?php endif; ?><?php foreach ($allClasses as $class): ?><option value="<?= h($class['id']) ?>" <?= (int)$class['id'] === $selectedClassId ? 'selected' : '' ?>><?= h($class['name']) ?></option><?php endforeach; ?></select></label>
    <button type="submit">Open class</button>
  </form>

  <div class="layout">
    <section class="panel">
      <h2>Weekly timetable</h2>
      <?php if (!$timetableRows): ?><div class="empty">No timetable entries have been added for this class.</div><?php else: ?>
      <table>
        <thead><tr><th>Day</th><th>Time</th><th>Subject</th><th>Teacher</th><th>Room</th><?php if ($isAdmin): ?><th></th><?php endif; ?></tr></thead>
        <tbody>
        <?php foreach ($timetableRows as $row): ?>
          <tr>
            <td><strong><?= h($row['day_of_week']) ?></strong></td>
            <td><?= h(substr((string)$row['start_time'], 0, 5)) ?>–<?= h(substr((string)$row['end_time'], 0, 5)) ?></td>
            <td><?= h($row['subject_name'] ?? 'Unspecified') ?></td>
            <td><?= h($row['teacher_name'] ?? 'Unassigned') ?></td>
            <td><?= h($row['room'] ?? '—') ?></td>
            <?php if ($isAdmin): ?><td><form method="post"><input type="hidden" name="slot_id" value="<?= h($row['id']) ?>"><button class="danger" name="delete_timetable_slot" type="submit">Remove</button></form></td><?php endif; ?>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </section>
    <aside class="panel">
      <h2>Upcoming events</h2>
      <?php if (!$events): ?><div class="empty">No upcoming events for this audience.</div><?php endif; ?>
      <?php foreach ($events as $event): ?>
        <article class="event">
          <span class="tag"><?= h(ucfirst($event['event_type'])) ?></span>
          <h3><?= h($event['title']) ?></h3>
          <p><strong><?= h(date('d M Y', strtotime((string)$event['start_date']))) ?><?= $event['end_date'] !== $event['start_date'] ? ' – ' . h(date('d M Y', strtotime((string)$event['end_date']))) : '' ?></strong></p>
          <?php if (!empty($event['class_name'])): ?><p>Class: <?= h($event['class_name']) ?></p><?php endif; ?>
          <?php if (!empty($event['description'])): ?><p><?= nl2br(h($event['description'])) ?></p><?php endif; ?>
          <?php if ($isAdmin): ?><form method="post"><input type="hidden" name="event_id" value="<?= h($event['id']) ?>"><button class="danger" name="delete_calendar_event" type="submit">Remove event</button></form><?php endif; ?>
        </article>
      <?php endforeach; ?>
    </aside>
  </div>
</main>
</body>
</html>
