<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="container-fluid py-4">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <div class="d-flex align-items-center gap-2">
            <a href="/exam-event" class="btn btn-outline-secondary btn-sm">
                <i class="bi bi-arrow-left"></i>
            </a>
            <div>
                <h4 class="mb-0 fw-bold">Alokasi & Validasi Peserta</h4>
                <small class="text-muted">Petakan siswa ke ruang ujian secara silang tingkat dan kunci penempatan</small>
            </div>
        </div>
        
        <div>
            <?php if ($event['is_locked']): ?>
                <form action="/exam-event/<?= $event['id'] ?>/unfinalize" method="POST" onsubmit="return confirm('Membuka kunci alokasi akan menghapus seluruh nomor peserta dan nomor meja yang telah digenerate. Lanjutkan?')">
                    <?= csrf_field() ?>
                    <button type="submit" class="btn btn-danger btn-lg shadow-sm">
                        <i class="bi bi-unlock-fill me-1"></i> Buka Kunci Alokasi
                    </button>
                </form>
            <?php else: ?>
                <form action="/exam-event/<?= $event['id'] ?>/finalize" method="POST">
                    <?= csrf_field() ?>
                    <button type="submit" class="btn btn-success btn-lg shadow-sm" 
                        <?= (empty($rooms) || !empty($validation['duplicates']) || !empty($validation['overloaded']) || !empty($validation['missing'])) ? 'disabled' : '' ?>>
                        <i class="bi bi-lock-fill me-1"></i> Kunci & Generate Peserta
                    </button>
                </form>
            <?php endif; ?>
        </div>
    </div>

    <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?= session()->getFlashdata('success') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?= session()->getFlashdata('error') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- TAMPILAN STATUS LOCK - PREMIUM DASHBOARD -->
    <?php if ($event['is_locked']): ?>
        <style>
        .hover-lift {
            transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out !important;
        }
        .hover-lift:hover {
            transform: translateY(-3px) !important;
            box-shadow: 0 .5rem 1rem rgba(0,0,0,.08) !important;
        }
        .text-purple {
            color: #6f42c1 !important;
        }
        .bg-purple-light {
            background-color: rgba(111, 66, 193, 0.1) !important;
        }
        </style>
        <div class="card shadow-sm border-0 mb-4 bg-white overflow-hidden" style="border-radius: 12px;">
            <div class="card-body p-4 bg-light bg-gradient">
                <div class="row align-items-center">
                    <div class="col-md-8 d-flex align-items-center gap-3">
                        <div class="bg-success bg-opacity-10 text-success rounded-circle p-3 d-flex align-items-center justify-content-center shadow-sm" style="width: 64px; height: 64px; border: 1px solid rgba(25, 135, 84, 0.2);">
                            <i class="bi bi-shield-lock-fill fs-2 text-success"></i>
                        </div>
                        <div>
                            <h5 class="mb-1 fw-bold text-dark">Administrasi Ujian Resmi Dikunci</h5>
                            <p class="text-muted small mb-0">Seluruh nomor peserta dan denah duduk telah digenerate secara otomatis. Silakan cetak kelengkapan ujian melalui panel di bawah ini.</p>
                        </div>
                    </div>
                    <div class="col-md-4 text-md-end mt-3 mt-md-0">
                        <span class="badge bg-success bg-opacity-10 text-success border border-success px-3 py-2 fw-semibold" style="font-size: 0.85rem;">
                            <i class="bi bi-check-circle-fill me-1"></i> Terfinalisasi & Aktif
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- PRINT HUB / PUSAT CETAK DOKUMEN -->
        <h5 class="fw-bold text-dark mb-3"><i class="bi bi-printer-fill text-primary me-2"></i>Pusat Cetak Dokumen Ujian</h5>
        <div class="row g-3 mb-4">
            <!-- 1. Kartu Peserta -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/cards" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #0d6efd !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-primary bg-opacity-10 text-primary rounded">
                            <i class="bi bi-credit-card fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Kartu Peserta</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Layout Folio/F4, 4 kartu per halaman</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- 2. Kartu Meja -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/desk-labels" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #6f42c1 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-purple-light text-purple rounded">
                            <i class="bi bi-tags-fill fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Kartu Meja</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Ukuran pas dengan label nomor meja</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- 3. Daftar Hadir -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/attendance" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #198754 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-success bg-opacity-10 text-success rounded">
                            <i class="bi bi-journal-check fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Daftar Hadir Ruangan</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Layout A4 per ruang ujian (Margin 1cm)</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- 4. Denah Tempat Duduk -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/seating-chart" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #fd7e14 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-warning bg-opacity-10 text-warning rounded">
                            <i class="bi bi-grid-3x3-gap-fill fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Denah Tempat Duduk</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Layout A4 Landscape, penataan fluid cerdas</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- 5. Berita Acara -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/official-report" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #20c997 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-info bg-opacity-10 text-info rounded" style="color: #20c997; background-color: rgba(32, 201, 151, 0.1);">
                            <i class="bi bi-file-earmark-ruled-fill fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Berita Acara Ujian</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Master blanko A4 untuk digandakan</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- 6. Rekap Peserta -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/room-summary" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #6c757d !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-secondary bg-opacity-10 text-secondary rounded">
                            <i class="bi bi-table fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Rekapitulasi Ruang</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Tabel ringkasan rincian peserta asal</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- Jadwal Pengawas -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/proctor-schedule" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #0dcaf0 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-info bg-opacity-10 text-info rounded" style="background-color: rgba(13, 202, 240, 0.1); color: #0dcaf0;">
                            <i class="bi bi-person-badge-fill fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Jadwal Pengawas</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Matrik jadwal mengawas ruang dan legenda kode</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- Jadwal Asesmen -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/exam-schedule" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #ffc107 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-warning bg-opacity-10 text-warning rounded">
                            <i class="bi bi-calendar-check-fill fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Jadwal Asesmen</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Jadwal asesmen untuk dibagikan ke siswa</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- Daftar Hadir Pengawas -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/proctor-attendance" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #198754 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-success bg-opacity-10 text-success rounded">
                            <i class="bi bi-journal-text fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Hadir Pengawas</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Lembar daftar hadir pengawas per sesi ujian (A4)</p>
                        </div>
                    </div>
                </a>
            </div>
        </div>

        <h5 class="fw-bold text-dark mb-3 mt-4"><i class="bi bi-door-open-fill text-success me-2"></i>Kelengkapan Tempel Pintu & Informasi Ruang</h5>
        <div class="row g-3 mb-4">
            <!-- 7. Daftar Peserta Ruang -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/room-participants" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #0dcaf0 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-info bg-opacity-10 text-info rounded" style="background-color: rgba(13, 202, 240, 0.1); color: #0dcaf0;">
                            <i class="bi bi-card-list fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Daftar Peserta Ruang</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Daftar nama & kelas per ruang (Tempel Pintu)</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- 8. Label Pintu & Rekap -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/door-label" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #ffc107 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-warning bg-opacity-10 text-warning rounded">
                            <i class="bi bi-door-closed fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Label Pintu & Rekap</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Label nama ruang & rincian siswa asal A4 Landscape</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- 9. Tanda Bel -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/bell-schedule" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #d63384 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-danger bg-opacity-10 text-danger rounded" style="background-color: rgba(214, 51, 132, 0.1); color: #d63384;">
                            <i class="bi bi-bell fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Ketentuan Tanda Bel</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Daftar bunyi & waktu ketukan bel ujian</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- 10. Tata Tertib Pengawas -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/proctor-rules" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #fd7e14 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-warning bg-opacity-10 text-warning rounded" style="background-color: rgba(253, 126, 20, 0.1); color: #fd7e14;">
                            <i class="bi bi-person-badge fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Tata Tertib Pengawas</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Aturan kode etik pengawas ruang ujian</p>
                        </div>
                    </div>
                </a>
            </div>
            <!-- 11. Tata Tertib Peserta -->
            <div class="col-md-4 col-sm-6">
                <a href="/exam-event/<?= $event['id'] ?>/print/student-rules" target="_blank" class="card h-100 border-0 shadow-sm bg-white text-decoration-none hover-lift" style="border-left: 5px solid #20c997 !important; border-radius: 8px;">
                    <div class="card-body p-3 d-flex align-items-center gap-3">
                        <div class="p-2 bg-success bg-opacity-10 text-success rounded" style="background-color: rgba(32, 201, 151, 0.1); color: #20c997;">
                            <i class="bi bi-people fs-4"></i>
                        </div>
                        <div>
                            <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem;">Tata Tertib Peserta</h6>
                            <p class="text-muted mb-0 small" style="font-size: 0.78rem;">Aturan dan larangan peserta asesmen</p>
                        </div>
                    </div>
                </a>
            </div>
        </div>
    <?php endif; ?>

    <!-- VISUAL PAIRING PLANNER CARD -->
    <?php if (!$event['is_locked']): ?>
    <div class="card shadow-sm border-0 mb-4 bg-white">
        <div class="card-header fw-bold bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
            <div>
                <i class="bi bi-grid-3x3-gap-fill me-2 text-primary"></i>Visual Pairing Planner (Penyusunan Rencana Silang)
                <span id="save-status-indicator" class="ms-3 small fw-normal text-muted" style="transition: opacity 0.3s ease;"></span>
            </div>
            <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#collapsePlanner" aria-expanded="true">
                <i class="bi bi-chevron-up" id="plannerCollapseIcon"></i>
            </button>
        </div>
        <div class="collapse show" id="collapsePlanner">
            <div class="card-body p-4">
                <div class="alert alert-info py-2 px-3 small border-0 mb-4 d-flex align-items-center bg-info bg-opacity-10 text-info-emphasis">
                    <i class="bi bi-info-circle-fill me-2 fs-5 text-info"></i>
                    <div>
                        <strong>Panduan Penyusunan Rencana:</strong> Drag & drop (geser) kartu kelas ke atas/bawah di setiap kolom untuk menyelaraskan baris kelas secara horizontal. Sistem akan menghitung selisih jumlah siswa secara real-time. Klik tombol <strong>Gunakan</strong> di kartu kelas untuk memasukkan kelas ke form alokasi di bawah.
                    </div>
                </div>

                <div class="row g-3 mb-2">
                    <?php 
                    $activeLevels = array_keys($levelsData ?? []);
                    $colWidth = count($activeLevels) > 0 ? floor(12 / count($activeLevels)) : 12;
                    if ($colWidth < 3) $colWidth = 3;
                    ?>
                    
                    <?php foreach ($activeLevels as $lvl): ?>
                        <div class="col-md-<?= $colWidth ?>">
                            <div class="bg-light bg-opacity-75 rounded p-3 border">
                                <h6 class="fw-bold mb-3 border-bottom pb-2 text-dark" style="font-size: 0.9rem;">
                                    <i class="bi bi-tag-fill me-1 text-primary"></i>Tingkat <?= esc($lvl) ?>
                                </h6>
                                <div class="planner-column d-flex flex-column gap-2" id="planner-col-<?= esc($lvl) ?>" data-level="<?= esc($lvl) ?>" style="min-height: 200px;">
                                    <!-- Draggable cards will be outputted here dynamically by JS -->
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- Live pairing metrics table -->
                <div class="mt-4">
                    <h6 class="fw-bold mb-2 small text-uppercase text-secondary"><i class="bi bi-calculator me-1"></i>Analisis Kelayakan Pasangan Baris</h6>
                    <div class="table-responsive border rounded">
                        <table class="table table-hover align-middle mb-0" id="pairing-metrics-table">
                            <thead class="table-light">
                                <tr style="font-size: 0.8rem;">
                                    <th width="10%" class="text-center">Baris</th>
                                    <th width="60%">Pasangan Kelas (Siswa)</th>
                                    <th width="15%" class="text-center">Selisih</th>
                                    <th width="15%" class="text-center">Kelayakan</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Rows generated dynamically by JS -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="row g-4">
        
        <!-- KOLOM KIRI: FORM & ATURAN MAPPING RUANG -->
        <div class="col-lg-8">
            
            <!-- FORM MAPPING (Hanya jika belum dikunci) -->
            <?php if (!$event['is_locked']): ?>
                <div class="card shadow-sm border-0 mb-4">
                    <div class="card-header fw-semibold bg-white border-bottom py-3">
                        <i class="bi bi-plus-circle-fill me-2 text-success"></i>Tambah Aturan Penempatan Peserta
                    </div>
                    <div class="card-body p-4">
                        <form action="/exam-event/<?= $event['id'] ?>/allocation/save-rule" method="POST">
                            <?= csrf_field() ?>
                            <div class="row g-3">
                                <!-- Pilih Ruang -->
                                <div class="col-md-3">
                                    <label class="form-label small fw-bold">Pilih Ruang Ujian</label>
                                    <select name="exam_room_id" class="form-select" required>
                                        <option value="">-- Ruang --</option>
                                        <?php foreach ($rooms as $room): ?>
                                            <option value="<?= $room['id'] ?>">
                                                <?= esc($room['name']) ?> (Sisa: <?= esc($room['capacity'] - $room['allocated_count']) ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <!-- Pilih Kelas -->
                                <div class="col-md-3">
                                    <label class="form-label small fw-bold">Pilih Kelas</label>
                                    <select name="classroom_id" class="form-select" required>
                                        <option value="">-- Kelas --</option>
                                        <?php foreach ($classrooms as $c): ?>
                                            <?php 
                                            $totalSiswa = $studentCounts[$c['id']] ?? 0;
                                            if ($totalSiswa > 0):
                                            ?>
                                            <option value="<?= $c['id'] ?>">
                                                <?= esc($c['name']) ?> (<?= $totalSiswa ?> siswa)
                                            </option>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <!-- Absen Awal -->
                                <div class="col-md-2">
                                    <label class="form-label small fw-bold">Absen Awal</label>
                                    <input type="number" name="start_absen" class="form-control" min="1" placeholder="1" required>
                                </div>
                                <!-- Absen Akhir -->
                                <div class="col-md-2">
                                    <label class="form-label small fw-bold">Absen Akhir</label>
                                    <input type="number" name="end_absen" class="form-control" min="1" placeholder="10" required>
                                </div>
                                <!-- Tombol Save -->
                                <div class="col-md-2 d-flex align-items-end">
                                    <button type="submit" class="btn btn-success w-100">
                                        <i class="bi bi-plus-lg me-1"></i> Tempatkan
                                    </button>
                                </div>
                            </div>
                            <div class="form-text mt-2 text-muted">
                                <i class="bi bi-info-circle me-1"></i> Urutan nomor absen mengikuti alfabetis nama siswa aktif pada periode ini.
                            </div>
                        </form>
                    </div>
                </div>
            <?php endif; ?>

            <!-- DAFTAR ALOKASI RUANG -->
            <div class="card shadow-sm border-0">
                <div class="card-header fw-semibold bg-white border-bottom py-3">
                    <i class="bi bi-door-closed-fill me-2 text-primary"></i>Kondisi Pengisian Ruangan
                </div>
                <div class="card-body p-4">
                    <div class="row g-4">
                        <?php if (empty($rooms)): ?>
                            <div class="col-12 text-center py-5 text-muted">
                                <i class="bi bi-house-exclamation fs-3 d-block mb-2"></i>
                                Belum ada ruang ujian. Silakan buat ruang ujian terlebih dahulu.
                            </div>
                        <?php else: ?>
                            <?php foreach ($rooms as $room): 
                                $pct = $room['capacity'] > 0 ? round(($room['allocated_count'] / $room['capacity']) * 100) : 0;
                                $barColor = $pct > 100 ? 'bg-danger' : ($pct === 100 ? 'bg-success' : 'bg-primary');
                            ?>
                                <div class="col-md-6">
                                    <div class="border rounded p-3 bg-light bg-opacity-50 h-100">
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <h6 class="fw-bold mb-0 text-dark"><?= esc($room['name']) ?></h6>
                                            <small class="fw-semibold text-muted">
                                                <?= esc($room['allocated_count']) ?> / <?= esc($room['capacity']) ?> Kursi
                                            </small>
                                        </div>
                                        
                                        <!-- Progress Bar -->
                                        <div class="progress mb-3" style="height: 8px;">
                                            <div class="progress-bar <?= $barColor ?>" role="progressbar" style="width: <?= $pct ?>%" aria-valuenow="<?= $pct ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                        </div>

                                        <!-- List Aturan Di Ruang Ini -->
                                        <div class="small-rules-list">
                                            <?php if (empty($room['rules'])): ?>
                                                <small class="text-muted d-block py-2 italic"><i class="bi bi-dash"></i> Belum ada siswa ditempatkan</small>
                                            <?php else: ?>
                                                <ul class="list-group list-group-flush border-top border-bottom">
                                                    <?php foreach ($room['rules'] as $rule): ?>
                                                        <li class="list-group-item d-flex justify-content-between align-items-center bg-transparent py-2 px-0">
                                                            <div>
                                                                <i class="bi bi-person-fill text-muted me-1"></i>
                                                                Kelas <strong><?= esc($rule['classroom_name']) ?></strong> 
                                                                (Absen <?= esc($rule['start_absen']) ?> - <?= esc($rule['end_absen']) ?>)
                                                                <span class="badge bg-secondary-subtle text-secondary ms-1"><?= esc($rule['end_absen'] - $rule['start_absen'] + 1) ?> siswa</span>
                                                            </div>
                                                            <?php if (!$event['is_locked']): ?>
                                                                <a href="/exam-event/allocation/delete-rule/<?= $rule['id'] ?>" class="btn btn-link btn-sm text-danger p-0 border-0" title="Hapus Aturan" onclick="return confirm('Hapus aturan penempatan ini?')">
                                                                    <i class="bi bi-x-circle-fill"></i>
                                                                </a>
                                                            <?php endif; ?>
                                                        </li>
                                                    <?php endforeach; ?>
                                                </ul>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

        </div>

        <!-- KOLOM KANAN: SUMMARY MONITORING VALIDASI -->
        <div class="col-lg-4">
            
            <!-- RINGKASAN MONITORING -->
            <div class="card shadow-sm border-0 mb-4 bg-primary text-white">
                <div class="card-body p-4">
                    <h6 class="fw-bold mb-3"><i class="bi bi-speedometer me-2"></i>Status Alokasi Global</h6>
                    <div class="row align-items-center g-3">
                        <div class="col-6">
                            <div class="display-6 fw-bold"><?= $validation['total_allocated'] ?></div>
                            <small class="opacity-75">Teralokasi</small>
                        </div>
                        <div class="col-6 border-start border-white border-opacity-25">
                            <div class="display-6 fw-bold"><?= $validation['total_eligible'] ?></div>
                            <small class="opacity-75">Total Siswa Aktif</small>
                        </div>
                    </div>
                    <?php 
                    $globalPct = $validation['total_eligible'] > 0 ? round(($validation['total_allocated'] / $validation['total_eligible']) * 100) : 0;
                    ?>
                    <div class="progress mt-3 bg-white bg-opacity-25" style="height: 6px;">
                        <div class="progress-bar bg-white" role="progressbar" style="width: <?= $globalPct ?>%" aria-valuenow="<?= $globalPct ?>" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                    <div class="d-flex justify-content-between mt-2 small opacity-75">
                        <span>Persentase Teralokasi</span>
                        <span><?= $globalPct ?>%</span>
                    </div>
                </div>
            </div>

            <!-- SARAN PENYANDINGAN KELAS (SMART CROSS-PAIRING) -->
            <?php if (!$event['is_locked']): ?>
            <div class="card shadow-sm border-0 mb-4 bg-light bg-gradient">
                <div class="card-header fw-semibold bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <div>
                        <i class="bi bi-magic me-2 text-info"></i>Saran Silang Kelas
                    </div>
                    <span class="badge bg-info-subtle text-info small">Rekomendasi</span>
                </div>
                <div class="card-body p-3">
                    <p class="small text-muted mb-3" style="font-size: 0.8rem;">
                        <i class="bi bi-info-circle me-1"></i> Klik nama kelas di bawah untuk mengisi formulir alokasi secara otomatis.
                    </p>

                    <!-- Triplets (3 Kelas) -->
                    <?php if (!empty($recommendations['triplets'])): ?>
                        <div class="mb-3">
                            <h6 class="fw-bold small text-uppercase text-secondary mb-2" style="font-size: 0.72rem; letter-spacing: 0.05em;">Silang 3 Tingkat</h6>
                            <div class="list-group list-group-flush border rounded overflow-hidden">
                                <?php foreach ($recommendations['triplets'] as $t): ?>
                                    <div class="list-group-item bg-white p-2">
                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                            <span class="badge <?= $t['badgeClass'] ?> text-white font-size-xs" style="font-size:0.65rem; padding: 2px 5px;"><?= $t['quality'] ?></span>
                                            <small class="text-muted" style="font-size:0.7rem;">Rentang: <?= $t['diff'] ?> siswa</small>
                                        </div>
                                        <div class="d-flex gap-1 align-items-center flex-wrap">
                                            <?php foreach ($t['classes'] as $cls): ?>
                                                <button type="button" class="btn btn-sm <?= $cls['is_full'] ? 'btn-success bg-opacity-25 text-success border-success' : 'btn-outline-secondary' ?> btn-suggestion-fill py-0 px-2 fw-semibold" style="font-size: 0.75rem;" 
                                                        data-class-id="<?= $cls['id'] ?>" 
                                                        data-next-start="<?= $cls['next_start'] ?>" 
                                                        data-next-end="<?= $cls['next_end'] ?>"
                                                        data-sisa="<?= $cls['sisa'] ?>"
                                                        title="<?= $cls['is_full'] ? 'Kelas selesai teralokasi' : 'Isi otomatis sisa siswa' ?>">
                                                    <?= esc($cls['name']) ?> (<?= $cls['count'] ?><?= !$cls['is_full'] && $cls['sisa'] !== $cls['count'] ? ', sisa: ' . $cls['sisa'] : '' ?><?= $cls['is_full'] ? ' ✓' : '' ?>)
                                                </button>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Pairs (2 Kelas) -->
                    <?php if (!empty($recommendations['pairs'])): ?>
                        <div>
                            <h6 class="fw-bold small text-uppercase text-secondary mb-2" style="font-size: 0.72rem; letter-spacing: 0.05em;">Silang 2 Tingkat</h6>
                            <div class="list-group list-group-flush border rounded overflow-hidden">
                                <?php foreach ($recommendations['pairs'] as $p): ?>
                                    <div class="list-group-item bg-white p-2">
                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                            <span class="badge <?= $p['badgeClass'] ?> text-white font-size-xs" style="font-size:0.65rem; padding: 2px 5px;"><?= $p['quality'] ?></span>
                                            <small class="text-muted" style="font-size:0.7rem;">Selisih: <?= $p['diff'] ?> siswa</small>
                                        </div>
                                        <div class="d-flex gap-1 align-items-center flex-wrap">
                                            <?php foreach ($p['classes'] as $cls): ?>
                                                <button type="button" class="btn btn-sm <?= $cls['is_full'] ? 'btn-success bg-opacity-25 text-success border-success' : 'btn-outline-secondary' ?> btn-suggestion-fill py-0 px-2 fw-semibold" style="font-size: 0.75rem;" 
                                                        data-class-id="<?= $cls['id'] ?>" 
                                                        data-next-start="<?= $cls['next_start'] ?>" 
                                                        data-next-end="<?= $cls['next_end'] ?>"
                                                        data-sisa="<?= $cls['sisa'] ?>"
                                                        title="<?= $cls['is_full'] ? 'Kelas selesai teralokasi' : 'Isi otomatis sisa siswa' ?>">
                                                    <?= esc($cls['name']) ?> (<?= $cls['count'] ?><?= !$cls['is_full'] && $cls['sisa'] !== $cls['count'] ? ', sisa: ' . $cls['sisa'] : '' ?><?= $cls['is_full'] ? ' ✓' : '' ?>)
                                                </button>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if (empty($recommendations['triplets']) && empty($recommendations['pairs'])): ?>
                        <div class="text-center py-2 text-muted small">
                            <i class="bi bi-slash-circle me-1"></i> Belum ada rekomendasi
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- LAPORAN VALIDASI (PRE-LOCK REPORT) -->
            <div class="card shadow-sm border-0">
                <div class="card-header fw-semibold bg-white border-bottom py-3">
                    <i class="bi bi-shield-check-fill me-2 text-dark"></i>Laporan Validasi Sistem
                </div>
                <div class="card-body p-4">
                    
                    <!-- 1. DUPLIKASI -->
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="fw-bold small text-uppercase letter-spacing-sm">1. Duplikasi Ruang</span>
                            <?php if (empty($validation['duplicates'])): ?>
                                <span class="badge bg-success-subtle text-success"><i class="bi bi-check-circle me-1"></i>Aman</span>
                            <?php else: ?>
                                <span class="badge bg-danger-subtle text-danger"><i class="bi bi-exclamation-triangle me-1"></i>Bentrok (<?= count($validation['duplicates']) ?>)</span>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($validation['duplicates'])): ?>
                            <div class="border rounded p-2 bg-danger bg-opacity-10 text-danger small max-height-200 overflow-y-auto">
                                <ul class="mb-0 ps-3">
                                    <?php foreach ($validation['duplicates'] as $dup): ?>
                                        <li>
                                            <strong><?= esc($dup['student']['full_name']) ?></strong> (<?= esc($dup['student']['classroom_name']) ?>)
                                            <div class="text-muted small">Terdaftar ganda di: <?= implode(', ', $dup['rooms']) ?></div>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php else: ?>
                            <small class="text-muted">Tidak ada siswa yang terdaftar di lebih dari satu ruangan.</small>
                        <?php endif; ?>
                    </div>

                    <!-- 2. OVERLOAD RUANG -->
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="fw-bold small text-uppercase letter-spacing-sm">2. Kapasitas Ruang</span>
                            <?php if (empty($validation['overloaded'])): ?>
                                <span class="badge bg-success-subtle text-success"><i class="bi bi-check-circle me-1"></i>Aman</span>
                            <?php else: ?>
                                <span class="badge bg-danger-subtle text-danger"><i class="bi bi-exclamation-triangle me-1"></i>Overload (<?= count($validation['overloaded']) ?>)</span>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($validation['overloaded'])): ?>
                            <div class="border rounded p-2 bg-danger bg-opacity-10 text-danger small">
                                <ul class="mb-0 ps-3">
                                    <?php foreach ($validation['overloaded'] as $over): ?>
                                        <li>
                                            <strong><?= esc($over['name']) ?></strong> 
                                            melebihi kapasitas: terisi <?= esc($over['allocated_count']) ?> dari <?= esc($over['capacity']) ?> kursi.
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php else: ?>
                            <small class="text-muted">Tidak ada ruang yang terisi melebihi kapasitas.</small>
                        <?php endif; ?>
                    </div>

                    <!-- 3. SISWA TERLEWAT (MISSING) -->
                    <div>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="fw-bold small text-uppercase letter-spacing-sm">3. Siswa Terlewat</span>
                            <?php if (empty($validation['missing'])): ?>
                                <span class="badge bg-success-subtle text-success"><i class="bi bi-check-circle me-1"></i>Lengkap</span>
                            <?php else: ?>
                                <span class="badge bg-warning-subtle text-warning"><i class="bi bi-info-circle me-1"></i>Kurang (<?= count($validation['missing']) ?>)</span>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($validation['missing'])): ?>
                            <div class="border rounded p-2 bg-warning bg-opacity-10 text-warning-emphasis small" style="max-height: 250px; overflow-y: auto;">
                                <ul class="mb-0 ps-3">
                                    <?php foreach ($validation['missing'] as $miss): ?>
                                        <li>
                                            <strong><?= esc($miss['full_name']) ?></strong> 
                                            (Kelas <?= esc($miss['classroom_name']) ?>)
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php else: ?>
                            <small class="text-muted">Semua siswa aktif pada tingkat yang dipilih telah mendapatkan ruang ujian.</small>
                        <?php endif; ?>
                    </div>

                </div>
            </div>

        </div>

    </div>

