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

<?php
$sum        = $summary ?? [];
$activeYear = $sum['academic_year'] ?? null;
$yearId     = $activeYear['id'] ?? 0;
?>

<!-- Ringkasan SKL -->
<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="fs-2 fw-bold text-success"><?= $sum['total_lulus'] ?? 0 ?></div>
            <div class="text-muted small">Siswa LULUS</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="fs-2 fw-bold text-danger"><?= $sum['total_tidak_lulus'] ?? 0 ?></div>
            <div class="text-muted small">Siswa TIDAK LULUS</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="fs-2 fw-bold text-primary"><?= $sum['with_skl'] ?? 0 ?></div>
            <div class="text-muted small">SKL Sudah Diupload</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm text-center py-3">
            <div class="fs-2 fw-bold text-warning"><?= $sum['without_skl'] ?? 0 ?></div>
            <div class="text-muted small">LULUS Belum Ada SKL</div>
        </div>
    </div>
</div>

<!-- ── CARD: Upload + Hapus dalam 1 baris ───────────────────── -->
<div class="row g-3 mb-4">
    <div class="col-md-7">
        <div class="card shadow-sm border-0 rounded-3 h-100">
            <div class="card-header bg-white py-3 border-0">
                <h5 class="card-title fw-bold mb-0"><i class="bi bi-file-earmark-zip me-2 text-primary"></i>Upload SKL Massal</h5>
                <p class="text-muted small mb-0 mt-1">
                    Nama file PDF di dalam ZIP harus sesuai NISN siswa. Contoh: <code>1234567890.pdf</code><br>
                    Maksimal ukuran file ZIP: <strong>40MB</strong> &mdash; jika melebihi batas akan ditolak otomatis.
                </p>
            </div>
            <div class="card-body p-4">
                <form id="uploadForm" enctype="multipart/form-data">
                    <?= csrf_field() ?>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Pilih File ZIP</label>
                        <input type="file" name="skl_zip_file" class="form-control" accept=".zip" required>
                    </div>
                    <button type="submit" class="btn btn-primary" id="btnUpload">
                        <i class="bi bi-upload me-2"></i>Upload &amp; Proses
                    </button>
                </form>
                <div id="uploadReport" class="mt-3"></div>
            </div>
        </div>
    </div>
    <div class="col-md-5">
        <div class="card shadow-sm border-0 rounded-3 h-100 border-danger">
            <div class="card-body p-4 d-flex flex-column h-100">
                <div class="d-flex align-items-center gap-2 mb-3">
                    <i class="bi bi-trash3 fs-4 text-danger"></i>
                    <div>
                        <h6 class="fw-bold text-danger mb-0">Hapus SKL</h6>
                        <div class="text-muted small">Pilih tahun, lalu hapus file SKL.</div>
                    </div>
                </div>
                <div class="d-flex align-items-center gap-2 mb-2">
                    <select id="deleteYearSelect" class="form-select form-select-sm border-0 bg-light shadow-none" style="width:auto;min-width:160px;">
                        <?php foreach ($sklYears as $y): ?>
                        <option value="<?= $y['id'] ?>" <?= $y['id'] == $yearId ? 'selected' : '' ?>>
                            <?= esc($y['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <span class="text-muted small">SKL: <strong id="deleteCountText"><?= $sum['with_skl'] ?? 0 ?></strong></span>
                    <button class="btn btn-outline-danger btn-sm" id="btnDeleteMassal">
                        <i class="bi bi-trash3 me-1"></i>Hapus
                    </button>
                </div>
                <div class="small text-muted mt-auto">
                    <i class="bi bi-info-circle me-1"></i>Hanya file SKL yang dihapus. Status kelulusan siswa <strong>tidak berubah</strong>.
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ── TABEL DAFTAR SISWA (tahun aktif) ──────────────────────── -->
<div class="card shadow-sm border-0 rounded-3 mb-4">
    <div class="card-header bg-white py-3 border-0 d-flex align-items-center justify-content-between">
        <div>
            <h5 class="card-title fw-bold mb-0"><i class="bi bi-table me-2 text-primary"></i>Detail SKL per Siswa</h5>
            <p class="text-muted small mb-0">Daftar siswa kelas akhir tahun <?= esc($activeYear['name'] ?? 'aktif') ?> dan status upload SKL.</p>
        </div>
        <div class="d-flex gap-2">
            <input type="text" id="sklSearchInput" class="form-control form-control-sm"
                   placeholder="Cari NISN atau Nama..." style="width:200px;">
            <select id="sklFilterStatus" class="form-select form-select-sm" style="width:150px;">
                <option value="all">Semua Status</option>
                <option value="uploaded">Sudah Upload SKL</option>
                <option value="pending">Belum Upload SKL</option>
                <option value="lulus">LULUS</option>
                <option value="tidak_lulus">TIDAK LULUS</option>
                <option value="belum_ditentukan">BELUM DITENTUKAN</option>
            </select>
        </div>
    </div>
    <div class="card-body p-4 pt-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle" id="sklStudentTable">
                <thead class="table-light">
                    <tr>
                        <th>NISN</th>
                        <th>Nama Siswa</th>
                        <th>Kelas</th>
                        <th>Status Kelulusan</th>
                        <th>Status SKL</th>
                        <th class="text-center">SKL Diupload</th>
                    </tr>
                </thead>
                <tbody id="sklStudentBody">
                    <tr><td colspan="6" class="text-center text-muted py-3">
                        <span class="spinner-border spinner-border-sm me-2"></span>Memuat data...
                    </td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    // ── LOAD TABEL SISWA ──────────────────────────────────────────
    let sklStudents = [];

    function loadSklStudentTable() {
        const tbody = document.getElementById('sklStudentBody');
        tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted py-3"><span class="spinner-border spinner-border-sm me-2"></span>Memuat data...</td></tr>';

        fetch('/admin/graduation/skl/student-list')
            .then(r => r.json())
            .then(data => {
                if (!data.success || !data.students) {
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-danger py-3">' + (data.message || 'Gagal memuat data.') + '</td></tr>';
                    return;
                }
                sklStudents = data.students;
                renderSklTable();
            })
            .catch(() => {
                tbody.innerHTML = '<tr><td colspan="6" class="text-center text-danger py-3">Terjadi kesalahan koneksi.</td></tr>';
            });
    }

    function renderSklTable() {
        const tbody = document.getElementById('sklStudentBody');
        const searchVal = document.getElementById('sklSearchInput').value.toLowerCase().trim();
        const filterVal = document.getElementById('sklFilterStatus').value;

        let filtered = sklStudents.filter(s => {
            if (searchVal) {
                const nisnMatch = (s.nisn || '').toLowerCase().includes(searchVal);
                const nameMatch = (s.full_name || '').toLowerCase().includes(searchVal);
                if (!nisnMatch && !nameMatch) return false;
            }
            if (filterVal === 'uploaded') return s.skl_file_path;
            if (filterVal === 'pending')  return !s.skl_file_path;
            if (filterVal === 'lulus')    return s.graduation_status === 'LULUS';
            if (filterVal === 'tidak_lulus') return s.graduation_status === 'TIDAK_LULUS';
            if (filterVal === 'belum_ditentukan') return s.graduation_status === 'BELUM_DITENTUKAN';
            return true;
        });

        if (filtered.length === 0) {
            tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted py-3">Tidak ada data yang cocok.</td></tr>';
            return;
        }

        tbody.innerHTML = filtered.map(s => {
            const statusLabel = s.graduation_status === 'LULUS' ? 'LULUS' :
                               (s.graduation_status === 'TIDAK_LULUS' ? 'TIDAK LULUS' : 'BELUM DITENTUKAN');
            const statusClass = s.graduation_status === 'LULUS' ? 'bg-success' :
                               (s.graduation_status === 'TIDAK_LULUS' ? 'bg-danger' : 'bg-warning text-dark');
            const sklIcon = s.skl_file_path
                ? '<span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>Tersedia</span>'
                : '<span class="badge bg-secondary"><i class="bi bi-x-circle me-1"></i>Belum</span>';
            const sklDate = s.skl_uploaded_at
                ? formatDate(s.skl_uploaded_at)
                : '<span class="text-muted">—</span>';
            return `<tr>
                <td><code>${s.nisn || '-'}</code></td>
                <td>${s.full_name}</td>
                <td>${s.classroom_name || '-'}</td>
                <td><span class="badge ${statusClass}">${statusLabel}</span></td>
                <td>${sklIcon}</td>
                <td class="text-center" style="font-size:0.85rem;">${sklDate}</td>
            </tr>`;
        }).join('');
    }

    function formatDate(dt) {
        if (!dt) return '<span class="text-muted">—</span>';
        const parts = dt.split(' ');
        if (parts.length < 1) return dt;
        const dateParts = parts[0].split('-');
        if (dateParts.length < 3) return parts[0];
        const months = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
        const mIdx = parseInt(dateParts[1]) - 1;
        return parseInt(dateParts[2]) + ' ' + (months[mIdx] || dateParts[1]) + ' ' + dateParts[0];
    }

    document.getElementById('sklSearchInput').addEventListener('input', renderSklTable);
    document.getElementById('sklFilterStatus').addEventListener('change', renderSklTable);
    document.addEventListener('DOMContentLoaded', loadSklStudentTable);

    // ── UPDATE COUNT SKL SAAT GANTI TAHUN DI DROPDOWN ────────────
    document.getElementById('deleteYearSelect').addEventListener('change', function() {
        const yearId = this.value;
        fetch('/admin/graduation/skl/count/' + yearId)
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('deleteCountText').textContent = data.count;
                }
            })
            .catch(() => {});
    });

    // ── UPLOAD ─────────────────────────────────────────────────────
    document.getElementById('uploadForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const btn    = document.getElementById('btnUpload');
        const report = document.getElementById('uploadReport');

        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Memproses...';
        report.innerHTML = '';

        const fileInput = document.querySelector('input[name="skl_zip_file"]');
        if (fileInput && fileInput.files && fileInput.files[0]) {
            const maxBytes = 40 * 1024 * 1024;
            if (fileInput.files[0].size > maxBytes) {
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-upload me-2"></i>Upload &amp; Proses';
                report.innerHTML = `<div class="alert alert-danger mb-2">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    File terlalu besar! Maksimal <strong>40MB</strong>, file yang dipilih sebesar
                    <strong>${(fileInput.files[0].size / (1024 * 1024)).toFixed(1)}MB</strong>.
                </div>`;
                return;
            }
        }

        fetch('/admin/graduation/skl/upload-process', {
            method: 'POST',
            body: new FormData(this)
        })
        .then(r => r.json())
        .then(data => {
            let html = `<div class="alert ${data.success ? 'alert-success' : 'alert-warning'} mb-2">
                <strong>${data.message}</strong><br>
                Berhasil: <strong>${data.success_count}</strong> &nbsp;|&nbsp;
                Gagal: <strong>${data.failed_count}</strong>
            </div>`;

            if (data.failed_items && data.failed_items.length > 0) {
                html += `<div class="table-responsive">
                    <table class="table table-sm table-bordered mb-0">
                        <thead class="table-light"><tr><th>NISN</th><th>Keterangan</th></tr></thead>
                        <tbody>`;
                data.failed_items.forEach(item => {
                    html += `<tr><td><code>${item.nisn}</code></td><td class="text-danger">${item.reason}</td></tr>`;
                });
                html += `</tbody></table></div>`;
            }

            report.innerHTML = html;
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-upload me-2"></i>Upload &amp; Proses';

            if (data.success_count > 0) {
                setTimeout(() => location.reload(), 2000);
            }
        })
        .catch(() => {
            report.innerHTML = `<div class="alert alert-danger">Terjadi kesalahan koneksi.</div>`;
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-upload me-2"></i>Upload &amp; Proses';
        });
    });

    // ── HAPUS MASSAL ───────────────────────────────────────────────
    const btnDel = document.getElementById('btnDeleteMassal');
    if (btnDel) {
        btnDel.addEventListener('click', function() {
            const yearId = document.getElementById('deleteYearSelect').value;
            const yearName = document.getElementById('deleteYearSelect').selectedOptions[0].text;
            const count = document.getElementById('deleteCountText').textContent;

            Swal.fire({
                title: 'Hapus SKL ' + yearName + '?',
                html: 'Akan menghapus <strong>' + count + ' file SKL</strong> dari server.<br>'
                    + 'Status LULUS/TIDAK LULUS siswa <strong>tidak berubah</strong>.<br><br>'
                    + '<span class="text-danger"><i class="bi bi-exclamation-triangle me-1"></i>Tindakan ini tidak bisa dibatalkan.</span>',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonText: 'Batal',
                confirmButtonText: 'Ya, Hapus'
            }).then(result => {
                if (!result.isConfirmed) return;

                btnDel.disabled = true;
                btnDel.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Menghapus...';

                fetch('/admin/graduation/skl/' + yearId, {
                    method: 'DELETE',
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                })
                .then(r => r.json())
                .then(data => {
                    Swal.fire(
                        data.success ? 'Berhasil' : 'Gagal',
                        data.message,
                        data.success ? 'success' : 'error'
                    ).then(() => {
                        if (data.success) location.reload();
                    });
                    btnDel.disabled = false;
                    btnDel.innerHTML = '<i class="bi bi-trash3 me-1"></i>Hapus SKL';
                })
                .catch(() => {
                    Swal.fire('Error', 'Terjadi kesalahan koneksi.', 'error');
                    btnDel.disabled = false;
                    btnDel.innerHTML = '<i class="bi bi-trash3 me-1"></i>Hapus SKL';
                });
            });
        });
    }
</script>

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