<!DOCTYPE html>
<html lang="id">
<head>
    <?php helper('logo'); ?>
    <link rel="icon" type="image/png" href="<?= getLogo('sekolah') ?>">
<meta charset="UTF-8">
<title>Cetak Rekap Peserta per Ruang - <?= 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: A4 Portrait */
@page {
    size: A4 portrait;
    margin: 0;
}

.a4-sheet {
    width: 210mm;
    height: 297mm;
    background: white;
    position: relative;
    margin: 0 auto 20px;
    padding: 10mm 15mm;
    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: 13pt;
    font-weight: bold;
    text-transform: uppercase;
    margin-top: 2mm;
    margin-bottom: 4mm;
    text-decoration: underline;
    letter-spacing: 0.5px;
}

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

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

/* Signature */
.footer-area {
    display: flex;
    justify-content: flex-end;
    margin-top: auto;
    font-size: 12pt;
}
.sig-box {
    text-align: center;
    width: 60mm;
}
.sig-space {
    height: 18mm;
}
.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>📊 Rekapitulasi Peserta per Ruang</h2>
        <p>Ringkasan alokasi ujian &nbsp;·&nbsp; Kertas A4 Portrait</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
$pages = [];
$temp = $rooms;
$isFirst = true;
while (!empty($temp)) {
    // Page 1 takes up to 22 rooms due to Kop/Header. Page 2+ takes up to 28.
    $chunkSize = $isFirst ? 22 : 28;
    $pages[] = array_splice($temp, 0, $chunkSize);
    $isFirst = false;
}
if (empty($pages)) {
    $pages[] = [];
}

$globalIdx = 1;
$totalPages = count($pages);
$sumAllocated = 0;

// Calculate total global allocated sum first
foreach ($rooms as $room) {
    $roomId = $room['id'];
    $roomRules = $rulesByRoom[$roomId] ?? [];
    foreach ($roomRules as $rule) {
        $count = $rule['end_absen'] - $rule['start_absen'] + 1;
        $sumAllocated += $count;
    }
}
?>

<?php foreach ($pages as $pIdx => $pageRooms): 
    $isFirstPage = ($pIdx === 0);
    $isLastPage = ($pIdx === $totalPages - 1);
?>
<div class="a4-sheet" style="page-break-after: always; margin-bottom: 20px;">
    <?php if ($isFirstPage): ?>
        <!-- Official Kop -->
        <?= view('letter/_kop', ['letterSettings' => $letterSettings, 'schoolSettings' => $schoolSettings]) ?>

        <div class="page-title">REKAPITULASI PESERTA PER RUANG ASESMEN</div>

        <div class="event-details-bar">
            <span><strong>ASESMEN:</strong> <?= esc($event['name']) ?></span>
            <span><strong>TA.</strong> <?= strtoupper(esc($letterSettings['academic_year'] ?? $event['academic_year'] ?? '2025/2026')) ?> (SEMESTER <?= strtoupper(esc($event['semester'] ?? 'GANJIL')) ?>)</span>
        </div>
    <?php else: ?>
        <!-- Simplified header for page 2+ -->
        <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1.5px solid #000; padding-bottom: 1.5mm; margin-bottom: 4mm; font-size: 8pt; font-weight: bold; text-transform: uppercase;">
            <span>Rekapitulasi Peserta — <?= esc($event['name']) ?></span>
            <span>Halaman <?= ($pIdx + 1) ?> dari <?= $totalPages ?></span>
        </div>
    <?php endif; ?>

    <!-- Table -->
    <table class="summary-table">
        <thead>
            <tr>
                <th width="8%">No</th>
                <th width="30%">Nama Ruang</th>
                <th width="42%">Rincian Peserta</th>
                <th width="20%">Jumlah Peserta</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($pageRooms)): ?>
                <tr>
                    <td colspan="4" class="text-center py-4 text-muted" style="font-style: italic;">
                        Belum ada data ruang ujian
                    </td>
                </tr>
            <?php else: 
                foreach ($pageRooms as $room):
                    $roomId = $room['id'];
                    $roomRules = $rulesByRoom[$roomId] ?? [];
                    
                    // Format detail text: "7A : 1-16 | 8A : 1-16"
                    $detailParts = [];
                    $totalAllocatedInRoom = 0;
                    foreach ($roomRules as $rule) {
                        $className = $rule['classroom_name'] ?? '-';
                        $start = $rule['start_absen'];
                        $end = $rule['end_absen'];
                        $count = $end - $start + 1;
                        
                        $detailParts[] = "{$className} : {$start}-{$end}";
                        $totalAllocatedInRoom += $count;
                    }
                    $detailText = empty($detailParts) ? '-' : implode(' | ', $detailParts);
            ?>
                <tr>
                    <td class="center"><?= $globalIdx++ ?></td>
                    <td><strong><?= esc($room['name']) ?></strong></td>
                    <td><?= esc($detailText) ?></td>
                    <td class="center fw-bold"><?= $totalAllocatedInRoom ?> Siswa</td>
                </tr>
                <?php endforeach; ?>
                
                <?php if ($isLastPage): ?>
                    <!-- Total Row -->
                    <tr class="total-row">
                        <td colspan="3" class="center">TOTAL GLOBAL</td>
                        <td class="center"><?= $sumAllocated ?> Siswa</td>
                    </tr>
                <?php endif; ?>
            <?php endif; ?>
        </tbody>
    </table>

    <?php if ($isLastPage): ?>
        <!-- Footer Signature -->
        <div class="footer-area" style="margin-top: 8mm;">
            <div class="sig-box">
                <?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>
                    <?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"></div>
                <div class="sig-name"><?= esc($schoolSettings['principal_name'] ?? '') ?></div>
                <div>NIP. <?= esc($schoolSettings['principal_nip'] ?? '-') ?></div>
            </div>
        </div>
    <?php endif; ?>
</div>
<?php endforeach; ?>

</body>
</html>
