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

<div class="card d-flex flex-column" style="height:calc(100vh - 160px)">

    <!-- Header -->
    <div class="card-header d-flex align-items-center justify-content-between flex-wrap gap-2 flex-shrink-0">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-person-x text-primary"></i>
            <span class="fw-semibold">Data Alumni & Non-Aktif</span>
            <span class="badge bg-secondary" id="totalCount">0</span>
        </div>
    </div>

    <!-- Filter Bar -->
    <div class="px-3 pt-3 pb-2 border-bottom flex-shrink-0">
        <div class="row g-2 align-items-end">
            <!-- Filter Status -->
            <div class="col-sm-3">
                <label class="form-label small text-muted mb-1">Status Siswa</label>
                <select id="filterStatus" class="form-select form-select-sm" onchange="applyFilter(true)">
                    <option value="">-- Pilih Status --</option>
                    <option value="Alumni">Alumni</option>
                    <option value="Mutasi">Mutasi</option>
                    <option value="Drop Out">Drop Out</option>
                </select>
            </div>
            <!-- Filter Tahun (Lulus/Keluar) -->
            <div class="col-sm-3">
                <label id="labelYear" class="form-label small text-muted mb-1">Tahun</label>
                <select id="filterYear" class="form-select form-select-sm" onchange="applyFilter(false)" disabled>
                    <option value="">-- Pilih Tahun --</option>
                </select>
            </div>
            <!-- Search -->
            <div class="col-sm-3">
                <label class="form-label small text-muted mb-1">Cari</label>
                <input type="text" id="searchInput" class="form-control form-control-sm"
                    placeholder="Nama / NIS / NISN..." oninput="applyFilter(false)" disabled>
            </div>
            <div class="col-sm-3 d-flex align-items-end gap-2">
                <button class="btn btn-outline-secondary btn-sm" onclick="resetFilter()">
                    <i class="bi bi-x-circle me-1"></i>Reset
                </button>
                <span class="text-muted small ms-auto" id="infoCount"></span>
            </div>
        </div>
    </div>

    <!-- Tabel (scrollable) -->
    <div class="flex-grow-1 overflow-auto" style="min-height:0">
        <table class="table table-hover table-sm mb-0">
            <thead class="table-light sticky-top">
                <tr>
                    <th style="width:40px" class="text-center">#</th>
                    <th>NIS</th>
                    <th>Nama Lengkap</th>
                    <th style="width:50px">L/P</th>
                    <th style="width:90px">Status</th>
                    <th>Info Keluar</th>
                    <th style="width:90px">Aksi</th>
                </tr>
            </thead>
            <tbody id="studentBody">
                <tr>
                    <td colspan="7" class="text-center text-muted py-5">
                        <i class="bi bi-funnel fs-2 d-block mb-2 opacity-25"></i>
                        <small>Pilih status untuk menampilkan data alumni & non-aktif</small>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

</div>

<!-- Modal Konfirmasi Aktifkan Kembali -->
<div class="modal fade" id="reactivateModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title fw-semibold">
                    <i class="bi bi-arrow-repeat me-2 text-success"></i>Aktifkan Kembali
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="mb-1 small">Aktifkan kembali siswa:</p>
                <p class="fw-semibold mb-3" id="reactivateName"></p>
                <div class="alert alert-info py-2 small mb-0">
                    <i class="bi bi-info-circle me-1"></i>
                    Status siswa akan diubah menjadi <strong>Aktif</strong>. Jika tidak memiliki kelas di periode aktif, silakan assign kembali lewat menu <strong>Assign Kelas</strong>.
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-success btn-sm" id="btnReactivateConfirm">
                    <span id="reactivateLabel"><i class="bi bi-check-circle me-1"></i>Ya, Aktifkan</span>
                    <span id="reactivateLoading" style="display:none">
                        <span class="spinner-border spinner-border-sm"></span>
                    </span>
                </button>
            </div>
        </div>
    </div>
</div>

