<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
require_once __DIR__ . '/helpers.php';
if (!isset($_SESSION['parent_id'])) { header('Location: login.php'); exit; }

$conn = portalGetConnection();
if (!$conn instanceof mysqli) { http_response_code(500); exit('Database connection failed.'); }
$children = portalGetChildren($conn, (int) $_SESSION['parent_id']);
$childId = (int) ($_GET['child_id'] ?? ($children[0]['id'] ?? 0));
if ($childId > 0 && !portalParentOwnsStudent($conn, (int) $_SESSION['parent_id'], $childId)) {
    header('Location: dashboard.php?error=unauthorized');
    exit;
}
$student = $childId > 0 ? portalGetStudent($conn, $childId, (int) $_SESSION['parent_id']) : null;
$term = portalCurrentTerm($conn);
$year = portalCurrentYear($conn);
$periods = [];
$slots = [];
if ($student) {
    $periodResult = $conn->query("SELECT * FROM timetable_periods ORDER BY order_no ASC");
    while ($periodResult && $row = $periodResult->fetch_assoc()) { $periods[] = $row; }

    $stmt = $conn->prepare(
        "SELECT ts.*, s.subject_name, st.full_name AS teacher_name, p.period_name, p.is_break, p.order_no
         FROM timetable_slots ts
         LEFT JOIN subjects s ON s.id = ts.subject_id
         LEFT JOIN staff st ON st.id = ts.teacher_id
         LEFT JOIN timetable_periods p ON p.id = ts.period_id
         WHERE ts.class_name = ? AND ts.academic_year = ? AND ts.term = ?
         ORDER BY p.order_no ASC, ts.day_of_week ASC"
    );
    $className = (string) ($student['class'] ?? '');
    $stmt->bind_param('sss', $className, $year, $term);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $slots[(int) $row['period_id']][(string) $row['day_of_week']] = $row;
    }
    $stmt->close();
}
$days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
echo portalPageStart('Timetable', 'reports', 'Class Timetable');
?>
<?= portalChildSwitcher($children, $childId, 'timetable.php') ?>
<div class="portal-card">
    <div class="portal-section-title">Timetable for <?= htmlspecialchars(portalStudentDisplayName($student ?: [])) ?></div>
    <div class="portal-muted small mb-3">Current term: <?= htmlspecialchars($term) ?> • Academic year: <?= htmlspecialchars($year) ?></div>
    <?php if (empty($periods) || empty($slots)): ?>
    <div class="text-center py-5 portal-muted">
        <i class="fas fa-calendar-times" style="font-size:2.5rem;opacity:.4;display:block;margin-bottom:12px"></i>
        <strong>No timetable available</strong><br>
        <span style="font-size:.85rem">The timetable for <?= htmlspecialchars($term . ' ' . $year) ?> has not been set up yet.<br>Please check back later or contact the school.</span>
    </div>
    <?php else: ?>
    <div class="portal-table-wrap">
        <table class="portal-table">
            <thead><tr><th>Period</th><?php foreach ($days as $day): ?><th><?= htmlspecialchars($day) ?></th><?php endforeach; ?></tr></thead>
            <tbody>
            <?php foreach ($periods as $period): ?>
                <?php if ((int) $period['is_break'] === 1): ?>
                    <tr>
                        <td><?= htmlspecialchars((string) $period['period_name']) ?></td>
                        <td colspan="6" class="text-center text-muted">BREAK</td>
                    </tr>
                <?php else: ?>
                    <tr>
                        <td><?= htmlspecialchars((string) $period['period_name']) ?><br><small class="portal-muted"><?= htmlspecialchars(substr((string) $period['start_time'],0,5)) ?> - <?= htmlspecialchars(substr((string) $period['end_time'],0,5)) ?></small></td>
                        <?php foreach ($days as $day): $slot = $slots[(int) $period['id']][$day] ?? null; ?>
                            <td>
                                <?php if ($slot): ?>
                                    <div class="fw-semibold"><?= htmlspecialchars((string) ($slot['subject_name'] ?? '')) ?></div>
                                    <div class="portal-muted small"><?= htmlspecialchars((string) ($slot['teacher_name'] ?? '')) ?></div>
                                    <div class="portal-muted small"><?= htmlspecialchars((string) ($slot['room'] ?? '')) ?></div>
                                <?php else: ?>
                                    <span class="portal-muted small">-</span>
                                <?php endif; ?>
                            </td>
                        <?php endforeach; ?>
                    </tr>
                <?php endif; ?>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>
<?= portalPageEnd('reports') ?>
