<!DOCTYPE html>
<html lang="id">
<head>
    <?php helper('logo'); ?>
    <link rel="icon" type="image/png" href="<?= getLogo('sekolah') ?>">
<meta charset="UTF-8">
<title>Cetak Denah Tempat Duduk - <?= 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 Landscape (297mm x 210mm) */
@page {
    size: A4 landscape;
    margin: 0;
}

.a4-sheet-landscape {
    width: 297mm;
    height: 210mm;
    background: white;
    position: relative;
    page-break-after: always;
    margin: 0 auto 20px;
    padding: 10mm 15mm;
    box-shadow: 0 4px 10px rgba(0,0,0,0.15);
    display: flex;
    flex-direction: column;
}

/* Title & Header info */
.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    border-bottom: 2px solid #000;
    padding-bottom: 2mm;
    margin-bottom: 3mm;
}
.chart-title h3 {
    font-size: 12pt;
    font-weight: bold;
    text-transform: uppercase;
}
.chart-title p {
    font-size: 8.5pt;
    color: #475569;
    margin-top: 1mm;
    text-transform: uppercase;
}
.chart-info {
    text-align: right;
    font-size: 8.5pt;
    line-height: 1.3;
}

/* Papan Tulis / Depan Kelas Indicator */
.front-indicator {
    background: #f1f5f9;
    border: 1.5px solid #475569;
    text-align: center;
    padding: 1.2mm 0;
    font-size: 8.5pt;
    font-weight: bold;
    text-transform: uppercase;
    letter-spacing: 2px;
    border-radius: 4px;
    margin: 1mm auto 4mm auto;
    width: 60%;
}

/* Seating Grid Container */
.grid-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
}

.desk-row {
    display: flex;
    justify-content: space-around;
    gap: 2mm;
}

/* Double Desk Box */
.double-desk {
    border: 1.5px solid #000;
    background: #fff;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}
.desk-header {
    background: #334155;
    color: #fff;
    text-align: center;
    font-size: 6.8pt;
    font-weight: bold;
    padding: 0.6mm 0;
    border-bottom: 1px solid #000;
    letter-spacing: 0.5px;
}
.desk-seats {
    display: flex;
    height: 19.5mm;
}
.seat {
    width: 50%;
    padding: 1.2mm 1.5mm;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    font-size: 6.5pt;
    height: 100%;
}
.seat:first-child {
    border-right: 1.5px dashed #64748b;
}

.seat-num {
    font-weight: bold;
    color: #475569;
    border-bottom: 0.2mm solid #e2e8f0;
    padding-bottom: 0.5mm;
    margin-bottom: 0.5mm;
    display: flex;
    justify-content: space-between;
}
.seat-class {
    background: #f1f5f9;
    padding: 0.1mm 0.8mm;
    border-radius: 2px;
    font-size: 5.5pt;
    font-weight: bold;
}
.seat-name {
    font-weight: bold;
    color: #000;
    line-height: 1.15;
    word-break: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    margin-top: 0.5mm;
}
.seat-number-str {
    font-size: 5.5pt;
    color: #64748b;
    margin-top: auto;
}

/* Empty Seat styling */
.seat.empty {
    background: #f8fafc;
    justify-content: center;
    align-items: center;
    color: #cbd5e1;
    font-style: italic;
}

/* Footer info */
.chart-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 3mm;
    font-size: 7.5pt;
    color: #475569;
    border-top: 1px solid #cbd5e1;
    padding-top: 1.5mm;
}

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

<div class="preview-header">
    <div>
        <h2>🗺 Cetak Denah Duduk Peserta</h2>
        <p><?= count($rooms) ?> ruang &nbsp;·&nbsp; Kertas A4 Landscape &nbsp;·&nbsp; Denah Fleksibel / Fluid</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 foreach ($rooms as $room): 
    $roomSeats = $seatsByRoom[$room['id']] ?? [];
    $totalStudents = count($roomSeats);
    
    // Count students per class in this room
    $classCounts = [];
    foreach ($roomSeats as $seat) {
        if (!empty($seat['classroom_name'])) {
            $cName = $seat['classroom_name'];
            $classCounts[$cName] = ($classCounts[$cName] ?? 0) + 1;
        }
    }
    
    $hasOver20 = false;
    foreach ($classCounts as $cName => $count) {
        if ($count > 20) {
            $hasOver20 = true;
            break;
        }
    }
    
    // Calculate R_c for each column (c = 1, 2, 3, 4)
    $R_cols = [];
    if ($totalStudents <= 0) {
        $R_cols = [5, 5, 5, 5];
        $max_R = 5;
    } else {
        $M = ceil($totalStudents / 2); // desks needed
        
        // Fluid max 5 base. But if there is a class with > 20 students OR total students > 40, max can be 6.
        $maxR = ($hasOver20 || $totalStudents > 40) ? 6 : 5;
        
        if ($M <= 20) {
            $R = ceil($M / 4);
            $R_cols = [$R, $R, $R, $R];
            $max_R = $R;
        } else {
            // M > 20. Base height is 5 for all columns.
            // Distribute remaining desks to the rightmost columns first, up to max 6 desks per column.
            $extra = $M - 20;
            $R_cols = [
                5 + ($extra >= 4 ? 1 : 0),
                5 + ($extra >= 3 ? 1 : 0),
                5 + ($extra >= 2 ? 1 : 0),
                5 + ($extra >= 1 ? 1 : 0)
            ];
            $max_R = max($R_cols);
        }
    }
