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

<div class="row">
    <div class="col-12">
        <div class="card mb-3">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-clock-history text-primary"></i>
                <span class="fw-semibold">Riwayat Siswa</span>
            </div>
            <div class="card-body">
                <p class="text-muted small mb-3">
                    Masukkan NIS, NISN, atau nama siswa untuk mencari riwayat akademik.
                </p>
                <div class="row g-2">
                    <div class="col-md-8">
                        <div class="input-group">
                            <span class="input-group-text bg-light">
                                <i class="bi bi-search text-muted"></i>
                            </span>
                            <input type="text" id="searchInput" class="form-control"
                                placeholder="Ketik NIS, NISN, atau nama siswa...">
                            <button class="btn btn-primary" id="btnSearch">
                                <i class="bi bi-search me-1"></i>Cari
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Hasil Pencarian -->
    <div class="col-md-5" id="searchResultCard" style="display:none">
        <div class="card mb-3">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-people text-primary"></i>
                <span class="fw-semibold">Hasil Pencarian</span>
                <span class="badge bg-secondary" id="resultCount">0</span>
            </div>
            <div class="card-body p-0">
                <table class="table table-hover mb-0" id="tableSearch">
                    <thead class="table-light">
                        <tr>
                            <th>NIS</th>
                            <th>NISN</th>
                            <th>Nama</th>
                            <th>L/P</th>
                        </tr>
                    </thead>
                    <tbody id="searchBody">
                        <tr>
                            <td colspan="4" class="text-center text-muted py-3">
                                Belum ada hasil pencarian
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Detail & Riwayat -->
    <div class="col-md-7" id="historyCard" style="display:none">
        <div class="card mb-3">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-person-badge text-primary"></i>
                <span class="fw-semibold">Profil Siswa</span>
            </div>
            <div class="card-body" id="studentProfile">
            </div>
        </div>

        <div class="card">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-journal-text text-primary"></i>
                <span class="fw-semibold">Riwayat Akademik</span>
            </div>
            <div class="card-body p-0">
                <table class="table table-hover mb-0" id="tableHistory">
                    <thead class="table-light">
                        <tr>
                            <th>Tahun Ajaran</th>
                            <th>Semester</th>
                            <th>Kelas</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody id="historyBody">
                        <tr>
                            <td colspan="4" class="text-center text-muted py-3">
                                Pilih siswa untuk melihat riwayat
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
const statusColor = {
    'Aktif'        : 'success',
    'Naik Kelas'   : 'primary',
    'Tinggal Kelas': 'warning',
    'Lulus'        : 'info',
    'Mutasi'       : 'secondary',
    'Drop Out'     : 'danger',
};

// Cari siswa
function doSearch() {
    const q = $('#searchInput').val().trim();
    if (q.length < 2) {
        alert('Minimal 2 karakter untuk pencarian!');
        return;
    }

    $('#btnSearch').prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>Mencari...');

    $.get('/student-history/search', { q }, function(res) {
        $('#btnSearch').prop('disabled', false).html('<i class="bi bi-search me-1"></i>Cari');

        if (!res.success || res.students.length === 0) {
            $('#searchBody').html('<tr><td colspan="4" class="text-center text-muted py-3">Siswa tidak ditemukan</td></tr>');
            $('#resultCount').text(0);
            $('#searchResultCard').show();
            $('#historyCard').hide();
            return;
        }

        $('#resultCount').text(res.students.length);
        let html = '';
        res.students.forEach(s => {
            const genderBadge = `<span class="badge" style="background:${s.gender=='L'?'#0d6efd':'#e91e8c'}">${s.gender}</span>`;
            const statusBadge = s.status == 'Aktif'
                ? '<span class="badge bg-success">Aktif</span>'
                : `<span class="badge bg-secondary">${s.status}</span>`;
            html += `
                <tr class="student-row" data-id="${s.id}" style="cursor:pointer" title="Klik untuk lihat riwayat">
                    <td class="fw-semibold">${s.nis}</td>
                    <td>${s.nisn ?? '-'}</td>
                    <td>${s.full_name} ${statusBadge}</td>
                    <td>${genderBadge}</td>
                </tr>`;
        });

        $('#searchBody').html(html);
        $('#searchResultCard').show();

        // Kalau hanya 1 hasil, langsung tampilkan riwayat
        if (res.students.length === 1) {
            loadHistory(res.students[0].id);
        }
    });
}

// Load riwayat siswa
function loadHistory(studentId) {
    $('.student-row').removeClass('table-active');
    $(`.student-row[data-id="${studentId}"]`).addClass('table-active');

    $('#historyBody').html('<tr><td colspan="4" class="text-center py-3"><span class="spinner-border spinner-border-sm"></span> Memuat...</td></tr>');
    $('#historyCard').show();

    $.get(`/student-history/history/${studentId}`, function(res) {
        if (!res.success) {
            $('#historyBody').html('<tr><td colspan="4" class="text-center text-muted py-3">Gagal memuat riwayat</td></tr>');
            return;
        }

        const s = res.student;

        // Profil
        $('#studentProfile').html(`
            <div class="row g-2">
                <div class="col-sm-6">
                    <table class="table table-sm table-borderless mb-0">
                        <tr><td class="text-muted" width="40%">NIS</td><td class="fw-semibold">${s.nis}</td></tr>
                        <tr><td class="text-muted">NISN</td><td>${s.nisn ?? '-'}</td></tr>
                        <tr><td class="text-muted">Nama</td><td class="fw-semibold">${s.full_name}</td></tr>
                    </table>
                </div>
                <div class="col-sm-6">
                    <table class="table table-sm table-borderless mb-0">
                        <tr><td class="text-muted" width="40%">L/P</td><td>${s.gender == 'L' ? 'Laki-laki' : 'Perempuan'}</td></tr>
                        <tr><td class="text-muted">Masuk</td><td>${s.entry_year ?? '-'}</td></tr>
                        <tr><td class="text-muted">Status</td><td><span class="badge bg-${s.status=='Aktif'?'success':'secondary'}">${s.status}</span></td></tr>
                    </table>
                </div>
            </div>
        `);

        // Riwayat
        if (!res.histories || res.histories.length === 0) {
            $('#historyBody').html('<tr><td colspan="4" class="text-center text-muted py-3">Belum ada riwayat akademik</td></tr>');
            return;
        }

        let html = '';
        res.histories.forEach(h => {
            const semBadge = `<span class="badge ${h.semester=='Ganjil'?'bg-primary':'bg-info text-dark'}">${h.semester}</span>`;
            const stColor  = statusColor[h.status] ?? 'secondary';
            html += `
                <tr>
                    <td>${h.year_name}</td>
                    <td>${semBadge}</td>
                    <td>${h.grade_name} — ${h.classroom_name}</td>
                    <td><span class="badge bg-${stColor}">${h.status}</span></td>
                </tr>`;
        });
        $('#historyBody').html(html);
    });
}

// Event listeners
$('#btnSearch').on('click', doSearch);
$('#searchInput').on('keypress', function(e) {
    if (e.which === 13) doSearch();
});
$(document).on('click', '.student-row', function() {
    loadHistory($(this).data('id'));
});
</script>
<?= $this->endSection() ?>