<!DOCTYPE html>
<html lang="id">
<head>
    <?php helper('logo'); ?>
    <link rel="icon" type="image/png" href="<?= getLogo('sekolah') ?>">
<meta charset="UTF-8">
<title>Cetak Jadwal Pengawas - <?= esc($event['name']) ?></title>
<style>
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: Arial, sans-serif;
    background: #e2e8f0;
    padding: 20px;
}

/* Preview Header */
.preview-header {
    background: #1e293b;
    color: white;
    padding: 12px 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    position: sticky;
    top: 10px;
    z-index: 100;
}
.preview-header h2 {
    font-size: 1.1rem;
    margin: 0;
}
.preview-header p {
    font-size: 0.8rem;
    opacity: 0.8;
    margin-top: 4px;
}
.btn-back {
    background: #475569;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.8rem;
    margin-right: 8px;
}
.btn-print {
    background: #0ea5e9;
    color: white;
    border: none;
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.8rem;
    font-weight: bold;
}

/* Page Setup: Folio (F4) Landscape */
@page {
    size: 330mm 215mm;
    margin: 0;
}

.a4-sheet {
    width: 330mm;
    height: 215mm;
    background: white;
    position: relative;
    margin: 0 auto 20px;
    padding: 8mm 5mm;
    box-shadow: 0 4px 10px rgba(0,0,0,0.15);
    display: flex;
    flex-direction: column;
}

/* Title & Info */
.page-title {
    text-align: center;
    font-size: 11pt;
    font-weight: bold;
    text-transform: uppercase;
    margin-top: 1mm;
    margin-bottom: 2mm;
    text-decoration: underline;
    letter-spacing: 0.5px;
}

.event-details-bar {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    padding: 1.5mm 3mm;
    border-radius: 4px;
    font-size: 9pt;
    margin-bottom: 3mm;
    display: flex;
    justify-content: space-between;
    text-transform: uppercase;
}

/* Table */
.schedule-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 8pt;
    margin-bottom: 3mm;
}
.schedule-table th, .schedule-table td {
    border: 1px solid #000;
    padding: 2.2mm 1.5mm;
    vertical-align: middle;
}
.schedule-table th {
    text-align: center;
    font-weight: bold;
    background: #f1f5f9;
    text-transform: uppercase;
}
.schedule-table td.center {
    text-align: center;
}

/* Legend section */
.legend-box {
    margin-top: 2mm;
    border: 1px solid #cbd5e1;
    border-radius: 4px;
    padding: 2mm 3mm;
    font-size: 8pt;
    background-color: #f8fafc;
}
.legend-title {
    font-weight: bold;
    margin-bottom: 1mm;
    text-transform: uppercase;
    font-size: 8.5pt;
    border-bottom: 1px solid #cbd5e1;
    padding-bottom: 0.5mm;
}
.legend-grid {
    column-count: 4;
    column-gap: 4mm;
}
.legend-item {
    display: flex;
    align-items: flex-start;
    width: 100%;
    font-size: 7.5pt;
    padding: 0.4mm 0;
    box-sizing: border-box;
    break-inside: avoid;
}

/* Signature */
.footer-area {
    display: flex;
    justify-content: flex-end;
    margin-top: auto;
    font-size: 9.5pt;
}
.sig-box {
    text-align: center;
    width: 65mm;
    position: relative;
}
.sig-space {
    height: 10mm;
    position: relative;
}
.sig-name {
    font-weight: bold;
    text-decoration: underline;
}

