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

<div class="card shadow-sm border-0 rounded-3">
    <div class="card-header bg-white py-3 border-0">
        <div class="d-flex align-items-center justify-content-between">
            <div>
                <h5 class="card-title fw-bold mb-0">Daftar Siswa Kelulusan</h5>
                <p class="text-muted small mb-0">Tetapkan status kelulusan siswa (LULUS / TIDAK LULUS).</p>
            </div>
            <div class="d-flex gap-2">
                <button class="btn btn-outline-success btn-sm" onclick="bulkUpdate('LULUS')">
                    <i class="bi bi-check-circle me-1"></i>Tetapkan LULUS
                </button>
                <button class="btn btn-outline-danger btn-sm" onclick="bulkUpdate('TIDAK_LULUS')">
                    <i class="bi bi-x-circle me-1"></i>Tetapkan TIDAK LULUS
                </button>
            </div>
        </div>
    </div>
    <div class="card-body p-4 pt-0">
        <table class="table table-hover align-middle" id="studentTable">
            <thead class="table-light">
                <tr>
                    <th style="width:50px"><input type="checkbox" id="checkAll"></th>
                    <th>NISN</th>
                    <th>Nama Siswa</th>
                    <th>Kelas</th>
                    <th>Status Kelulusan</th>
                    <th class="text-center">Aksi</th>
                </tr>
            </thead>
            <tbody id="studentBody">
                <!-- Data siswa dimuat via AJAX -->
            </tbody>
        </table>
    </div>
</div>

<script>
    function loadStudents() {
        const tbody = document.getElementById('studentBody');
        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/students/ajax')
            .then(r => r.json())
            .then(data => {
                tbody.innerHTML = '';

                if (!data.success) {
                    tbody.innerHTML = `<tr><td colspan="6" class="text-center text-danger py-3"><i class="bi bi-exclamation-triangle me-2"></i>${data.message || 'Gagal memuat data siswa.'}</td></tr>`;
                    return;
                }

                const students = data.students || [];
                if (students.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted py-3">Tidak ada siswa kelas akhir yang ditemukan.</td></tr>';
                    return;
                }

                students.forEach(s => {
                    const statusBadge = s.graduation_status === 'LULUS' ? 'bg-success' : (s.graduation_status === 'TIDAK_LULUS' ? 'bg-danger' : 'bg-warning text-dark');
                    const statusLabel = s.graduation_status === 'BELUM_DITENTUKAN' ? 'BELUM DITENTUKAN' : s.graduation_status;
                    tbody.innerHTML += `
                        <tr>
                            <td><input type="checkbox" class="checkStudent" value="${s.student_id}"></td>
                            <td>${s.nisn ?? '-'}</td>
                            <td>${s.full_name}</td>
                            <td>${s.classroom_name}</td>
                            <td><span class="badge ${statusBadge}">${statusLabel}</span></td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-outline-primary" onclick="updateStatus(${s.student_id}, 'LULUS')">LULUS</button>
                                <button class="btn btn-sm btn-outline-danger" onclick="updateStatus(${s.student_id}, 'TIDAK_LULUS')">TIDAK LULUS</button>
                            </td>
                        </tr>
                    `;
                });
            })
            .catch(err => {
                tbody.innerHTML = `<tr><td colspan="6" class="text-center text-danger py-3"><i class="bi bi-exclamation-triangle me-2"></i>Terjadi kesalahan: ${err.message}</td></tr>`;
                console.error('loadStudents error:', err);
            });
    }

    function updateStatus(studentId, status) {
        fetch(`/admin/graduation/students/${studentId}/status`, {
            method: 'POST',
            body: new URLSearchParams({ status: status, '<?= csrf_token() ?>': '<?= csrf_hash() ?>' })
        })
        .then(r => r.json())
        .then(data => {
            Swal.fire(data.success ? 'Berhasil' : 'Gagal', data.message, data.success ? 'success' : 'error');
            loadStudents();
        });
    }

    function bulkUpdate(status) {
        const selected = Array.from(document.querySelectorAll('.checkStudent:checked')).map(cb => cb.value);
        if (selected.length === 0) return Swal.fire('Oops', 'Pilih minimal satu siswa.', 'warning');

        Swal.fire({
            title: `Tetapkan ${status.replace('_', ' ')}?`,
            html: `<strong>${selected.length} siswa</strong> akan ditetapkan sebagai <strong>${status.replace('_', ' ')}</strong>.`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Ya, Tetapkan',
            cancelButtonText: 'Batal',
            confirmButtonColor: status === 'LULUS' ? '#198754' : '#dc3545',
        }).then(result => {
            if (!result.isConfirmed) return;

            // Kirim array dengan append() — URLSearchParams object notation
            // menggabungkan array jadi string sehingga PHP hanya terima 1 elemen
            const params = new URLSearchParams();
            params.append('status', status);
            params.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');
            selected.forEach(id => params.append('student_ids[]', id));

            fetch('/admin/graduation/students/bulk-status', {
                method: 'POST',
                body: params
            })
            .then(r => r.json())
            .then(data => {
                Swal.fire(data.success ? 'Berhasil' : 'Gagal', data.message, data.success ? 'success' : 'error');
                loadStudents();
            })
            .catch(() => Swal.fire('Error', 'Gagal terhubung ke server.', 'error'));
        });
    }

    document.getElementById('checkAll').addEventListener('change', (e) => {
        document.querySelectorAll('.checkStudent').forEach(cb => cb.checked = e.target.checked);
    });

    loadStudents();
</script>

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