<style>
.overflow-auto thead.sticky-top th {
    top: 0; z-index: 2; background: #f8f9fa;
}
[data-bs-theme="dark"] .overflow-auto thead.sticky-top th {
    background: #2a3447;
}
.exit-info { font-size: .78rem; line-height: 1.5; }
.exit-info .label { color: #888; }
</style>

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

<?= $this->section('scripts') ?>
<script>
const allStudents = <?= json_encode(array_map(function($s) {
    return [
        'id'          => $s['id'],
        'nis'         => $s['nis'],
        'nisn'        => $s['nisn'] ?? '',
        'full_name'   => $s['full_name'],
        'gender'      => $s['gender'],
        'birth_place' => $s['birth_place'] ?? '',
        'birth_date'  => $s['birth_date'] ?? '',
        'status'      => $s['status'],
        'entry_year'  => $s['entry_year'] ?? '',
        'exit_date'   => $s['exit_date'] ?? '',
        'exit_to'     => $s['exit_to'] ?? '',
        'exit_reason' => $s['exit_reason'] ?? '',
    ];
}, $students)) ?>;

let reactivateId = null;

// ── INIT ─────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
    applyFilter(true);
});

// ── FILTER & SEARCH ──────────────────────────────────────────
function applyFilter(isStatusChange = false) {
    const status = document.getElementById('filterStatus').value;
    const yearSelect = document.getElementById('filterYear');
    const searchInput = document.getElementById('searchInput');
    
    if (!status) {
        yearSelect.disabled = true;
        yearSelect.value = '';
        yearSelect.innerHTML = '<option value="">-- Pilih Tahun --</option>';
        document.getElementById('labelYear').textContent = 'Tahun';
        
        searchInput.disabled = true;
        searchInput.value = '';
        resetBody();
        updateCount(0, 0);
        return;
    }

    if (isStatusChange) {
        populateYearFilter(status);
    }

    const year = yearSelect.value;
    const q = searchInput.value.toLowerCase().trim();
    searchInput.disabled = false;

    const filtered = allStudents.filter(s => {
        const matchStatus = s.status === status;
        
        let matchYear = true;
        if (year) {
            if (s.exit_date) {
                const d = new Date(s.exit_date);
                matchYear = !isNaN(d.getTime()) && d.getFullYear().toString() === year;
            } else {
                matchYear = false;
            }
        }

        const matchSearch = !q ||
            s.full_name.toLowerCase().includes(q) ||
            s.nis.toLowerCase().includes(q) ||
            (s.nisn ?? '').toLowerCase().includes(q);
        
        return matchStatus && matchYear && matchSearch;
    });

    renderStudents(filtered);
    
    // Calculate total in this status and year combination
    const totalInStatusAndYear = allStudents.filter(s => {
        const matchStatus = s.status === status;
        let matchYear = true;
        if (year) {
            if (s.exit_date) {
                const d = new Date(s.exit_date);
                matchYear = !isNaN(d.getTime()) && d.getFullYear().toString() === year;
            } else {
                matchYear = false;
            }
        }
        return matchStatus && matchYear;
    }).length;

    updateCount(filtered.length, totalInStatusAndYear);
}

function populateYearFilter(status) {
    const yearSelect = document.getElementById('filterYear');
    const labelYear = document.getElementById('labelYear');
    
    if (status === 'Alumni') {
        labelYear.textContent = 'Tahun Lulus';
    } else {
        labelYear.textContent = 'Tahun Keluar';
    }

    // Find all unique years for the selected status
    const years = new Set();
    allStudents.forEach(s => {
        if (s.status === status && s.exit_date) {
            const d = new Date(s.exit_date);
            if (!isNaN(d.getTime())) {
                years.add(d.getFullYear());
            }
        }
    });

    // Sort years descending
    const sortedYears = Array.from(years).sort((a, b) => b - a);

    // Re-populate select options
    const currentValue = yearSelect.value;
    yearSelect.innerHTML = '<option value="">-- Semua Tahun --</option>';
    sortedYears.forEach(y => {
        const opt = new Option(y, y);
        yearSelect.appendChild(opt);
    });

    // Restore previous value if it still exists in the new options
    if (sortedYears.includes(parseInt(currentValue))) {
        yearSelect.value = currentValue;
    } else {
        yearSelect.value = '';
    }
    
    yearSelect.disabled = false;
}

