<?= $this->extend('layout/admin') ?>
<?= $this->section('content') ?>

<style>
    /* ================== PREMIUM PPDB STYLE ================== */
    .page-wrapper {
        background: #f3f6ff;
        padding: 24px;
        border-radius: 22px;
    }

    .card-premium {
        border-radius: 22px;
        border: none;
        overflow: hidden;
    }

    .header-box {
        background: linear-gradient(135deg, #1e3cff, #5278ff);
        color: #fff;
        padding: 28px;
    }

    .header-box h4 {
        font-weight: 900;
        margin-bottom: 4px;
    }

    .badge-status {
        padding: 8px 16px;
        border-radius: 30px;
        font-size: 13px;
    }

    .info-box {
        background: #fff;
        border: 1px solid #dde4ff;
        border-radius: 18px;
        padding: 20px 22px;
        margin-top: 20px;
    }

    .section-header {
        font-weight: 900;
        color: #1020a0;
        margin-bottom: 12px;
    }

    .label {
        font-size: 12px;
        color: #6b77e5;
    }

    .value {
        font-size: 16px;
        font-weight: 700;
        color: #0c1970;
    }

    .doc-card {
        border: 1px dashed #cbd4ff;
        background: #fafbff;
        border-radius: 14px;
        padding: 14px;
    }

    .doc-title {
        font-weight: 800;
        font-size: 14px;
    }

    .doc-empty {
        font-size: 13px;
        color: #999;
    }

    /* ================== TIMELINE ================== */
    .timeline-wrap {
        position: relative;
        padding-left: 30px;
    }

    .timeline-wrap::before {
        content: '';
        position: absolute;
        top: 0;
        left: 12px;
        width: 4px;
        height: 100%;
        background: #d9e0ff;
        border-radius: 8px;
    }

    .timeline-item {
        position: relative;
        margin-bottom: 20px;
    }

    .timeline-dot {
        position: absolute;
        left: 4px;
        top: 4px;
        width: 16px;
        height: 16px;
        background: #ffb400;
        border-radius: 50%;
        border: 3px solid #fff;
    }

    .completed .timeline-dot {
        background: #28c76f;
    }

    .rejected .timeline-dot {
        background: #ff4d4f;
    }

    .timeline-box {
        background: #fff;
        border-radius: 12px;
        padding: 14px 18px;
        border: 1px solid #dde4ff;
    }

    .timeline-title {
        font-weight: 900;
        color: #1020a0;
    }

    .timeline-time {
        font-size: 12px;
        color: #6b77e5;
    }

    .timeline-desc {
        font-size: 13px;
        color: #555;
    }
</style>

<?php
$status = strtoupper($record['status'] ?? 'SUBMIT');
$badge = 'bg-warning text-dark';
if ($status === 'APPROVED')
    $badge = 'bg-success';
if ($status === 'REJECTED')
    $badge = 'bg-danger';

$base = base_url('uploads/ppdb/');
$rapors = json_decode($record['rapor_file'] ?? '[]', true);
?>

<div class="page-wrapper">
    <div class="card card-premium shadow-sm">

        <!-- ================= HEADER ================= -->
        <div class="header-box d-flex justify-content-between align-items-center">
            <div>
                <h4>Detail Pendaftaran PPDB</h4>
                <div>Nomor Pendaftaran: <b><?= $record['reg_no'] ?></b></div>
                <span class="badge <?= $badge ?> badge-status mt-2"><?= $status ?></span>
            </div>

            <div class="d-flex gap-2">
                <a href="<?= site_url('ppdb/verification') ?>" class="btn btn-secondary">
                    Kembali
                </a>

                <a href="<?= site_url('ppdb/print/' . $record['id']) ?>" target="_blank"
                    class="btn btn-warning fw-bold text-dark">
                    <i class="fas fa-print"></i> Cetak
                </a>

                <?php if ($status === 'SUBMIT'): ?>
                    <button class="btn btn-success fw-bold" onclick="approvePPDB(<?= $record['id'] ?>)">
                        <i class="fas fa-check"></i> Terima
                    </button>
                    <button class="btn btn-danger fw-bold" onclick="openRejectModal(<?= $record['id'] ?>)">
                        <i class="fas fa-times"></i> Tolak
                    </button>
                <?php endif ?>
            </div>
        </div>

        <!-- ================= IDENTITAS ================= -->
        <div class="info-box">
            <div class="section-header"><i class="fas fa-id-card"></i> Identitas Siswa</div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <div class="label">Nama Lengkap</div>
                    <div class="value"><?= $record['name'] ?></div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="label">NISN</div>
                    <div class="value"><?= $record['nisn'] ?></div>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="label">Jenis Kelamin</div>
                    <div class="value"><?= $record['gender'] == 'M' ? 'Laki-laki' : 'Perempuan' ?></div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="label">Tempat Lahir</div>
                    <div class="value"><?= $record['birth_place'] ?></div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="label">Tanggal Lahir</div>
                    <div class="value"><?= indo_date($record['birth_date']) ?></div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="label">Alamat</div>
                    <div class="value"><?= $record['address_street'] ?></div>
                </div>
            </div>
        </div>

        <!-- ================= ORANG TUA ================= -->
        <div class="info-box">
            <div class="section-header"><i class="fas fa-users"></i> Orang Tua</div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <div class="label">Ayah</div>
                    <div class="value"><?= $record['father_name'] ?></div>
                </div>
                <div class="col-md-6 mb-3">
                    <div class="label">Pekerjaan Ayah</div>
                    <div class="value"><?= $record['father_job'] ?></div>
                </div>
                <div class="col-md-6 mb-3">
                    <div class="label">Ibu</div>
                    <div class="value"><?= $record['mother_name'] ?></div>
                </div>
                <div class="col-md-6 mb-3">
                    <div class="label">Pekerjaan Ibu</div>
                    <div class="value"><?= $record['mother_job'] ?></div>
                </div>
            </div>
        </div>

        <!-- ================= SEKOLAH ================= -->
        <div class="info-box">
            <div class="section-header"><i class="fas fa-school"></i> Sekolah Asal</div>
            <div class="row">
                <div class="col-md-6">
                    <div class="label">Sekolah</div>
                    <div class="value"><?= $record['school_origin'] ?></div>
                </div>
                <div class="col-md-6">
                    <div class="label">Kota</div>
                    <div class="value"><?= $record['school_city'] ?></div>
                </div>
            </div>
        </div>

        <!-- ================= DOKUMEN ================= -->
        <div class="info-box">
            <div class="section-header"><i class="fas fa-file"></i> Dokumen</div>
            <div class="row">

                <div class="col-md-12 mb-3 doc-card">
                    <div class="doc-title">Rapor</div>
                    <?php if ($rapors):
                        foreach ($rapors as $i => $r): ?>
                            <a href="<?= $base . $r ?>" target="_blank" class="btn btn-outline-primary btn-sm mt-2">
                                Lihat Rapor <?= $i + 1 ?>
                            </a>
                        <?php endforeach; else: ?>
                        <div class="doc-empty">Tidak ada</div>
                    <?php endif ?>
                </div>

                <div class="col-md-4 doc-card">
                    <div class="doc-title">KK</div>
                    <?= $record['kk_file'] ? "<a class='btn btn-sm btn-outline-success mt-2' target='_blank' href='{$base}{$record['kk_file']}'>Lihat</a>" : "<div class='doc-empty'>Tidak ada</div>" ?>
                </div>

                <div class="col-md-4 doc-card">
                    <div class="doc-title">Akta</div>
                    <?= $record['akta_file'] ? "<a class='btn btn-sm btn-outline-warning mt-2' target='_blank' href='{$base}{$record['akta_file']}'>Lihat</a>" : "<div class='doc-empty'>Tidak ada</div>" ?>
                </div>

                <div class="col-md-4 doc-card">
                    <div class="doc-title">Foto</div>
                    <?= $record['photo_file'] ? "<a class='btn btn-sm btn-outline-danger mt-2' target='_blank' href='{$base}{$record['photo_file']}'>Lihat</a>" : "<div class='doc-empty'>Tidak ada</div>" ?>
                </div>

            </div>
        </div>

    </div>
</div>

<!-- ================= JS (TIDAK DIUBAH LOGIC) ================= -->
<script>
    function approvePPDB(id) {
        if (!confirm('Terima pendaftaran?')) return;
        fetch(`<?= site_url('ppdb/admin/approve') ?>/${id}`, { method: 'POST' })
            .then(r => r.json()).then(r => { alert(r.message); location.reload() });
    }

    function openRejectModal(id) {
        document.getElementById('rejectId').value = id;
        new bootstrap.Modal(document.getElementById('rejectModal')).show();
    }

    function submitReject() {
        const id = document.getElementById('rejectId').value;
        const note = document.getElementById('rejectNote').value;
        fetch(`<?= site_url('ppdb/admin/reject') ?>/${id}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ reject_note: note })
        }).then(r => r.json()).then(r => { alert(r.message); location.reload() });
    }
</script>
<!-- Time Line -->
<div class="info-box mb-4">
    <div class="section-header">
        <i class="fas fa-stream me-2"></i> Timeline Pendaftaran
    </div>

    <style>
        .timeline-wrap {
            position: relative;
            padding-left: 30px;
        }

        .timeline-wrap:before {
            content: "";
            position: absolute;
            top: 0;
            left: 10px;
            width: 4px;
            height: 100%;
            background: #d6e0ff;
            border-radius: 10px;
        }

        .timeline-item {
            position: relative;
            margin-bottom: 18px;
        }

        .timeline-dot {
            position: absolute;
            left: -2px;
            top: 4px;
            width: 16px;
            height: 16px;
            background: #4e7bff;
            border-radius: 50%;
            border: 3px solid #fff;
            box-shadow: 0 0 6px rgba(0, 0, 0, .2);
        }

        .timeline-box {
            background: #fff;
            border: 1px solid #d6e0ff;
            border-radius: 12px;
            padding: 12px 16px;
        }

        .timeline-title {
            font-weight: 900;
            color: #0f1f6d;
            font-size: 15px;
        }

        .timeline-time {
            font-size: 12px;
            color: #6376ff;
        }

        .timeline-desc {
            font-size: 13px;
            color: #555;
        }

        .completed .timeline-dot {
            background: #28c76f !important;
        }

        .rejected .timeline-dot {
            background: #ff4d4f !important;
        }

        .submit .timeline-dot {
            background: #ffb400 !important;
        }
    </style>

    <?php
    $status = strtoupper($record['status']);
    ?>

    <?php
    // === CEK KELENGKAPAN DOKUMEN ===
    $rapors = json_decode($record['rapor_file'] ?? '[]', true);

    $isRaporOk = !empty($rapors);
    $isKkOk = !empty($record['kk_file']);
    $isAktaOk = !empty($record['akta_file']);
    $isFotoOk = !empty($record['photo_file']);

    $isDokumenLengkap = $isRaporOk && $isKkOk && $isAktaOk && $isFotoOk;


    // Tentukan class timeline
    $verifikasiClass = 'submit'; // default kuning
    if ($isDokumenLengkap) {
        $verifikasiClass = 'completed'; // hijau
    }
    ?>

    <div class="timeline-wrap">

        <div class="timeline-item completed">
            <span class="timeline-dot"></span>
            <div class="timeline-box">
                <div class="timeline-title">Pendaftaran Dikirim</div>
                <div class="timeline-time">
                    <?= $record['created_at']; ?>
                </div>
                <div class="timeline-desc">Siswa telah mengisi formulir dan mengirim pendaftaran.</div>
            </div>
        </div>

        <?php
        $docClass = $isDokumenLengkap ? 'completed' : 'submit';
        $docText = $isDokumenLengkap
            ? 'Semua dokumen sudah lengkap dan siap diverifikasi.'
            : 'Dokumen belum lengkap, menunggu unggahan.';
        ?>

        <div class="timeline-item <?= $docClass ?>">
            <span class="timeline-dot"></span>
            <div class="timeline-box">
                <div class="timeline-title">Verifikasi Dokumen</div>
                <div class="timeline-time">
                    <?= $record['updated_at'] ?? '-' ?>
                </div>
                <div class="timeline-desc">
                    <?= $docText ?>
                </div>
            </div>
        </div>

    </div>

    <?php if ($status == 'APPROVED'): ?>
        <div class="timeline-item completed">
            <span class="timeline-dot"></span>
            <div class="timeline-box">
                <div class="timeline-title">Diterima</div>
                <div class="timeline-time">
                    <?= $record['updated_at']; ?>
                </div>
                <div class="timeline-desc">Selamat! Siswa dinyatakan diterima.</div>
            </div>
        </div>
    <?php elseif ($status == 'REJECTED'): ?>
        <div class="timeline-item rejected">
            <span class="timeline-dot"></span>
            <div class="timeline-box">
                <div class="timeline-title">Ditolak</div>
                <div class="timeline-time">
                    <?= $record['updated_at']; ?>
                </div>
                <div class="timeline-desc">Mohon maaf, siswa tidak lolos seleksi.</div>
            </div>
        </div>

        <?php if ($status === 'REJECTED' && !empty($record['reject_note'])): ?>
            <div class="alert alert-danger mt-3">
                <b>Alasan Penolakan:</b><br>
                <?= nl2br(esc($record['reject_note'])) ?>
            </div>
        <?php endif; ?>

    <?php else: ?>
        <div class="timeline-item submit">
            <span class="timeline-dot"></span>
            <div class="timeline-box">
                <div class="timeline-title">Menunggu Keputusan</div>
                <div class="timeline-time">-</div>
                <div class="timeline-desc">
                    Proses seleksi sedang berlangsung.
                </div>
            </div>
        </div>
    <?php endif; ?>

</div>
<div class="card-footer text-end">
    <small class="text-muted">
        Dibuat: <?= date('d/m/Y H:i', strtotime($record['created_at'])) ?>
        Update: <?= $record['updated_at'] ?? '-' ?>
    </small>
</div>

</div>
</div>

<script>
    function approvePPDB(id) {
        if (!confirm('Terima pendaftaran?')) return;
        fetch(`<?= site_url('ppdb/admin/approve') ?>/${id}`, { method: 'POST' })
            .then(r => r.json()).then(r => { alert(r.message); location.reload(); });
    }

    function rejectPPDB(id) {
        const note = prompt("Masukkan alasan penolakan:");

        if (!note || note.trim() === '') {
            alert('Alasan penolakan wajib diisi');
            return;
        }

        fetch(`<?= site_url('ppdb/admin/reject') ?>/${id}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                reject_note: note
            })
        })
            .then(r => r.json())
            .then(r => {
                alert(r.message);
                if (r.status) location.reload();
            });
    }
