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

<div class="card">
    <div class="card-header">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-calendar-range text-primary"></i>
            <span class="fw-semibold">Rekap Absensi Semester</span>
        </div>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">Tingkat</label>
                    <select id="grade_id" class="form-select">
                        <option value="">-- Pilih Tingkat --</option>
                        <?php foreach ($grades as $g): ?>
                        <option value="<?= $g['id'] ?>"><?= esc($g['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">Kelas</label>
                    <select id="classroom_id" class="form-select" disabled>
                        <option value="">-- Pilih Tingkat Dulu --</option>
                    </select>
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">&nbsp;</label>
                    <div class="d-flex gap-2">
                        <button class="btn btn-primary" id="btnView">
                            <i class="bi bi-search me-1"></i>Tampilkan
                        </button>
                        <button class="btn btn-success" id="btnExportPDF">
                            <i class="bi bi-file-pdf me-1"></i>Export PDF
                        </button>
                        <button class="btn btn-outline-success" id="btnExportExcel">
                            <i class="bi bi-file-earmark-excel me-1"></i>Excel
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <hr>
        
        <div id="rekapResult" style="display:none">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0" id="rekapTitle"></h6>
                <span class="badge bg-secondary" id="totalHari"></span>
            </div>
            <div class="table-responsive">
                <table class="table table-bordered table-sm">
                    <thead class="table-light">
                        <tr>
                            <th width="40">#</th>
                            <th>NIS</th>
                            <th>Nama Siswa</th>
                            <th width="80" class="text-center bg-warning">Sakit</th>
                            <th width="80" class="text-center bg-info">Izin</th>
                            <th width="80" class="text-center bg-danger">Alpha</th>
                        </tr>
                    </thead>
                    <tbody id="rekapBody"></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
$(document).ready(function() {
    $('#grade_id').change(function() {
        const gradeId = $(this).val();
        const classroomSelect = $('#classroom_id');
        
        if (!gradeId) {
            classroomSelect.prop('disabled', true).html('<option value="">-- Pilih Tingkat Dulu --</option>');
            return;
        }
        
        $.ajax({
            url: '/attendance/get-classrooms',
            method: 'GET',
            data: { grade_id: gradeId, period_id: '<?= $activePeriod['id'] ?>' },
            dataType: 'json',
            success: function(data) {
                classroomSelect.prop('disabled', false);
                let options = '<option value="">-- Pilih Kelas --</option>';
                $.each(data, function(i, cls) {
                    options += `<option value="${cls.id}">${cls.name} (${cls.grade_name})</option>`;
                });
                classroomSelect.html(options);
            }
        });
    });
    
    $('#btnView').click(function() {
        const classroomId = $('#classroom_id').val();
        const periodId = '<?= $activePeriod['id'] ?>';
        const className = $('#classroom_id option:selected').text();
        
        if (!classroomId) {
            alert('Pilih kelas terlebih dahulu!');
            return;
        }
        
        $('#rekapResult').hide();
        $('#rekapBody').html('<tr><td colspan="6" class="text-center py-3"><div class="spinner-border spinner-border-sm"></div> Loading...<\/td></td>');
        $('#rekapResult').show();
        
        $.ajax({
            url: '/attendance/get-rekap-semester',
            method: 'GET',
            data: {
                classroom_id: classroomId,
                period_id: periodId
            },
            dataType: 'json',
            success: function(data) {
                if (data.success && data.students.length > 0) {
                    $('#rekapTitle').text(`Rekap Semester - ${className} - ${data.periode}`);
                    $('#totalHari').text(`Total hari aktif: ${data.total_hari_aktif} hari`);
                    
                    let html = '';
                    $.each(data.students, function(i, s) {
                        html += `
                            <tr>
                                <td class="text-center">${i + 1}</td>
                                <td>${s.nis}</td>
                                <td>${escapeHtml(s.full_name)}</td>
                                <td class="text-center bg-warning bg-opacity-25 fw-bold">${s.sakit}</td>
                                <td class="text-center bg-info bg-opacity-25 fw-bold">${s.izin}</td>
                                <td class="text-center bg-danger bg-opacity-25 fw-bold">${s.alpha}</td>
                            </tr>
                        `;
                    });
                    $('#rekapBody').html(html);
                } else {
                    $('#rekapBody').html('<tr><td colspan="6" class="text-center text-muted py-5">Tidak ada data absensi</td></tr>');
                }
            },
            error: function(xhr) {
                console.log(xhr.responseText);
                $('#rekapBody').html('<tr><td colspan="6" class="text-center text-danger">Gagal memuat data</td></tr>');
            }
        });
    });
});

function escapeHtml(str) {
    if (!str) return '';
    return str.replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}

$('#btnExportPDF').click(function() {
    const classroomId = $('#classroom_id').val();
    const periodId = '<?= $activePeriod['id'] ?>';
    
    if (!classroomId) {
        alert('Pilih kelas terlebih dahulu!');
        return;
    }
    
    window.open(`/attendance/export-pdf-semester?classroom_id=${classroomId}&period_id=${periodId}`, '_blank');
});

$('#btnExportExcel').click(function() {
    const classroomId = $('#classroom_id').val();
    const periodId = '<?= $activePeriod['id'] ?>';
    
    if (!classroomId) {
        alert('Pilih kelas terlebih dahulu!');
        return;
    }
    
    window.open(`/attendance/export-excel-semester?classroom_id=${classroomId}&period_id=${periodId}`, '_blank');
});

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