function resetBody() {
    document.getElementById('studentBody').innerHTML = `
        <tr>
            <td colspan="7" class="text-center text-muted py-5">
                <i class="bi bi-funnel fs-2 d-block mb-2 opacity-25"></i>
                <small>Pilih status untuk menampilkan data alumni & non-aktif</small>
            </td>
        </tr>`;
}

function resetFilter() {
    document.getElementById('filterStatus').value = '';
    document.getElementById('filterYear').value = '';
    document.getElementById('searchInput').value = '';
    applyFilter(true);
}

// ── RENDER ───────────────────────────────────────────────────
function renderStudents(students) {
    if (students.length === 0) {
        document.getElementById('studentBody').innerHTML = `
            <tr>
                <td colspan="7" class="text-center text-muted py-5">
                    <i class="bi bi-inbox fs-2 d-block mb-2 opacity-25"></i>
                    <small>Tidak ada data</small>
                </td>
            </tr>`;
        return;
    }

    const statusMap = {
        'Alumni'   : ['bg-success', 'mortarboard'],
        'Mutasi'   : ['bg-warning', 'arrow-right-circle'],
        'Drop Out' : ['bg-danger',  'x-circle'],
    };

    const html = students.map((s, idx) => {
        const genderBg = s.gender === 'L' ? '#0d6efd' : '#e91e8c';
        const [badgeClass, icon] = statusMap[s.status] ?? ['bg-secondary', 'question-circle'];

        // ── Info Keluar ──────────────────────────────────────
        let exitHtml = '<span class="text-muted small">—</span>';

        if (s.status === 'Alumni') {
            const parts = [];
            let gradYear = '—';
            if (s.exit_date) {
                const d = new Date(s.exit_date);
                if (!isNaN(d.getTime())) {
                    gradYear = d.getFullYear();
                }
            }
            parts.push(`<span class="label">Tahun Lulus: </span>${gradYear}`);
            if (s.entry_year) {
                parts.push(`<span class="label">Angkatan: </span>${escHtml(s.entry_year)}`);
            }
            exitHtml = `<div class="exit-info">${parts.join('<br>')}</div>`;

        } else if (s.status === 'Mutasi') {
            const parts = [];
            if (s.exit_date) {
                const d = new Date(s.exit_date);
                parts.push(`<span class="label">Tanggal: </span>${d.toLocaleDateString('id-ID',{day:'2-digit',month:'short',year:'numeric'})}`);
            }
            if (s.exit_to) {
                parts.push(`<span class="label">Tujuan: </span>${escHtml(s.exit_to)}`);
            }
            if (s.exit_reason) {
                parts.push(`<span class="label">Alasan: </span>${escHtml(s.exit_reason)}`);
            }
            exitHtml = parts.length
                ? `<div class="exit-info">${parts.join('<br>')}</div>`
                : '<span class="text-muted small fst-italic">Belum diisi</span>';

        } else if (s.status === 'Drop Out') {
            const parts = [];
            if (s.exit_date) {
                const d = new Date(s.exit_date);
                parts.push(`<span class="label">Tanggal: </span>${d.toLocaleDateString('id-ID',{day:'2-digit',month:'short',year:'numeric'})}`);
            }
            if (s.exit_reason) {
                parts.push(`<span class="label">Alasan: </span>${escHtml(s.exit_reason)}`);
            }
            exitHtml = parts.length
                ? `<div class="exit-info">${parts.join('<br>')}</div>`
                : '<span class="text-muted small fst-italic">Belum diisi</span>';
        }

        return `
        <tr id="row-${s.id}">
            <td class="text-center text-muted small align-middle">${idx + 1}</td>
            <td class="align-middle">
                <div class="fw-semibold small">${escHtml(s.nis)}</div>
                <div class="text-muted" style="font-size:.72rem">${escHtml(s.nisn || '—')}</div>
            </td>
            <td class="align-middle">
                <span class="fw-semibold small">${escHtml(s.full_name)}</span>
            </td>
            <td class="align-middle">
                <span class="badge" style="font-size:.7rem;background:${genderBg}">${s.gender}</span>
            </td>
            <td class="align-middle">
                <span class="badge ${badgeClass}" style="font-size:.7rem">
                    <i class="bi bi-${icon} me-1"></i>${escHtml(s.status)}
                </span>
            </td>
            <td class="align-middle">${exitHtml}</td>
            <td class="align-middle">
                <div class="d-flex gap-1">
                    <a href="/student/show/${s.id}"
                        class="btn btn-sm btn-outline-info" title="Detail">
                        <i class="bi bi-eye"></i>
                    </a>
                    <button class="btn btn-sm btn-outline-success" title="Aktifkan Kembali"
                        onclick="openReactivate(${s.id}, '${escHtml(s.full_name)}')">
                        <i class="bi bi-arrow-repeat"></i>
                    </button>
                </div>
            </td>
        </tr>`;
    }).join('');

    document.getElementById('studentBody').innerHTML = html;
}

