<?= $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-people text-primary"></i>
            <span class="fw-semibold">Data Siswa Aktif</span>
            <?php if ($activePeriod): ?>
            <span class="badge bg-success">
                <?= esc($activePeriod['year_name']) ?> — <?= esc($activePeriod['semester']) ?>
            </span>
            <?php endif; ?>
        </div>
        <div class="d-flex gap-2">
            <a href="/student/generate-accounts" class="btn btn-warning btn-sm text-dark fw-semibold" onclick="return confirm('Apakah Anda yakin ingin memproses massal pembuatan akun login untuk seluruh siswa yang belum memilikinya?')">
                <i class="bi bi-person-plus-fill me-1"></i>Generate Akun Siswa
            </a>
            <a href="/student/create" class="btn btn-primary btn-sm">
                <i class="bi bi-plus-circle me-1"></i>Tambah Siswa
            </a>
            <a href="/student/import" class="btn btn-success btn-sm">
                <i class="bi bi-file-earmark-excel me-1"></i>Import Excel
            </a>
        </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">
            <div class="col-sm-3">
                <label class="form-label small text-muted mb-1">Tingkat</label>
                <select id="filterGrade" class="form-select form-select-sm" onchange="onGradeChange()">
                    <option value="">-- Pilih Tingkat --</option>
                    <?php foreach ($grades as $grade): ?>
                    <option value="<?= $grade['id'] ?>"><?= esc($grade['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-sm-3">
                <label class="form-label small text-muted mb-1">Kelas</label>
                <select id="filterClassroom" class="form-select form-select-sm" disabled onchange="onClassroomChange()">
                    <option value="">-- Pilih Kelas --</option>
                </select>
            </div>
            <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="onSearch()" 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" 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" id="tableStudent">
            <thead class="table-light sticky-top">
                <tr>
                    <th style="width:40px" class="text-center">No</th>
                    <th style="width:52px">Foto</th>
                    <th>NIS</th>
                    <th>NISN</th>
                    <th>Nama Lengkap</th>
                    <th style="width:50px">L/P</th>
                    <th>TTL</th>
                    <th style="width:110px">Aksi</th>
                </tr>
            </thead>
            <tbody id="studentBody">
                <tr>
                    <td colspan="8" class="text-center text-muted py-5">
                        <i class="bi bi-funnel fs-2 d-block mb-2 opacity-25"></i>
                        <small>Pilih tingkat dan kelas untuk menampilkan data siswa</small>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- Modal Mutasi / DO / Keluar -->
    <div class="modal fade" id="exitStudentModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <form id="exitStudentForm">
                <?= csrf_field() ?>
                <input type="hidden" name="student_id" id="exitStudentId">
                <div class="modal-content border-0 shadow">
                    <div class="modal-header bg-warning-subtle py-3">
                        <h5 class="modal-title fw-bold text-dark"><i class="bi bi-person-dash me-2"></i>Proses Siswa Keluar</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-4">
                        <div class="mb-3">
                            <label class="form-label fw-bold small text-muted">Nama Siswa</label>
                            <input type="text" id="exitStudentName" class="form-control form-control-sm bg-light" readonly>
                        </div>
                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <label class="form-label fw-bold small text-muted">Status Baru <span class="text-danger">*</span></label>
                                <select name="status" id="exitStatus" class="form-select form-select-sm" required onchange="toggleExitToField(this.value)">
                                    <option value="">-- Pilih --</option>
                                    <option value="Mutasi">Mutasi</option>
                                    <option value="Drop Out">Drop Out</option>
                                    <option value="Alumni">Alumni</option>
                                </select>
                            </div>
                            <div class="col-6">
                                <label class="form-label fw-bold small text-muted">Tanggal Keluar <span class="text-danger">*</span></label>
                                <input type="date" name="exit_date" id="exitDate" class="form-control form-control-sm" required>
                            </div>
                        </div>
                        <div class="mb-3" id="exitToField" style="display:none">
                            <label class="form-label fw-bold small text-muted">Sekolah Tujuan <span class="text-danger">*</span></label>
                            <input type="text" name="exit_to" id="exitTo" class="form-control form-control-sm" placeholder="Contoh: SMP Negeri 1 Wonogiri">
                        </div>
                        <div class="mb-0">
                            <label class="form-label fw-bold small text-muted">Alasan Keluar</label>
                            <textarea name="exit_reason" id="exitReason" class="form-control form-control-sm" rows="3" placeholder="Alasan keluar/mutasi siswa..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer border-top-0">
                        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-sm btn-warning fw-semibold"><i class="bi bi-check-circle me-1"></i>Ya, Proses Keluar</button>
                    </div>
                </div>
            </form>
        </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;
}
.avatar-sm {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    object-fit: cover;
    background: #e8f0fe;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #0d6efd;
    font-size: 1rem;
    flex-shrink: 0;
}
</style>

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

<?= $this->section('scripts') ?>
<script>
const allClassrooms = [
    <?php foreach ($classrooms as $c): ?>
    { id: '<?= $c['id'] ?>', gradeId: '<?= $c['grade_id'] ?>', name: '<?= esc($c['name']) ?>' },
    <?php endforeach; ?>
];

const PERIOD_ID = <?= $activePeriod['id'] ?? 0 ?>;

let allStudents  = []; // cache hasil AJAX
let currentClass = '';

// ── LOCAL STORAGE ────────────────────────────────────────────
function saveFilterState() {
    const gradeId = document.getElementById('filterGrade').value;
    const classroomId = document.getElementById('filterClassroom').value;
    localStorage.setItem('student_filter_grade', gradeId);
    localStorage.setItem('student_filter_classroom', classroomId);
}

function restoreFilterState() {
    const savedGrade = localStorage.getItem('student_filter_grade');
    const savedClass = localStorage.getItem('student_filter_classroom');

    if (!savedGrade && !savedClass) return false;

    if (savedGrade) {
        const gradeSel = document.getElementById('filterGrade');
        gradeSel.value = savedGrade;
        onGradeChange();
    }

    if (savedClass) {
        const selClass = document.getElementById('filterClassroom');
        selClass.value = savedClass;
        onClassroomChange();
    }

    return true;
}

function clearFilterState() {
    localStorage.removeItem('student_filter_grade');
    localStorage.removeItem('student_filter_classroom');
}

// ── FILTER GRADE ─────────────────────────────────────────────
function onGradeChange() {
    const gradeId = document.getElementById('filterGrade').value;
    const selClass = document.getElementById('filterClassroom');

    selClass.innerHTML = '<option value="">-- Pilih Kelas --</option>';
    allClassrooms
        .filter(c => !gradeId || c.gradeId === gradeId)
        .forEach(c => selClass.appendChild(new Option(c.name, c.id)));

    selClass.disabled = !gradeId;
    document.getElementById('searchInput').disabled = true;
    document.getElementById('searchInput').value   = '';
    currentClass = '';
    allStudents  = [];
    resetBody();
    updateCount();
    saveFilterState();
}

// ── FILTER CLASSROOM ──────────────────────────────────────────
function onClassroomChange() {
    const classroomId = document.getElementById('filterClassroom').value;
    if (!classroomId) {
        document.getElementById('searchInput').disabled = true;
        document.getElementById('searchInput').value   = '';
        currentClass = '';
        allStudents  = [];
        resetBody();
        updateCount();
        saveFilterState();
        return;
    }

    currentClass = classroomId;
    loadStudents(classroomId);
    saveFilterState();
}

// ── SEARCH (client-side filter dari cache) ────────────────────
function onSearch() {
    const q = document.getElementById('searchInput').value.toLowerCase();
    const filtered = allStudents.filter(s =>
        s.full_name.toLowerCase().includes(q) ||
        s.nis.toLowerCase().includes(q) ||
        (s.nisn ?? '').toLowerCase().includes(q)
    );
    renderStudents(filtered);
    updateCount(filtered.length, allStudents.length);
}

// ── RESET ────────────────────────────────────────────────────
function resetFilter() {
    document.getElementById('filterGrade').value      = '';
    document.getElementById('filterClassroom').innerHTML = '<option value="">-- Pilih Kelas --</option>';
    document.getElementById('filterClassroom').disabled  = true;
    document.getElementById('searchInput').value      = '';
    document.getElementById('searchInput').disabled   = true;
    currentClass = '';
    allStudents  = [];
    resetBody();
    updateCount();
    clearFilterState();
}

// ── LOAD AJAX ────────────────────────────────────────────────
function loadStudents(classroomId) {
    setLoading();

    fetch(`/student/by-class?classroom_id=${classroomId}&period_id=${PERIOD_ID}`)
        .then(r => r.json())
        .then(data => {
            allStudents = data.students ?? [];
            document.getElementById('searchInput').disabled = false;
            document.getElementById('searchInput').value   = '';
            renderStudents(allStudents);
            updateCount(allStudents.length);
        })
        .catch(() => {
            document.getElementById('studentBody').innerHTML = errorRow();
        });
}

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

    const html = students.map((s, idx) => {
        const no = idx + 1;
        const foto = s.photo
            ? `<img src="${s.photo_url}" class="avatar-sm" alt="" style="object-fit: cover;">`
            : `<div class="avatar-sm mx-auto"><i class="bi bi-person"></i></div>`;

        const ttl = [s.birth_place, s.birth_date
            ? new Date(s.birth_date).toLocaleDateString('id-ID', { day:'2-digit', month:'short', year:'numeric' })
            : null]
            .filter(Boolean).join(', ') || '-';

        const genderBg = s.gender === 'L' ? '#0d6efd' : '#e91e8c';

        return `
        <tr>
            <td class="text-center text-muted small align-middle">${no}</td>
            <td class="text-center align-middle">${foto}</td>
            <td class="fw-semibold small align-middle">${escHtml(s.nis)}</td>
            <td class="small text-muted align-middle">${escHtml(s.nisn ?? '-')}</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="small text-muted align-middle">${escHtml(ttl)}</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>
                    <a href="/student/edit/${s.id}" class="btn btn-sm btn-outline-primary" title="Edit">
                        <i class="bi bi-pencil"></i>
                    </a>
                    <button type="button" class="btn btn-sm btn-outline-warning" title="Mutasi / DO / Keluar" onclick="openExitModal(${s.id}, '${escHtml(s.full_name)}')">
                        <i class="bi bi-person-dash"></i>
                    </button>
                    <a href="/student/delete/${s.id}"
                        class="btn btn-sm btn-outline-danger" title="Hapus"
                        onclick="return confirm('Hapus data siswa ini?')">
                        <i class="bi bi-trash"></i>
                    </a>
                </div>
            </td>
        </tr>`;
    }).join('');

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

// ── HELPERS ──────────────────────────────────────────────────
function setLoading() {
    document.getElementById('studentBody').innerHTML = `
        <tr>
            <td colspan="8" class="text-center text-muted py-5">
                <span class="spinner-border spinner-border-sm me-2"></span>
                <small>Memuat data...</small>
            </td>
        </tr>`;
}

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

function errorRow() {
    return `<tr><td colspan="8" class="text-center text-danger py-4 small">
        <i class="bi bi-exclamation-circle me-1"></i>Gagal memuat data
    </td></tr>`;
}

function updateCount(shown, total) {
    const el = document.getElementById('infoCount');
    if (shown === undefined) {
        el.textContent = '';
    } else if (total !== undefined && shown !== total) {
        el.textContent = `${shown} dari ${total} siswa`;
    } else {
        el.textContent = `${shown} siswa`;
    }
}

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

let exitModalInstance = null;

function openExitModal(id, name) {
    document.getElementById('exitStudentId').value = id;
    document.getElementById('exitStudentName').value = name;
    document.getElementById('exitStatus').value = '';
    
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('exitDate').value = today;
    
    document.getElementById('exitTo').value = '';
    document.getElementById('exitReason').value = '';
    document.getElementById('exitToField').style.display = 'none';
    document.getElementById('exitTo').required = false;

    if (!exitModalInstance) {
        exitModalInstance = new bootstrap.Modal(document.getElementById('exitStudentModal'));
    }
    exitModalInstance.show();
}

function toggleExitToField(status) {
    const field = document.getElementById('exitToField');
    const input = document.getElementById('exitTo');
    if (status === 'Mutasi') {
        field.style.display = 'block';
        input.required = true;
    } else {
        field.style.display = 'none';
        input.required = false;
        input.value = '';
    }
}

function updateCsrfTokens(newHash) {
    const csrfInputs = document.querySelectorAll('input[name="<?= csrf_token() ?>"]');
    csrfInputs.forEach(input => {
        input.value = newHash;
    });
}

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);
}