</div>

<script>
// Pass php variables to JS
const initialClasses = <?= json_encode($levelsData ?? []) ?>;
const eventId = <?= json_encode($event['id']) ?>;
const activeLevels = <?= json_encode($activeLevels ?? []) ?>;
window.csrfHashVal = '<?= csrf_hash() ?>';

// Update all CSRF token fields on the page to prevent expiration
function updateCsrfTokens(newHash) {
    window.csrfHashVal = newHash;
    const csrfInputs = document.querySelectorAll('input[name="<?= csrf_token() ?>"]');
    csrfInputs.forEach(input => {
        input.value = newHash;
    });
}

// Draggable operations
function makeDraggable(el) {
    el.addEventListener('dragstart', function(e) {
        e.dataTransfer.setData('text/plain', el.id);
        el.classList.add('dragging');
    });
    
    el.addEventListener('dragend', function() {
        el.classList.remove('dragging');
        saveOrder(el.parentElement);
        updatePairingMetrics();
    });
}

function initColumn(col) {
    col.addEventListener('dragover', function(e) {
        e.preventDefault();
        const dragging = col.querySelector('.dragging');
        if (!dragging) return;
        const afterElement = getDragAfterElement(col, e.clientY);
        if (afterElement == null) {
            col.appendChild(dragging);
        } else {
            col.insertBefore(dragging, afterElement);
        }
    });
}