// ── REAKTIVASI ───────────────────────────────────────────────
function openReactivate(id, name) {
    reactivateId = id;
    document.getElementById('reactivateName').textContent = name;
    new bootstrap.Modal(document.getElementById('reactivateModal')).show();
}

document.getElementById('btnReactivateConfirm').addEventListener('click', function() {
    if (!reactivateId) return;

    document.getElementById('reactivateLabel').style.display   = 'none';
    document.getElementById('reactivateLoading').style.display = '';
    this.disabled = true;

    fetch(`/student/reactivate/${reactivateId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: `<?= csrf_token() ?>=${encodeURIComponent('<?= csrf_hash() ?>')}`
    })
    .then(r => r.json())
    .then(data => {
        bootstrap.Modal.getInstance(document.getElementById('reactivateModal')).hide();

        if (data.success) {
            const row = document.getElementById(`row-${reactivateId}`);
            if (row) row.remove();

            const idx = allStudents.findIndex(s => s.id == reactivateId);
            if (idx !== -1) allStudents.splice(idx, 1);
            applyFilter();

            let msg = data.message;
            if (!data.has_class) {
                msg += ' Silakan assign ke kelas melalui menu Assign Kelas.';
            } else {
                msg += ` Kelas: ${data.kelas}.`;
            }
            showToast(msg, 'success');
        } else {
            showToast(data.message, 'danger');
        }

        document.getElementById('reactivateLabel').style.display   = '';
        document.getElementById('reactivateLoading').style.display = 'none';
        document.getElementById('btnReactivateConfirm').disabled   = false;
        reactivateId = null;
    })
    .catch(() => {
        showToast('Terjadi kesalahan!', 'danger');
        document.getElementById('reactivateLabel').style.display   = '';
        document.getElementById('reactivateLoading').style.display = 'none';
        document.getElementById('btnReactivateConfirm').disabled   = false;
    });
});

// ── HELPERS ──────────────────────────────────────────────────
function updateCount(shown, total) {
    document.getElementById('totalCount').textContent = shown;
    const info = document.getElementById('infoCount');
    if (shown === 0 && total === 0) {
        info.textContent = '';
    } else {
        info.textContent = shown === total ? `${total} siswa` : `${shown} dari ${total} siswa`;
    }
}

function showToast(msg, type = 'success') {
    const wrapper = document.createElement('div');
    wrapper.className = 'position-fixed bottom-0 end-0 p-3';
    wrapper.style.zIndex = '9999';
    wrapper.innerHTML = `
        <div class="toast align-items-center text-white bg-${type} border-0 show" role="alert">
            <div class="d-flex">
                <div class="toast-body fw-semibold small">${escHtml(msg)}</div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        </div>`;
    document.body.appendChild(wrapper);
    setTimeout(() => wrapper.remove(), 4000);
}

function escHtml(str) {
    return String(str ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;')
        .replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}
</script>
<?= $this->endSection() ?>