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

<style>
.qr-table { font-size: 11px; min-width: 1000px }
.qr-table thead th { position: sticky; top: 0; z-index: 2; background: #f8f9fa; text-align: center; vertical-align: middle }
.qr-table thead th.day-col { width: 25px; font-size: 9px; padding: 2px 1px }
.qr-table tbody td { text-align: center; vertical-align: middle; padding: 2px 3px; font-size: 10px }
.qr-table tbody td.name-col { text-align: left; white-space: nowrap; font-size: 11px }
.qr-table .day-off { background: #ffe5e5 !important }
.qr-table .off-label { background: #ffe5e5; color: #999; font-size: 8px }
.qr-table .s { color: #0d6efd; font-weight: bold }
.qr-table .i { color: #fd7e14; font-weight: bold }
.qr-table .a { color: #dc3545; font-weight: bold }
.qr-table .dot { color: #adb5bd }
.qr-table .sum { font-weight: bold; font-size: 10px }
[data-bs-theme="dark"] .qr-table thead th { background: #2a3447 }
[data-bs-theme="dark"] .day-off { background: #3a1a1a !important }
[data-bs-theme="dark"] .qr-table .off-label { background: #3a1a1a }
</style>

<div class="card">
    <div class="card-header">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-graph-up-arrow text-primary"></i>
            <span class="fw-semibold">Rekap Absensi Bulanan (QR Code)</span>
        </div>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-3">
                <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-3">
                <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-2">
                <div class="mb-3">
                    <label class="form-label">Bulan</label>
                    <select id="month" class="form-select">
                        <?php foreach ($months as $num => $name): ?>
                        <option value="<?= $num ?>" <?= date('n') == $num ? 'selected' : '' ?>><?= $name ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-2">
                <div class="mb-3">
                    <label class="form-label">Tahun</label>
                    <select id="year" class="form-select">
                        <?php for ($y = date('Y') - 2; $y <= date('Y') + 1; $y++): ?>
                        <option value="<?= $y ?>" <?= date('Y') == $y ? 'selected' : '' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <div class="d-flex gap-1 mb-3 w-100">
                    <button class="btn btn-primary btn-sm w-100" id="btnView">
                        <i class="bi bi-search me-1"></i>Tampilkan
                    </button>
                    <button class="btn btn-success btn-sm w-100" id="btnExportPDF">
                        <i class="bi bi-file-pdf me-1"></i>PDF
                    </button>
                </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="mb-2 small text-muted">
                <span class="me-3"><span class="text-muted">.</span> = Hadir</span>
                <span class="me-3"><span class="s">S</span> = Sakit</span>
                <span class="me-3"><span class="i">I</span> = Izin</span>
                <span class="me-3"><span class="a">A</span> = Alpha</span>
                <span class="me-3"><span class="day-off">&nbsp;&nbsp;&nbsp;</span> = Libur</span>
            </div>
            <div class="table-responsive" style="max-height: 70vh; overflow-y: auto">
                <table class="table table-bordered table-sm qr-table mb-0" id="qrRekapTable">
                    <thead class="table-light" id="qrRekapHead"></thead>
                    <tbody id="qrRekapBody"></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 month = $('#month').val();
        const year = $('#year').val();
        const periodId = '<?= $activePeriod['id'] ?>';
        const className = $('#classroom_id option:selected').text();
        
        if (!classroomId) {
            alert('Pilih kelas terlebih dahulu!');
            return;
        }
        
        $('#rekapResult').hide();
        $('#qrRekapBody').html('<tr><td colspan="20" class="text-center py-3"><div class="spinner-border spinner-border-sm"></div> Loading...</td></tr>');
        $('#rekapResult').show();
        
        $.ajax({
            url: '/attendance/qr-get-rekap-bulanan',
            method: 'GET',
            data: { classroom_id: classroomId, period_id: periodId, month: month, year: year },
            dataType: 'json',
            success: function(data) {
                if (data.success && data.students.length > 0) {
                    $('#rekapTitle').text(`Rekap Bulanan (QR) - ${className} - ${getMonthName(month)} ${year}`);
                    $('#totalHari').text(`Total hari aktif: ${data.total_hari_aktif} hari`);
                    
                    let headHtml = '<tr><th rowspan="2" width="30">#</th><th rowspan="2">NIS</th><th rowspan="2">Nama Siswa</th><th rowspan="2" width="30">L/P</th>';
                    $.each(data.days, function(i, d) {
                        if (d.is_off) {
                            headHtml += `<th class="day-col off-label">${d.day}</th>`;
                        } else {
                            headHtml += `<th class="day-col">${d.day}</th>`;
                        }
                    });
                    headHtml += '<th width="30" class="bg-info bg-opacity-25">S</th><th width="30" class="bg-warning bg-opacity-25">I</th><th width="30" class="bg-danger bg-opacity-25">A</th><th width="30" class="bg-success bg-opacity-25">H</th></tr>';
                    headHtml += '<tr>';
                    $.each(data.days, function(i, d) {
                        headHtml += `<th class="day-col ${d.is_off ? 'off-label' : ''}" style="font-size:7px">${getDayLetter(d.day, data.bulan, data.tahun)}</th>`;
                    });
                    headHtml += '<th>S</th><th>I</th><th>A</th><th>H</th></tr>';
                    $('#qrRekapHead').html(headHtml);
                    
                    let bodyHtml = '';
                    $.each(data.students, function(i, s) {
                        let genderBadge = s.gender === 'L' ? '<span class="badge bg-primary" style="font-size:8px">L</span>' : '<span class="badge" style="font-size:8px;background:#e91e8c">P</span>';
                        bodyHtml += `<tr><td>${i + 1}</td><td class="small">${s.nis}</td><td class="name-col">${escapeHtml(s.full_name)}</td><td>${genderBadge}</td>`;
                        $.each(data.days, function(j, d) {
                            if (d.is_off) {
                                bodyHtml += `<td class="day-off"></td>`;
                            } else {
                                let st = s.statuses[d.day];
                                let cls = st === 'S' ? 's' : st === 'I' ? 'i' : st === 'A' ? 'a' : 'dot';
                                bodyHtml += `<td class="${cls}">${st || ''}</td>`;
                            }
                        });
                        bodyHtml += `<td class="sum">${s.sakit}</td><td class="sum">${s.izin}</td><td class="sum">${s.alpha}</td><td class="sum">${s.hadir}</td></tr>`;
                    });
                    $('#qrRekapBody').html(bodyHtml);
                } else {
                    $('#qrRekapBody').html('<tr><td colspan="20" class="text-center text-muted py-5">Tidak ada data absensi QR</td></tr>');
                }
            },
            error: function() {
                $('#qrRekapBody').html('<tr><td colspan="20" class="text-center text-danger">Gagal memuat data</td></tr>');
            }
        });
    });
});

function getMonthName(month) {
    const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
    return months[parseInt(month) - 1];
}

function getDayLetter(day, month, year) {
    const date = new Date(year, month - 1, day);
    const days = ['M', 'S', 'S', 'R', 'K', 'J', 'S'];
    return days[date.getDay()];
}

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 month = $('#month').val();
    const year = $('#year').val();
    const periodId = '<?= $activePeriod['id'] ?>';
    
    if (!classroomId) {
        alert('Pilih kelas terlebih dahulu!');
        return;
    }
    
    window.open(`/attendance/qr-export-pdf-bulanan?classroom_id=${classroomId}&period_id=${periodId}&month=${month}&year=${year}`, '_blank');
});
</script>
<?= $this->endSection() ?>