function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.draggable-class:not(.dragging)')];
    return draggableElements.reduce((closest, child) => {
        const box = child.getBoundingClientRect();
        const offset = y - box.top - box.height / 2;
        if (offset < 0 && offset > closest.offset) {
            return { offset: offset, element: child };
        } else {
            return closest;
        }
    }, { offset: Number.NEGATIVE_INFINITY }).element;
}

function saveOrder(column) {
    if (!column) return;
    const level = column.getAttribute('data-level');
    const cards = [...column.querySelectorAll('.draggable-class')];
    const order = cards.map(c => c.getAttribute('data-id'));
    localStorage.setItem(`exam_event_${eventId}_order_${level}`, JSON.stringify(order));
    
    // Auto-save the whole pairing plan to the database
    savePairingPlanToDatabase();
}

function savePairingPlanToDatabase() {
    const plan = {};
    activeLevels.forEach(lvl => {
        const col = document.getElementById(`planner-col-${lvl}`);
        if (col) {
            const cards = [...col.querySelectorAll('.draggable-class')];
            plan[lvl] = cards.map(c => c.getAttribute('data-id'));
        }
    });

    const statusEl = document.getElementById('save-status-indicator');
    if (statusEl) {
        statusEl.innerHTML = '<span class="spinner-border spinner-border-sm me-1 text-primary" role="status"></span> Menyimpan...';
        statusEl.style.opacity = '1';
    }

    const formData = new FormData();
    formData.append('pairing_plan', JSON.stringify(plan));
    
    // Add CSRF token
    const csrfName = '<?= csrf_token() ?>';
    const currentHash = window.csrfHashVal || '<?= csrf_hash() ?>';
    formData.append(csrfName, currentHash);

    fetch(`/exam-event/${eventId}/allocation/save-pairing-plan`, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (statusEl) {
            if (data.success) {
                statusEl.innerHTML = '<span class="text-success"><i class="bi bi-check-circle-fill me-1"></i>Tersimpan ke database</span>';
                if (data.csrf_hash) {
                    updateCsrfTokens(data.csrf_hash);
                }
                setTimeout(() => {
                    if (statusEl.innerHTML.includes('Tersimpan ke database')) {
                        statusEl.style.opacity = '0';
                    }
                }, 2000);
            } else {
                statusEl.innerHTML = `<span class="text-danger"><i class="bi bi-exclamation-triangle-fill me-1"></i>Gagal: ${data.message}</span>`;
            }
        }
    })
    .catch(err => {
        console.error(err);
        if (statusEl) {
            statusEl.innerHTML = '<span class="text-danger"><i class="bi bi-exclamation-triangle-fill me-1"></i>Gagal koneksi server</span>';
        }
    });
}

