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

}



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

$teacherId = (int) ($_GET['teacher_id'] ?? 0);

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

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

$periods = timetableGetPeriods($conn, $className);

$settings = timetableGetSettings($conn);

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

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



function timetablePrintGrid(array $periods, array $slots): string

{

    $days = timetableDays();

    $html = '<table class="table table-bordered print-table"><thead><tr><th style="width:190px">Period</th>';

    foreach ($days as $day) {

        $html .= '<th>' . htmlspecialchars($day) . '</th>';

    }

    $html .= '</tr></thead><tbody>';



    foreach ($periods as $period) {

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

        $pTypeMeta = timetableSpecialPeriodMeta(timetableGetPeriodType($period));

        if ($pTypeMeta !== null && $pTypeMeta['span']) {

            $html .= '<tr class="break-row"><td>' . $left . '</td><td colspan="6">' . $pTypeMeta['icon'] . ' ' . htmlspecialchars($pTypeMeta['label']) . '</td></tr>';

            continue;

        }



        $html .= '<tr><td>' . $left . '</td>';

        foreach ($days as $day) {

            $slot = null;

            foreach ($slots as $candidate) {

                if ((int) $candidate['period_id'] === (int) $period['id'] && $candidate['day_of_week'] === $day) {

                    $slot = $candidate;

                    break;

                }

            }

            if ($slot === null) {

                if ($pTypeMeta !== null) {

                    $html .= '<td class="text-center text-muted small">' . $pTypeMeta['icon'] . ' ' . htmlspecialchars($pTypeMeta['label']) . '</td>';

                } else {

                    $html .= '<td></td>';

                }

                continue;

            }

            $lines = [];

            if (!empty($slot['subject_name'])) {

                $lines[] = '<div class="fw-semibold">' . htmlspecialchars($slot['subject_name']) . '</div>';

            }

            if (!empty($slot['teacher_name'])) {

                $lines[] = '<div>' . htmlspecialchars($slot['teacher_name']) . '</div>';

            }

            if (!empty($slot['class_name'])) {

                $lines[] = '<div>' . htmlspecialchars($slot['class_name']) . '</div>';

            }

            if (!empty($slot['room'])) {

                $lines[] = '<div class="text-muted">' . htmlspecialchars($slot['room']) . '</div>';

            }

            $html .= '<td>' . implode('', $lines) . '</td>';

        }

        $html .= '</tr>';

    }



    $html .= '</tbody></table>';

    return $html;

}



$titleTarget = '';

$blocks = [];



if ($className !== '') {

    $titleTarget = $className;

    $blocks[] = ['title' => $className, 'slots' => timetableFetchClassSlots($conn, $className, $academicYear, $term), 'periods' => $periods];

} elseif ($teacherId > 0) {

    $teacherName = 'Teacher';

    $teacherStmt = $conn->prepare('SELECT full_name FROM staff WHERE id = ? LIMIT 1');

    $teacherStmt->bind_param('i', $teacherId);

    $teacherStmt->execute();

    $teacherResult = $teacherStmt->get_result();

    if ($teacherRow = $teacherResult->fetch_assoc()) {

        $teacherName = (string) $teacherRow['full_name'];

    }

    $teacherStmt->close();

    $titleTarget = $teacherName;

    $blocks[] = ['title' => $teacherName, 'slots' => timetableFetchTeacherSlots($conn, $teacherId, $academicYear, $term)];

} else {

    $titleTarget = 'Full School';

    foreach (timetableFetchAllClassesWithSlots($conn, $academicYear, $term) as $class) {

        $blocks[] = [

            'title'   => $class,

            'slots'   => timetableFetchClassSlots($conn, $class, $academicYear, $term),

            'periods' => timetableGetPeriods($conn, $class),

        ];

    }

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Printable Timetable</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>

        body{background:#fff;color:#000} .print-table td,.print-table th{font-size:11px;vertical-align:top} .print-table thead th{text-align:center;white-space:nowrap} .break-row td{background:#eee;font-weight:700;text-align:center}

        .print-toolbar{position:sticky;top:0;background:#fff;padding:12px 0}.logo{max-height:70px}

        @media print {.print-toolbar{display:none!important}.page-break{page-break-after:always}.print-table{width:100%} tr{page-break-inside:avoid}}

    </style>

</head>

<body>

    <div class="container py-4">

        <div class="print-toolbar d-flex justify-content-between align-items-center mb-4">

            <div></div>

            <button class="btn btn-primary" onclick="window.print()"><i class="fas fa-print me-1"></i>Print</button>

        </div>



        <div class="text-center mb-4">

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

                <div class="mb-2"><img src="../../<?= htmlspecialchars($logo) ?>" alt="School Logo" class="logo"></div>

            <?php endif; ?>

            <h3 class="mb-1"><?= htmlspecialchars($schoolName) ?></h3>

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

        </div>



        <?php foreach ($blocks as $index => $block): ?>

            <section class="<?= $index < count($blocks) - 1 ? 'page-break' : '' ?>">

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

                    <h5 class="mb-3"><?= htmlspecialchars($block['title']) ?></h5>

                <?php endif; ?>

                <?= timetablePrintGrid($block['periods'] ?? $periods, $block['slots']) ?>

            </section>

        <?php endforeach; ?>

    </div>

</body>

</html>