?>
<style>
    /* Custom width scaling based on column count to prevent overflow */
    #room-grid-<?= $room['id'] ?> .double-desk {
        width: <?= (255 / 4) - 3 ?>mm;
    }
    #room-grid-<?= $room['id'] ?> .desk-seats {
        height: <?= $max_R === 6 ? '16.5mm' : '19.5mm' ?>;
    }
</style>

<div class="a4-sheet-landscape" id="room-grid-<?= $room['id'] ?>">
    <div class="chart-header">
        <div class="chart-title">
            <h3>DENAH TEMPAT DUDUK PESERTA</h3>
            <p><?= esc($event['name']) ?></p>
        </div>
        <div class="chart-info">
            <strong>RUANG: <?= strtoupper(esc($room['name'])) ?></strong><br>
            Jumlah Peserta: <?= esc($totalStudents) ?> Siswa (Grid: <?= implode('-', $R_cols) ?> Meja)<br>
            Tahun Ajaran: <?= esc($event['academic_year'] ?? '2025/2026') ?>
        </div>
    </div>

    <!-- Papan Tulis / Depan Kelas -->
    <div class="front-indicator">PAPAN TULIS / MEJA PENGAWAS</div>

    <!-- Seating Grid -->
    <div class="grid-container">
        <?php 
        // Loop Baris r = 1 s.d max_R (Baris 1 paling depan dekat papan tulis)
        for ($r = 1; $r <= $max_R; $r++):
        ?>
            <div class="desk-row">
                <?php 
                // Loop Kolom c = 1 s.d 4
                for ($c = 1; $c <= 4; $c++):
                    $colLimit = $R_cols[$c - 1];
                    
                    if ($r <= $colLimit) {
                        // Formula desk index serpentine based on varying column heights:
                        if ($c === 1) {
                            $i = $r;
                        } elseif ($c === 2) {
                            $i = $R_cols[0] + ($R_cols[1] - $r + 1);
                        } elseif ($c === 3) {
                            $i = $R_cols[0] + $R_cols[1] + $r;
                        } else {
                            $i = $R_cols[0] + $R_cols[1] + $R_cols[2] + ($R_cols[3] - $r + 1);
                        }

                        // Sisi Kiri (Ganjil)
                        $seatLeftNum = 2 * $i - 1;
                        $studentLeft = $roomSeats[$seatLeftNum] ?? null;

                        // Sisi Kanan (Genap)
                        $seatRightNum = 2 * $i;
                        $studentRight = $roomSeats[$seatRightNum] ?? null;
                ?>
                        <!-- Meja i -->
                        <div class="double-desk">
                            <div class="desk-header">MEJA <?= $i ?></div>
                            <div class="desk-seats">
                                
                                <!-- Kursi Kiri -->
                                <?php if ($studentLeft): ?>
                                    <div class="seat">
                                        <div class="seat-num">
                                            <span>Kursi <?= $seatLeftNum ?></span>
                                            <span class="seat-class"><?= strtoupper(esc($studentLeft['classroom_name'])) ?></span>
                                        </div>
                                        <div class="seat-name"><?= strtoupper(esc($studentLeft['full_name'])) ?></div>
                                        <div class="seat-number-str"><?= esc($studentLeft['exam_number']) ?></div>
                                    </div>
                                <?php else: ?>
                                    <div class="seat empty">
                                        <span>KOSONG</span>
                                    </div>
                                <?php endif; ?>

                                <!-- Kursi Kanan -->
                                <?php if ($studentRight): ?>
                                    <div class="seat">
                                        <div class="seat-num">
                                            <span>Kursi <?= $seatRightNum ?></span>
                                            <span class="seat-class"><?= strtoupper(esc($studentRight['classroom_name'])) ?></span>
                                        </div>
                                        <div class="seat-name"><?= strtoupper(esc($studentRight['full_name'])) ?></div>
                                        <div class="seat-number-str"><?= esc($studentRight['exam_number']) ?></div>
                                    </div>
                                <?php else: ?>
                                    <div class="seat empty">
                                        <span>KOSONG</span>
                                    </div>
                                <?php endif; ?>

                            </div>
                        </div>
                <?php 
                    } else {
                        // Invisible spacer for alignment
                ?>
                        <div class="double-desk" style="border: none; background: transparent; box-shadow: none; visibility: hidden;"></div>
                <?php 
                    }
                endfor; 
                ?>
            </div>
        <?php endfor; ?>
    </div>

    <!-- Footer -->
    <div class="chart-footer">
        <span>* Penempatan fluid otomatis: <?= $max_R ?> baris ke belakang (maksimal 6) disesuaikan agar terbagi rata.</span>
        <span>Dicetak tanggal: <?= $printDate ?></span>
    </div>
</div>
<?php endforeach; ?>

</body>
</html>