function fillFormFromCard(classId, start, end) {
    if (!start || !end) {
        alert("Kelas ini sudah selesai dialokasikan seluruhnya!");
        return;
    }

    const classSelect = document.querySelector('select[name="classroom_id"]');
    const startInput = document.querySelector('input[name="start_absen"]');
    const endInput = document.querySelector('input[name="end_absen"]');
    
    if (classSelect) {
        classSelect.value = classId;
        classSelect.dispatchEvent(new Event('change'));
    }
    if (startInput) startInput.value = start;
    if (endInput) endInput.value = end;
    
    // Scroll to the rule form smoothly
    const ruleFormCard = document.querySelector('form[action*="save-rule"]');
    if (ruleFormCard) {
        ruleFormCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
        
        // Add a temporary highlight effect
        const fields = [classSelect, startInput, endInput];
        fields.forEach(el => {
            if (el) {
                el.style.transition = 'all 0.3s ease';
                el.style.backgroundColor = '#e8f0fe';
                el.style.borderColor = '#3b82f6';
            }
        });
        setTimeout(() => {
            fields.forEach(el => {
                if (el) {
                    el.style.backgroundColor = '';
                    el.style.borderColor = '';
                }
            });
        }, 1500);
    }
}

function updatePairingMetrics() {
    const tableBody = document.querySelector('#pairing-metrics-table tbody');
    if (!tableBody) return;
    
    tableBody.innerHTML = '';
    
    const columns = activeLevels.map(lvl => document.getElementById(`planner-col-${lvl}`));
    if (columns.some(col => !col)) return;
    
    const maxRows = Math.max(...columns.map(col => col.querySelectorAll('.draggable-class').length));
    
    if (maxRows === 0) {
        tableBody.innerHTML = `<tr><td colspan="4" class="text-center text-muted py-3">Tidak ada data kelas untuk ditampilkan</td></tr>`;
        return;
    }
    
    for (let i = 0; i < maxRows; i++) {
        const rowClasses = [];
        const counts = [];
        
        activeLevels.forEach(lvl => {
            const col = document.getElementById(`planner-col-${lvl}`);
            const cards = col.querySelectorAll('.draggable-class');
            const card = cards[i];
            
            if (card) {
                const name = card.querySelector('.class-name-label').textContent.replace('Kelas', '').trim();
                const count = parseInt(card.getAttribute('data-count'));
                const sisa = parseInt(card.getAttribute('data-sisa'));
                const nextStart = card.getAttribute('data-next-start');
                const nextEnd = card.getAttribute('data-next-end');
                const isFull = (sisa === 0);
                
                rowClasses.push({ 
                    id: card.getAttribute('data-id'), 
                    name: name, 
                    count: count,
                    sisa: sisa,
                    nextStart: nextStart,
                    nextEnd: nextEnd,
                    isFull: isFull
                });
                counts.push(count);
            }
        });
        
        let diffStr = '-';
        let quality = 'N/A';
        let badgeClass = 'bg-secondary';
        
        if (counts.length >= 2) {
            const max = Math.max(...counts);
            const min = Math.min(...counts);
            const diff = max - min;
            diffStr = `${diff} siswa`;
            
            if (diff <= 1) {
                quality = 'Sangat Serasi';
                badgeClass = 'bg-success';
            } else if (diff <= 3) {
                quality = 'Serasi';
                badgeClass = 'bg-info';
            } else if (diff <= 5) {
                quality = 'Cukup Serasi';
                badgeClass = 'bg-warning';
            } else {
                quality = 'Kurang Serasi';
                badgeClass = 'bg-danger';
            }
        }
        
        const rowHtml = `
            <tr style="font-size: 0.82rem;">
                <td class="text-center fw-bold text-muted">${i + 1}</td>
                <td>
                    <div class="d-flex align-items-center gap-2 flex-wrap">
                        ${rowClasses.map((rc, idx) => {
                            let bgClass = "bg-white text-dark";
                            let sisaText = `sisa: ${rc.sisa}`;
                            if (rc.isFull) {
                                bgClass = "bg-success bg-opacity-10 text-success border-success-subtle";
                                sisaText = "selesai";
                            }
                            return `
                                <span class="border rounded px-2 py-1 cursor-pointer hover-shadow ${bgClass}" 
                                      onclick="fillFormFromCard(${rc.id}, ${rc.nextStart ? rc.nextStart : 'null'}, ${rc.nextEnd ? rc.nextEnd : 'null'})" 
                                      title="Klik untuk isi form">
                                    <strong>${rc.name}</strong> (${rc.count} siswa | <span style="font-size:0.75rem;">${sisaText}</span>)
                                </span>
                                ${idx < rowClasses.length - 1 ? '<i class="bi bi-chevron-right text-muted small"></i>' : ''}
                            `;
                        }).join('')}
                    </div>
                </td>
                <td class="text-center fw-semibold">${diffStr}</td>
                <td class="text-center">
                    <span class="badge ${badgeClass} text-white font-size-xs" style="padding: 3px 8px; font-size: 0.72rem;">${quality}</span>
                </td>
            </tr>
        `;
        tableBody.insertAdjacentHTML('beforeend', rowHtml);
    }
}