/* Print Overrides */
@media print {
    body {
        background: white;
        padding: 0;
        margin: 0;
    }
    .preview-header {
        display: none !important;
    }
    .a4-sheet {
        margin: 0;
        box-shadow: none;
        page-break-after: avoid;
    }
    * {
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
}
</style>
</head>
<body>

<div class="preview-header">
    <div>
        <h2>📋 Cetak Jadwal Pengawas Ruang</h2>
        <p>Jadwal tugas pengawas ujian &nbsp;·&nbsp; Kertas Folio (F4) Landscape</p>
    </div>
    <div>
        <button class="btn-back" onclick="window.history.back()">← Kembali</button>
        <button class="btn-print" onclick="window.print()">🖨 Cetak / Simpan PDF</button>
    </div>
</div>

<?php
// Build list of all sessions
$sessions = [];
foreach ($schedules as $sch) {
    foreach ($sch['subjects'] as $sub) {
        $subjectName = is_array($sub) ? ($sub['name'] ?? '') : $sub;
        $subjectTime = is_array($sub) ? ($sub['time'] ?? '') : '';
        if (empty($subjectName)) continue;
        
        $sessions[] = [
            'schedule_id'  => $sch['id'],
            'exam_day'     => $sch['exam_day'],
            'exam_date'    => $sch['exam_date'],
            'subject_name' => $subjectName,
            'subject_time' => $subjectTime,
        ];
    }
}

$globalIdx = 1;
?>

<div class="a4-sheet" style="margin-bottom: 20px;">
    <!-- Title Section (No Kop) -->
    <div class="page-title" style="margin-top: 1mm; font-size: 13pt;">JADWAL PENGAWAS RUANG ASESMEN</div>

    <div class="event-details-bar">
        <span><strong>ASESMEN:</strong> <?= esc($event['name']) ?></span>
        <span><strong>TA.</strong> <?= strtoupper(esc($activePeriod['academic_year_name'] ?? '2025/2026')) ?> (SEMESTER <?= strtoupper(esc($event['semester'] ?? 'GANJIL')) ?>)</span>
    </div>

    <!-- Table -->
    <table class="schedule-table">
        <thead>
            <tr>
                <th width="4%">No</th>
                <th width="15%">Hari/Tanggal</th>
                <th width="15%">Mapel</th>
                <th width="10%">Waktu</th>
                <?php foreach ($rooms as $room): 
                    $shortRoomName = trim(preg_replace('/^ruang\s*/i', 'R', $room['name']));
                ?>
                    <th style="font-size: 7.5pt; font-weight: bold;"><?= esc($shortRoomName) ?></th>
                <?php endforeach; ?>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($sessions)): ?>
                <tr>
                    <td colspan="<?= count($rooms) + 4 ?>" class="text-center py-4 text-muted" style="font-style: italic;">
                        Belum ada data jadwal pengawas
                    </td>
                </tr>
            <?php else: ?>
                <?php 
                // Count schedule_id frequency
                $scheduleCounts = [];
                foreach ($sessions as $sess) {
                    $schId = $sess['schedule_id'];
                    $scheduleCounts[$schId] = ($scheduleCounts[$schId] ?? 0) + 1;
                }
                $printedSchedules = [];
                ?>
                <?php foreach ($sessions as $sess): 
                    $schId = $sess['schedule_id'];
                    $rowspan = $scheduleCounts[$schId];
                    $isFirstForSch = !in_array($schId, $printedSchedules);
                    if ($isFirstForSch) {
                        $printedSchedules[] = $schId;
                    }
                ?>
                <tr>
                    <?php if ($isFirstForSch): ?>
                        <td class="center" rowspan="<?= $rowspan ?>"><?= $globalIdx++ ?></td>
                        <td rowspan="<?= $rowspan ?>" style="font-size: 8pt; font-weight: bold;">
                            <strong><?= esc($sess['exam_day']) ?></strong><br>
                            <span style="font-size: 7.5pt; font-weight: normal; color: #475569;"><?= date('d/m/Y', strtotime($sess['exam_date'])) ?></span>
                        </td>
                    <?php endif; ?>
                    <td style="font-size: 8pt; font-weight: bold; color: #1e293b;"><?= esc($sess['subject_name']) ?></td>
                    <td class="center" style="font-size: 7.5pt; font-family: monospace;"><?= esc($sess['subject_time'] ?: '-') ?></td>
                    <?php foreach ($rooms as $room): 
                        $assign = $assignments[$sess['schedule_id']][$sess['subject_name']][$room['id']] ?? null;
                        $p1_code = '';
                        $p2_code = '';
                        if ($assign) {
                            if (!empty($assign['teacher_id_1']) && isset($teacherLookup[$assign['teacher_id_1']])) {
                                $p1_code = $teacherLookup[$assign['teacher_id_1']]['short_code'] ?: $teacherLookup[$assign['teacher_id_1']]['name'];
                            }
                            if (!empty($assign['teacher_id_2']) && isset($teacherLookup[$assign['teacher_id_2']])) {
                                $p2_code = $teacherLookup[$assign['teacher_id_2']]['short_code'] ?: $teacherLookup[$assign['teacher_id_2']]['name'];
                            }
                        }
                    ?>
                        <td class="center" style="font-weight: bold; font-size: 7.5pt; padding: 2.2mm 0.5mm; line-height: 1.25;">
                            <?php if (!empty($p1_code)): ?>
                                <div style="color: #15803d;"><?= esc($p1_code) ?></div>
                                <?php if (!empty($p2_code)): ?>
                                    <div style="border-top: 1px solid #ddd; margin-top: 0.5mm; padding-top: 0.5mm; color: #0369a1;"><?= esc($p2_code) ?></div>
                                <?php endif; ?>
                            <?php else: ?>
                                <span style="font-weight: normal; color: #cbd5e1;">-</span>
                            <?php endif; ?>
                        </td>
                    <?php endforeach; ?>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>

    <!-- Side-by-Side Footer (Legend & Signature) -->
    <div style="display: flex; gap: 4mm; margin-top: 5mm; align-items: flex-end;">
        <!-- Left Side: Legend Box (65% width) -->
        <div style="flex: 1;">
            <?php if (!empty($assignedTeachers)): ?>
                <div class="legend-box" style="margin-top: 0;">
                    <div class="legend-title">Keterangan Kode Pengawas:</div>
                    <div class="legend-grid">
                        <?php foreach ($assignedTeachers as $t): ?>
                            <div class="legend-item">
                                <strong style="min-width: 8mm; display: inline-block; flex-shrink: 0;"><?= esc($t['short_code'] ?: '-') ?>:</strong>
                                <span style="flex-grow: 1;"><?= esc($t['name']) ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Right Side: Signature Block (35% width) -->
        <div style="width: 70mm; flex-shrink: 0; text-align: center; margin-bottom: 20mm;">
            <div class="sig-box" style="width: 100%; font-size: 9pt;">
                <?php
                $cityName = ucwords(strtolower($schoolSettings['city'] ?? 'Wonogiri'));
                $months = [
                    1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
                    7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
                ];
                $start_time = strtotime($event['start_date']);
                $day = date('d', $start_time);
                $month_num = (int)date('m', $start_time);
                $year = date('Y', $start_time);
                $indonesian_date = $day . ' ' . $months[$month_num] . ' ' . $year;
                ?>
                <div><?= esc($cityName) ?>, <?= esc($indonesian_date) ?></div>
                <div style="margin-bottom: 2mm;">
                    <?php 
                    $schoolName = $schoolSettings['school_name'] ?? '';
                    if (stripos($schoolName, 'Madrasah') !== false || stripos($schoolName, 'MTs') !== false || stripos($schoolName, 'MA') !== false || stripos($schoolName, 'MI') !== false) {
                        echo 'Kepala Madrasah,';
                    } else {
                        echo 'Kepala Sekolah,';
                    }
                    ?>
                </div>
                
                <div class="sig-space" style="height: 10mm; position: relative;">
                    <?php if (!empty($cardSetting['headmaster_signature']) && file_exists(FCPATH . 'uploads/card/' . $cardSetting['headmaster_signature'])): ?>
                        <img src="<?= base_url('uploads/card/' . $cardSetting['headmaster_signature']) ?>" alt="TTD" style="position: absolute; left: 50%; top: -6mm; transform: translateX(-50%); height: 100px; width: auto; z-index: 10;">
                    <?php endif; ?>
                </div>
                
                <div class="sig-name" style="font-weight: bold; text-decoration: underline;"><?= esc($schoolSettings['principal_name'] ?? '') ?></div>
                <div>NIP. <?= esc($schoolSettings['principal_nip'] ?? '-') ?></div>
            </div>
        </div>
    </div>
</div>

</body>
</html>
