<?php

declare(strict_types=1);



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

require_once __DIR__ . '/helpers.php';



$conn = getDBConnection();

if (!$conn instanceof mysqli) {

    http_response_code(500);

    exit('Database connection failed.');

}



$classes = timetableGetClasses($conn);

$periods = timetableGetPeriods($conn);

$settings = timetableGetSettings($conn);

$schoolName = $settings['school_name'] ?? 'EduTrack School';

$logo = $settings['school_logo'] ?? '';

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

$defaultTerm  = timetableGetCurrentTerm($conn);

$defaultYear  = timetableGetCurrentYear($conn);

$term         = trim((string) ($_GET['term'] ?? $defaultTerm));

$academicYear = trim((string) ($_GET['academic_year'] ?? $defaultYear));

$slots = $className !== '' ? timetableFetchClassSlots($conn, $className, $academicYear, $term) : [];

$days = timetableDays();

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Public 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">

    <style>

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

        .table td,.table th{vertical-align:top}

        .school-header-brand { border-bottom: 3px solid #1a73e8; padding-bottom: 16px; margin-bottom: 24px; }

        .school-logo-placeholder { width:60px;height:60px;border-radius:50%;background:linear-gradient(135deg,#1a73e8,#0d47a1);

            display:flex;align-items:center;justify-content:center;color:#fff;font-size:1.4rem;font-weight:700; }

        @media print {

            .no-print { display:none!important; }

            .container { max-width:100%!important; padding:0!important; }

            .school-header-brand { border-bottom: 2px solid #000; }

            body { background:#fff!important; }

            .card { box-shadow:none!important; border:1px solid #ccc!important; }

            table { font-size:.82rem; }

        }

    </style>

</head>

<body class="bg-light">

<div class="container py-4">

    <!-- School Branding Header -->

    <div class="school-header-brand d-flex justify-content-between align-items-center flex-wrap gap-3">

        <div class="d-flex align-items-center gap-3">

            <?php if ($logo !== ''): ?>

                <img src="../../<?= htmlspecialchars($logo) ?>" alt="School Logo"

                     style="max-height:64px;max-width:64px;object-fit:contain;border-radius:6px">

            <?php else: ?>

                <div class="school-logo-placeholder"><?= strtoupper(substr((string) $schoolName, 0, 1)) ?></div>

            <?php endif; ?>

            <div>

                <h3 class="mb-0 fw-bold"><?= htmlspecialchars($schoolName) ?></h3>

                <div class="text-muted small">

                    <?php if ($className !== ''): ?>

                        Class Timetable &mdash; <?= htmlspecialchars($className) ?> &bull; <?= htmlspecialchars($term) ?> &bull; <?= htmlspecialchars($academicYear) ?>

                    <?php else: ?>

                        Class Timetable — Public View

                    <?php endif; ?>

                </div>

            </div>

        </div>

        <div class="d-flex gap-2 no-print">

            <?php if ($className !== ''): ?>

            <a href="?class_name=&term=<?= urlencode($term) ?>&academic_year=<?= urlencode($academicYear) ?>"

               class="btn btn-outline-secondary btn-sm">

                <i class="fas fa-arrow-left me-1"></i> Change Class

            </a>

            <?php endif; ?>

            <button class="btn btn-outline-primary btn-sm" onclick="window.print()">

                <i class="fas fa-print me-1"></i> Print

            </button>

        </div>

    </div>



    <?php if ($className === ''): ?>

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

            <div class="card-body">

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

                    <div class="col-md-4"><label class="form-label">Class</label><select name="class_name" class="form-select" required><option value="">Select class</option><?php foreach ($classes as $option): ?><option value="<?= htmlspecialchars($option) ?>"><?= htmlspecialchars($option) ?></option><?php endforeach; ?></select></div>

                    <div class="col-md-3"><label class="form-label">Term</label><select name="term" class="form-select"><?php foreach (timetableTerms() as $option): ?><option value="<?= htmlspecialchars($option) ?>" <?= $option === $defaultTerm ? 'selected' : '' ?>><?= htmlspecialchars($option) ?></option><?php endforeach; ?></select></div>

                    <div class="col-md-3"><label class="form-label">Academic Year</label><input type="text" name="academic_year" class="form-control" value="<?= htmlspecialchars($defaultYear) ?>"></div>

                    <div class="col-md-2"><button class="btn btn-primary w-100">View Timetable</button></div>

                </form>

            </div>

        </div>

    <?php elseif ($className !== '' && empty($slots) && empty($periods)): ?>

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

            <div class="card-body text-center py-5">

                <i class="fas fa-calendar-times fa-3x text-muted mb-3 d-block" style="opacity:.4"></i>

                <h5>No timetable found for <strong><?= htmlspecialchars($className) ?></strong></h5>

                <p class="text-muted">The timetable for this class has not been set up yet for <?= htmlspecialchars($term . ' ' . $academicYear) ?>.</p>

                <a href="?class_name=&term=<?= urlencode($term) ?>&academic_year=<?= urlencode($academicYear) ?>"

                   class="btn btn-outline-primary no-print">Try another class</a>

            </div>

        </div>

    <?php else: ?>

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

            <div class="card-body">

                <h5 class="mb-3">Timetable - <?= htmlspecialchars($className) ?> - <?= htmlspecialchars($term) ?> <?= htmlspecialchars($academicYear) ?></h5>

                <div class="table-responsive">

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

                        <thead class="table-light"><tr><th style="width:190px">Period</th><?php foreach ($days as $day): ?><th><?= htmlspecialchars($day) ?></th><?php endforeach; ?></tr></thead>

                        <tbody>

                            <?php foreach ($periods as $period): ?>

                                <?php $left = htmlspecialchars((string) $period['period_name']) . '<div class="small text-muted">' . substr((string) $period['start_time'], 0, 5) . ' - ' . substr((string) $period['end_time'], 0, 5) . '</div>'; ?>

                                <?php $pvMeta = timetableSpecialPeriodMeta(timetableGetPeriodType($period)); ?>

                                <?php if ($pvMeta !== null && $pvMeta['span']): ?>

                                    <tr class="break-row"><td><?= $left ?></td><td colspan="6"><?= $pvMeta['icon'] ?> <?= htmlspecialchars($pvMeta['label']) ?></td></tr>

                                <?php else: ?>

                                    <tr>

                                        <td><?= $left ?></td>

                                        <?php foreach ($days as $day): ?>

                                            <?php $slot = null; foreach ($slots as $candidate) { if ((int) $candidate['period_id'] === (int) $period['id'] && $candidate['day_of_week'] === $day) { $slot = $candidate; break; } } ?>

                                            <td>

                                                <?php if ($slot !== null): ?>

                                                    <div class="fw-semibold"><?= htmlspecialchars((string) ($slot['subject_name'] ?? '')) ?></div>

                                                    <div class="small"><?= htmlspecialchars((string) ($slot['teacher_name'] ?? '')) ?></div>

                                                    <div class="small text-muted"><?= htmlspecialchars((string) ($slot['room'] ?? '')) ?></div>

                                                <?php elseif ($pvMeta !== null): ?>

                                                    <div class="text-center text-muted small"><?= $pvMeta['icon'] ?> <?= htmlspecialchars($pvMeta['label']) ?></div>

                                                <?php endif; ?>

                                            </td>

                                        <?php endforeach; ?>

                                    </tr>

                                <?php endif; ?>

                            <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            </div>

        </div>

    <?php endif; ?>

</div>

</body>

</html>