function renderPlanner() {
    activeLevels.forEach(lvl => {
        const col = document.getElementById(`planner-col-${lvl}`);
        if (!col) return;
        
        col.innerHTML = '';
        
        const classes = initialClasses[lvl] || [];
        
        classes.forEach(c => {
            let cardStyle = "border-left: 4px solid #0d6efd !important; border-top: 1px solid #e2e8f0; border-bottom: 1px solid #e2e8f0; border-right: 1px solid #e2e8f0; border-radius: 6px;";
            let badgeHtml = `<span class="badge bg-secondary bg-opacity-10 text-secondary" style="font-size: 0.72rem; font-weight: 600;">Sisa: ${c.sisa}</span>`;
            let buttonHtml = `
                <button type="button" class="btn btn-link btn-xs text-success p-0 font-size-xs fw-bold fill-btn border-0 text-decoration-none" 
                        onclick="fillFormFromCard(${c.id}, ${c.next_start}, ${c.next_end}); event.stopPropagation();"
                        style="font-size: 0.72rem;">
                    <i class="bi bi-arrow-right-short fs-6"></i> Gunakan
                </button>
            `;
            let countColorClass = "text-primary";

            if (c.is_full) {
                cardStyle = "border-left: 4px solid #198754 !important; border-top: 1px solid #a3cfbb; border-bottom: 1px solid #a3cfbb; border-right: 1px solid #a3cfbb; border-radius: 6px; background-color: #f8fff9;";
                badgeHtml = `<span class="badge bg-success bg-opacity-10 text-success" style="font-size: 0.72rem; font-weight: 600;"><i class="bi bi-check-circle-fill me-1"></i>Selesai</span>`;
                buttonHtml = `<span class="text-success small fw-bold" style="font-size: 0.72rem;"><i class="bi bi-check-lg"></i> Dialokasikan</span>`;
                countColorClass = "text-success";
            }

            const cardHtml = `
                <div class="card p-2 draggable-class shadow-sm cursor-grab border-0 bg-white" 
                     draggable="true" 
                     id="class-card-${c.id}" 
                     data-id="${c.id}" 
                     data-count="${c.count}"
                     data-sisa="${c.sisa}"
                     data-next-start="${c.next_start || ''}"
                     data-next-end="${c.next_end || ''}"
                     style="${cardStyle}">
                    <div class="d-flex align-items-center justify-content-between">
                        <!-- Left: Class Name -->
                        <div class="fw-semibold text-start text-dark class-name-label" style="font-size: 0.85rem; width: 33%;">
                            <i class="bi bi-grip-vertical text-muted me-1"></i> Kelas ${c.name}
                        </div>
                        
                        <!-- Middle: Big Student Count -->
                        <div class="text-center" style="width: 34%;">
                            <span class="fs-4 fw-bold ${countColorClass}">${c.count}</span>
                            <small class="text-muted d-block" style="font-size: 0.65rem; margin-top: -4px;">Siswa</small>
                        </div>
                        
                        <!-- Right: Sisa Badge & Action Button -->
                        <div class="text-end d-flex flex-column align-items-end justify-content-center" style="width: 33%;">
                            <div class="mb-1">${badgeHtml}</div>
                            <div style="height: 18px; display: flex; align-items: center;">${buttonHtml}</div>
                        </div>
                    </div>
                </div>
            `;
            col.insertAdjacentHTML('beforeend', cardHtml);
        });
        
        col.querySelectorAll('.draggable-class').forEach(makeDraggable);
        initColumn(col);
    });
    
    updatePairingMetrics();
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    if (activeLevels.length > 0) {
        renderPlanner();
    }
});

// Setup click handlers for recommendation buttons in sidebar
document.querySelectorAll('.btn-suggestion-fill').forEach(button => {
    button.addEventListener('click', function() {
        const classId = this.getAttribute('data-class-id');
        const start = this.getAttribute('data-next-start');
        const end = this.getAttribute('data-next-end');
        fillFormFromCard(classId, start, end);
    });
});
</script>

<?= $this->endSection() ?>
