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

<div class="card border-0 shadow-sm">
    <div class="card-header bg-white py-3">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-graph-up text-primary fs-5"></i>
            <span class="fw-semibold text-dark">Rekap Absensi Bulanan</span>
        </div>
    </div>
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-3">
                <div class="mb-3">
                    <label class="form-label small fw-semibold">Tingkat</label>
                    <select id="grade_id" class="form-select form-select-sm">
                        <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 small fw-semibold">Kelas</label>
                    <select id="classroom_id" class="form-select form-select-sm" disabled>
                        <option value="">-- Pilih Tingkat Dulu --</option>
                    </select>
                </div>
            </div>
            <div class="col-md-3">
                <div class="mb-3">
                    <label class="form-label small fw-semibold">Bulan</label>
                    <select id="month" class="form-select form-select-sm">
                        <?php foreach ($months as $num => $name): ?>
                        <option value="<?= sprintf('%02d', $num) ?>" <?= date('n') == $num ? 'selected' : '' ?>><?= $name ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-3">
                <div class="mb-3">
                    <label class="form-label small fw-semibold">Tahun</label>
                    <select id="year" class="form-select form-select-sm">
                        <?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>
        
        <div class="d-flex flex-wrap gap-2 mt-2 mb-4">
            <button class="btn btn-sm btn-primary px-3" id="btnView">
                <i class="bi bi-search me-1"></i>Tampilkan
            </button>
            <button class="btn btn-sm btn-success px-3" id="btnExportPDF">
                <i class="bi bi-file-pdf me-1"></i>Cetak Rekap
            </button>
            <button class="btn btn-sm btn-outline-success px-3" id="btnExportExcel">
                <i class="bi bi-file-earmark-excel me-1"></i>Excel (Ringkasan)
            </button>
        </div>
        
        <div id="rekapResult" style="display:none">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0 fw-bold text-dark" id="rekapTitle"></h6>
                <span class="badge bg-secondary" id="totalHari"></span>
            </div>
            <div class="table-responsive">
                <table class="table table-bordered table-striped table-hover align-middle mb-0" id="recap-table" style="min-width: 1000px; font-size: 12px;">
                    <thead class="table-light">
                        <tr id="rekapHeaderRow">
                            <!-- Loaded dynamically -->
                        </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 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();
        $('#rekapBody').html('<tr><td colspan="15" class="text-center py-3"><div class="spinner-border spinner-border-sm text-primary"></div> Loading...<\/td></tr>');
        $('#rekapResult').show();
        
        $.ajax({
            url: '/attendance/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 - ${className} - ${getMonthName(month)} ${year}`);
                    $('#totalHari').text(`Total hari aktif: ${data.total_hari_aktif} hari`);
                    
                    // Draw Headers
                    let headHtml = `
                        <th class="text-center" style="width: 40px;">No</th>
                        <th style="width: 90px;">NIS</th>
                        <th style="min-width: 150px;">Nama Siswa</th>
                        <th class="text-center" style="width: 40px;">L/P</th>
                    `;
                    
                    data.days.forEach(day => {
                        let bgStyle = day.is_off ? 'background-color: #ffe5e5 !important; color: #dc3545;' : '';
                        let titleAttr = day.holiday_title ? `title="${day.holiday_title}" data-bs-toggle="tooltip"` : '';
                        headHtml += `<th class="text-center" style="width: 25px; min-width: 25px; font-size: 9px; padding: 4px 2px; ${bgStyle}" ${titleAttr}>${day.day}</th>`;
                    });
                    
                    headHtml += `
                        <th class="text-center text-info" style="width: 35px;">S</th>
                        <th class="text-center text-warning" style="width: 35px;">I</th>
                        <th class="text-center text-danger" style="width: 35px;">A</th>
                        <th class="text-center fw-bold" style="width: 45px;">H</th>
                    `;
                    $('#rekapHeaderRow').html(headHtml);
                    
                    // Draw Rows
                    let html = '';
                    $.each(data.students, function(i, s) {
                        let colsHtml = '';
                        data.days.forEach(day => {
                            let status = s.statuses[day.day] || '.';
                            let cellClass = 'text-center';
                            let cellStyle = day.is_off ? 'background-color: #fff2f2;' : '';
                            
                            if (status === 'S') cellClass += ' text-info fw-bold';
                            else if (status === 'I') cellClass += ' text-warning fw-bold';
                            else if (status === 'A') cellClass += ' text-danger fw-bold';
                            else if (status === '.') cellClass += ' text-muted';
                            
                            colsHtml += `<td class="${cellClass}" style="padding: 4px 2px; font-size: 10px; ${cellStyle}">${status}</td>`;
                        });

                        html += `
                            <tr>
                                <td class="text-center text-muted small">${i + 1}</td>
                                <td><code>${s.nis}</code></td>
                                <td class="fw-semibold text-dark text-truncate" style="max-width: 150px;" title="${s.full_name}">${escapeHtml(s.full_name)}</td>
                                <td class="text-center"><span class="badge bg-light text-dark" style="font-size: 10px;">${s.gender}</span></td>
                                ${colsHtml}
                                <td class="text-center text-info font-monospace fw-bold" style="font-size: 11px;">${s.sakit || '-'}</td>
                                <td class="text-center text-warning font-monospace fw-bold" style="font-size: 11px;">${s.izin || '-'}</td>
                                <td class="text-center text-danger font-monospace fw-bold" style="font-size: 11px;">${s.alpha || '-'}</td>
                                <td class="text-center font-monospace fw-bold" style="font-size: 11px;">${s.hadir}</td>
                            </tr>
                        `;
                    });
                    $('#rekapBody').html(html);
                    
                    // Initialize tooltips
                    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
                    tooltipTriggerList.map(function (tooltipTriggerEl) {
                        return new bootstrap.Tooltip(tooltipTriggerEl);
                    });
                } else {
                    $('#rekapBody').html('<tr><td colspan="15" 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="15" 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 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/export-pdf-bulanan?classroom_id=${classroomId}&period_id=${periodId}&month=${month}&year=${year}`, '_blank');
});

$('#btnExportExcel').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/export-excel-bulanan?classroom_id=${classroomId}&period_id=${periodId}&month=${month}&year=${year}`, '_blank');
});
</script>
<?= $this->endSection() ?>