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

<div class="row mb-4">
    <div class="col-12">
        <div class="d-flex align-items-center gap-3">
            <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center"
                 style="width:52px;height:52px">
                <i class="bi bi-journal-text fs-2 text-primary"></i>
            </div>
            <div>
                <h5 class="mb-0 fw-bold">Laporan Wali Kelas</h5>
                <small class="text-muted">
                    Kelas: <strong><?= esc($classroom['grade_name'] . ' ' . $classroom['classroom_name']) ?></strong> 
                    &mdash; Wali Kelas: <strong><?= esc($teacher['name']) ?></strong>
                </small>
            </div>
        </div>
    </div>
</div>

<!-- Quick Stats Widgets & Today's Absences -->
<div class="row g-3 mb-4">
    <!-- Stat 1: Rata-rata Kehadiran Kelas -->
    <div class="col-12 col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="bg-success bg-opacity-10 p-3 rounded-3 text-success">
                    <i class="bi bi-graph-up-arrow fs-2"></i>
                </div>
                <div>
                    <small class="text-muted d-block text-uppercase fw-semibold" style="font-size: 11px; letter-spacing: 0.5px;">Rata-rata Kehadiran</small>
                    <h3 class="mb-0 fw-bold text-success" id="stat-avg-attendance">-</h3>
                    <small class="text-muted" style="font-size: 11px;">Bulan terpilih</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Stat 2: Hari Efektif Belajar -->
    <div class="col-12 col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="bg-primary bg-opacity-10 p-3 rounded-3 text-primary">
                    <i class="bi bi-calendar-check fs-2"></i>
                </div>
                <div>
                    <small class="text-muted d-block text-uppercase fw-semibold" style="font-size: 11px; letter-spacing: 0.5px;">Hari Efektif Belajar</small>
                    <h3 class="mb-0 fw-bold text-primary" id="stat-active-days">-</h3>
                    <small class="text-muted" style="font-size: 11px;">Bulan terpilih</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Stat 3: Absen Hari Ini -->
    <div class="col-12 col-md-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="bg-danger bg-opacity-10 p-3 rounded-3 text-danger">
                    <i class="bi bi-person-x fs-2"></i>
                </div>
                <div>
                    <small class="text-muted d-block text-uppercase fw-semibold" style="font-size: 11px; letter-spacing: 0.5px;">Tidak Masuk Hari Ini</small>
                    <h3 class="mb-0 fw-bold text-danger"><?= count($todayAbsences) ?> Siswa</h3>
                    <small class="text-muted" style="font-size: 11px;">Tanggal: <?= format_tanggal_indonesia(date('Y-m-d')) ?></small>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <!-- Today's Absences List -->
    <div class="col-12 col-lg-5">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white border-0 py-3 d-flex align-items-center gap-2">
                <i class="bi bi-clock-history text-danger"></i>
                <h6 class="mb-0 fw-bold text-dark">Daftar Absen Hari Ini</h6>
            </div>
            <div class="card-body p-0" style="max-height: 280px; overflow-y: auto;">
                <?php if (empty($todayAbsences)): ?>
                    <div class="text-center py-5 text-muted">
                        <i class="bi bi-check-circle-fill text-success fs-2 d-block mb-2"></i>
                        <span class="small fw-medium">Semua siswa hadir hari ini</span>
                    </div>
                <?php else: ?>
                    <div class="list-group list-group-flush">
                        <?php foreach ($todayAbsences as $abs): ?>
                            <?php
                            $badgeClass = 'bg-secondary';
                            if ($abs['status'] === 'Sakit') $badgeClass = 'bg-info text-white';
                            elseif ($abs['status'] === 'Izin') $badgeClass = 'bg-warning text-dark';
                            elseif ($abs['status'] === 'Alpha') $badgeClass = 'bg-danger text-white';
                            ?>
                            <div class="list-group-item d-flex align-items-center justify-content-between py-2 px-3">
                                <div>
                                    <div class="fw-semibold text-dark small mb-0"><?= esc($abs['full_name']) ?></div>
                                    <small class="text-muted" style="font-size: 11px;">NIS: <?= esc($abs['nis']) ?></small>
                                </div>
                                <span class="badge <?= $badgeClass ?> rounded-pill px-3 py-1 fw-bold" style="font-size: 10px;">
                                    <?= esc($abs['status']) ?>
                                </span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Warnings: Attention Needed -->
    <div class="col-12 col-lg-7">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white border-0 py-3 d-flex align-items-center gap-2">
                <i class="bi bi-exclamation-triangle-fill text-warning"></i>
                <h6 class="mb-0 fw-bold text-dark">Siswa Perlu Perhatian Khusus</h6>
            </div>
            <div class="card-body p-0" style="max-height: 280px; overflow-y: auto;">
                <div id="attention-list-container">
                    <!-- Loaded dynamically via AJAX -->
                    <div class="text-center py-5 text-muted">
                        <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                        <span class="ms-2 small">Memuat data peringatan...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Main Monthly Attendance Table -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-white border-0 py-3 d-flex flex-wrap align-items-center justify-content-between gap-3">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-table text-primary"></i>
            <h6 class="mb-0 fw-bold text-dark">Rekapitulasi Kehadiran Bulanan</h6>
        </div>
        
        <div class="d-flex align-items-center gap-2">
            <!-- Dropdowns for filter -->
            <select class="form-select form-select-sm" id="filter-month" style="width: 140px;">
                <?php foreach ($months as $key => $name): ?>
                    <option value="<?= $key ?>" <?= $key == $defaultMonth ? 'selected' : '' ?>><?= $name ?></option>
                <?php endforeach; ?>
            </select>
            <select class="form-select form-select-sm" id="filter-year" style="width: 100px;">
                <?php foreach ($years as $yr): ?>
                    <option value="<?= $yr ?>" <?= $yr == $defaultYear ? 'selected' : '' ?>><?= $yr ?></option>
                <?php endforeach; ?>
            </select>
            
            <!-- Export / Print button -->
            <a href="#" id="btn-export" target="_blank" class="btn btn-sm btn-outline-primary d-flex align-items-center gap-1 shadow-xs">
                <i class="bi bi-printer-fill"></i> Cetak Laporan
            </a>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-bordered table-hover table-striped mb-0 align-middle" id="recap-table" style="min-width: 1000px; font-size: 12px;">
                <thead class="table-light">
                    <tr id="recap-thead-row">
                        <!-- Loaded dynamically via JS -->
                    </tr>
                </thead>
                <tbody id="recap-tbody">
                    <!-- Loaded dynamically via AJAX -->
                    <tr>
                        <td class="text-center py-5 text-muted">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2 mb-0 small">Memproses data kehadiran siswa...</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const monthSelect = document.getElementById('filter-month');
    const yearSelect = document.getElementById('filter-year');
    const btnExport = document.getElementById('btn-export');
    const recapTbody = document.getElementById('recap-tbody');
    const attentionContainer = document.getElementById('attention-list-container');
    const statAvgAttendance = document.getElementById('stat-avg-attendance');
    const statActiveDays = document.getElementById('stat-active-days');

    function updateExportLink() {
        const month = monthSelect.value;
        const year = yearSelect.value;
        btnExport.setAttribute('href', `<?= base_url('guru/presensi-kelas/export-pdf') ?>?month=${month}&year=${year}`);
    }

    function loadRekapData() {
        const month = monthSelect.value;
        const year = yearSelect.value;
        
        // Update URL print button immediately
        updateExportLink();

        // Show loading state
        recapTbody.innerHTML = `
            <tr>
                <td colspan="15" class="text-center py-5 text-muted">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 mb-0 small">Memproses data kehadiran siswa...</p>
                </td>
            </tr>
        `;
        
        attentionContainer.innerHTML = `
            <div class="text-center py-5 text-muted">
                <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                <span class="ms-2 small">Memuat data peringatan...</span>
            </div>
        `;

        fetch(`<?= base_url('guru/presensi-kelas/rekap') ?>?month=${month}&year=${year}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Gagal mengambil data dari server.');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // Update stats
                    statAvgAttendance.textContent = data.average_rate;
                    statActiveDays.textContent = data.active_days + ' Hari';

                    // Update recap table headers
                    let headHtml = `
                        <th class="text-center" style="width: 40px; min-width: 40px;">No</th>
                        <th style="width: 90px; min-width: 90px;">NIS</th>
                        <th style="min-width: 150px;">Nama Siswa</th>
                        <th class="text-center" style="width: 40px; min-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; min-width: 35px;">S</th>
                        <th class="text-center text-warning" style="width: 35px; min-width: 35px;">I</th>
                        <th class="text-center text-danger" style="width: 35px; min-width: 35px;">A</th>
                        <th class="text-center fw-bold" style="width: 50px; min-width: 50px;">%</th>
                    `;
                    document.getElementById('recap-thead-row').innerHTML = headHtml;

                    // Update recap table rows
                    if (data.recap.length === 0) {
                        recapTbody.innerHTML = `
                            <tr>
                                <td colspan="${data.days.length + 8}" class="text-center py-4 text-muted">
                                    Tidak ada data siswa aktif di kelas ini.
                                </td>
                            </tr>
                        `;
                    } else {
                        let rowsHtml = '';
                        data.recap.forEach((row, index) => {
                            let percentageClass = 'text-success';
                            if (row.attendance_rate < 85) percentageClass = 'text-danger fw-bold';
                            else if (row.attendance_rate < 95) percentageClass = 'text-warning fw-bold';

                            let colsHtml = '';
                            data.days.forEach(day => {
                                let status = row.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>`;
                            });

                            rowsHtml += `
                                <tr>
                                    <td class="text-center text-muted small">${index + 1}</td>
                                    <td><code>${row.nis}</code></td>
                                    <td class="fw-semibold text-dark text-truncate" style="max-width: 150px;" title="${row.full_name}">${row.full_name}</td>
                                    <td class="text-center"><span class="badge bg-light text-dark" style="font-size: 10px;">${row.gender}</span></td>
                                    ${colsHtml}
                                    <td class="text-center text-info font-monospace fw-bold" style="font-size: 11px;">${row.sakit || '-'}</td>
                                    <td class="text-center text-warning font-monospace fw-bold" style="font-size: 11px;">${row.izin || '-'}</td>
                                    <td class="text-center text-danger font-monospace fw-bold" style="font-size: 11px;">${row.alpha || '-'}</td>
                                    <td class="text-center font-monospace ${percentageClass}" style="font-size: 11px;">${row.attendance_rate}%</td>
                                </tr>
                            `;
                        });
                        recapTbody.innerHTML = rowsHtml;
                        
                        // Initialize tooltips if any
                        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
                        tooltipTriggerList.map(function (tooltipTriggerEl) {
                            return new bootstrap.Tooltip(tooltipTriggerEl);
                        });
                    }

                    // Update attention list
                    if (data.attention_required.length === 0) {
                        attentionContainer.innerHTML = `
                            <div class="text-center py-5 text-muted">
                                <i class="bi bi-shield-fill-check text-success fs-1 d-block mb-2"></i>
                                <span class="small fw-medium">Semua siswa memiliki rekam kehadiran yang baik bulan ini.</span>
                            </div>
                        `;
                    } else {
                        let listHtml = '<div class="list-group list-group-flush">';
                        data.attention_required.forEach(item => {
                            listHtml += `
                                <div class="list-group-item d-flex align-items-center justify-content-between py-2 px-3" style="background-color: #fffbeb;">
                                    <div>
                                        <div class="fw-bold text-dark small mb-0">${item.full_name}</div>
                                        <small class="text-muted" style="font-size: 11px;">NIS: ${item.nis} &mdash; <span class="text-danger fw-semibold">${item.reason}</span></small>
                                    </div>
                                    <div class="d-flex gap-1">
                                        ${item.sakit > 0 ? `<span class="badge bg-info text-white rounded-pill px-2 py-0.5" style="font-size: 9px;">S: ${item.sakit}</span>` : ''}
                                        ${item.izin > 0 ? `<span class="badge bg-warning text-dark rounded-pill px-2 py-0.5" style="font-size: 9px;">I: ${item.izin}</span>` : ''}
                                        ${item.alpha > 0 ? `<span class="badge bg-danger text-white rounded-pill px-2 py-0.5" style="font-size: 9px;">A: ${item.alpha}</span>` : ''}
                                    </div>
                                </div>
                            `;
                        });
                        listHtml += '</div>';
                        attentionContainer.innerHTML = listHtml;
                    }
                } else {
                    recapTbody.innerHTML = `
                        <tr>
                            <td colspan="15" class="text-center py-4 text-danger">
                                ${data.message || 'Gagal memuat data.'}
                            </td>
                        </tr>
                    `;
                }
            })
            .catch(error => {
                console.error(error);
                recapTbody.innerHTML = `
                    <tr>
                        <td colspan="15" class="text-center py-4 text-danger">
                            Terjadi kesalahan jaringan atau server.
                        </td>
                    </tr>
                `;
                attentionContainer.innerHTML = `
                    <div class="text-center py-4 text-danger small">
                        Terjadi kesalahan jaringan.
                    </div>
                `;
            });
    }

    // Bind event listeners
    monthSelect.addEventListener('change', loadRekapData);
    yearSelect.addEventListener('change', loadRekapData);

    // Initial load
    loadRekapData();
});
</script>

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