// Form Exit Student AJAX Submit
document.addEventListener('DOMContentLoaded', function() {
    restoreFilterState();

    const form = document.getElementById('exitStudentForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const studentId = document.getElementById('exitStudentId').value;
            const status = document.getElementById('exitStatus').value;
            const date = document.getElementById('exitDate').value;
            const to = document.getElementById('exitTo').value;
            const reason = document.getElementById('exitReason').value;

            const csrfTokenInput = form.querySelector('input[name="<?= csrf_token() ?>"]');
            const csrfHash = csrfTokenInput ? csrfTokenInput.value : '';

            const params = new URLSearchParams();
            params.append('status', status);
            params.append('exit_date', date);
            params.append('exit_to', to);
            params.append('exit_reason', reason);
            params.append('<?= csrf_token() ?>', csrfHash);

            fetch(`/student/exit-process/${studentId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: params
            })
            .then(r => r.json())
            .then(data => {
                if (data.csrf_token) {
                    updateCsrfTokens(data.csrf_token);
                    if (csrfTokenInput) {
                        csrfTokenInput.value = data.csrf_token;
                    }
                }
                
                if (data.success) {
                    showToast(data.message, 'success');
                    if (exitModalInstance) {
                        exitModalInstance.hide();
                    }
                    
                    const idx = allStudents.findIndex(s => s.id == studentId);
                    if (idx !== -1) {
                        allStudents.splice(idx, 1);
                    }
                    renderStudents(allStudents);
                    updateCount(allStudents.length);
                } else {
                    showToast(data.message, 'danger');
                }
            })
            .catch(() => {
                showToast('Terjadi kesalahan koneksi!', 'danger');
            });
        });
    }
});
</script>
<?= $this->endSection() ?>