</script>



<script>
    setInterval(() => {
        fetch("<?= site_url('ppdb/admin/doc-status/' . $record['id']) ?>")
            .then(res => res.json())
            .then(res => {
                const item = document.querySelector('.timeline-item.submit');
                if (res.complete && item) {
                    item.classList.remove('submit');
                    item.classList.add('completed');
                    item.querySelector('.timeline-desc').innerText =
                        'Semua dokumen sudah lengkap dan siap diverifikasi.';
                }
            });
    }, 5000); // cek tiap 5 detik
</script>
<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-times-circle"></i> Tolak Pendaftaran
                </h5>
                <button class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <input type="hidden" id="rejectId">

                <label class="form-label fw-bold">Alasan Penolakan</label>
                <textarea id="rejectNote" class="form-control" rows="4"
                    placeholder="Contoh: Dokumen rapor tidak lengkap..." required></textarea>
            </div>

            <div class="modal-footer">
                <button class="btn btn-light" data-bs-dismiss="modal">Batal</button>
                <button class="btn btn-danger fw-bold" onclick="submitReject()">
                    Tolak Sekarang
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    function openRejectModal(id) {
        document.getElementById('rejectId').value = id;
        document.getElementById('rejectNote').value = '';
        new bootstrap.Modal(document.getElementById('rejectModal')).show();
    }

    function submitReject() {
        const id = document.getElementById('rejectId').value;
        const note = document.getElementById('rejectNote').value.trim();

        if (!note) {
            alert('Alasan penolakan wajib diisi');
            return;
        }

        fetch(`<?= site_url('ppdb/admin/reject') ?>/${id}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({ reject_note: note })
        })
            .then(r => r.json())
            .then(r => {
                alert(r.message);
                if (r.status) location.reload();
            });
    }
</script>

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