<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: index.php'); exit; }
require_once 'config.php';
requireModule('attendance');
$conn = getDBConnection();
$allowed = ['admin','headteacher','director','registrar','supervisor','teacher','tutor'];
if (!in_array($_SESSION['role'] ?? '', $allowed)) {
    header('Location: dashboard.php?error=access_denied'); exit;
}
$current_year = getAcademicYear();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Attendance — EduTrack</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<style>
.status-btn-group .btn { min-width: 80px; font-size: .8rem; }
.register-row td { vertical-align: middle; }
.cal-grid { display: grid; grid-template-columns: repeat(7,1fr); gap: 4px; }
.cal-cell { aspect-ratio: 1; display: flex; align-items: center; justify-content: center;
            border-radius: 6px; font-size: .75rem; font-weight: 600; cursor: default; }
.cal-cell.present { background: #d1fae5; color: #065f46; }
.cal-cell.absent  { background: #fee2e2; color: #991b1b; }
.cal-cell.mixed   { background: #fef3c7; color: #92400e; }
.cal-cell.empty   { background: #f1f5f9; color: #94a3b8; }
.cal-cell.header  { background: transparent; font-size: .7rem; font-weight: 700;
                    color: #64748b; aspect-ratio: unset; padding: 4px 0; }
.stat-pill { display:inline-flex; align-items:center; gap: 6px; padding: 4px 12px;
             border-radius: 20px; font-size: .8rem; font-weight: 600; }
</style>
</head>
<body>
<div class="wrapper">
  <nav id="sidebar" class="sidebar">
    <?php if (!defined('EDUTRACK_MODULES')) require_once __DIR__ . '/module_definitions.php'; echo buildSidebar('attendance.php'); ?>
  </nav>
  <div class="main-content">
    <header class="header d-flex align-items-center justify-content-between">
      <div class="d-flex align-items-center gap-3">
        <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
        <div>
          <h4 class="mb-0">Attendance</h4>
          <nav aria-label="breadcrumb" class="d-none d-md-block">
            <ol class="breadcrumb mb-0 small">
              <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
              <li class="breadcrumb-item active">Attendance</li>
            </ol>
          </nav>
        </div>
      </div>
      <div class="d-flex gap-2">
        <span class="badge bg-success-subtle text-success py-2 px-3" id="todayBadge">
          <i class="fas fa-calendar-day me-1"></i>
          <?= date('l, d M Y') ?>
        </span>
      </div>
    </header>

    <main class="content">
      <ul class="nav nav-tabs mb-4" id="attendanceTabs" role="tablist">
        <li class="nav-item">
          <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tabRegister" type="button">
            <i class="fas fa-clipboard-check me-1"></i> Take Register
          </button>
        </li>
        <li class="nav-item">
          <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabRecords" type="button">
            <i class="fas fa-list me-1"></i> View Records
          </button>
        </li>
        <li class="nav-item">
          <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabReports" type="button">
            <i class="fas fa-chart-bar me-1"></i> Reports
          </button>
        </li>
        <li class="nav-item">
          <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabSMS" type="button">
            <i class="fas fa-sms me-1"></i> SMS Absentees
          </button>
        </li>
      </ul>

      <div class="tab-content">

        <!-- ═══ TAB 1: TAKE REGISTER ═══════════════════════════════════ -->
        <div class="tab-pane fade show active" id="tabRegister">
          <div class="card shadow-sm border-0 mb-4">
            <div class="card-body">
              <div class="row g-2 align-items-end mb-4">
                <div class="col-md-4">
                  <label class="form-label fw-semibold">Class</label>
                  <select id="regClass" class="form-select">
                    <option value="">— Select Class —</option>
                  </select>
                </div>
                <div class="col-md-3">
                  <label class="form-label fw-semibold">Date</label>
                  <input type="date" id="regDate" class="form-control" value="<?= date('Y-m-d') ?>"
                         max="<?= date('Y-m-d') ?>">
                </div>
                <div class="col-auto">
                  <button class="btn btn-outline-primary" onclick="loadRegister()">
                    <i class="fas fa-search me-1"></i> Load
                  </button>
                </div>
                <div class="col-auto ms-auto">
                  <div id="registerStatus" class="small text-muted"></div>
                </div>
              </div>

              <div id="registerArea" class="d-none">
                <div class="d-flex justify-content-between align-items-center mb-3">
                  <div>
                    <span class="me-3"><span class="stat-pill" style="background:#d1fae5;color:#065f46">
                      <i class="fas fa-check"></i> <span id="cntPresent">0</span> Present
                    </span></span>
                    <span class="me-3"><span class="stat-pill" style="background:#fee2e2;color:#991b1b">
                      <i class="fas fa-times"></i> <span id="cntAbsent">0</span> Absent
                    </span></span>
                    <span class="me-3"><span class="stat-pill" style="background:#fef3c7;color:#92400e">
                      <i class="fas fa-clock"></i> <span id="cntLate">0</span> Late
                    </span></span>
                    <span><span class="stat-pill" style="background:#ede9fe;color:#5b21b6">
                      <i class="fas fa-info-circle"></i> <span id="cntExcused">0</span> Excused
                    </span></span>
                  </div>
                  <div class="d-flex gap-2">
                    <button class="btn btn-sm btn-outline-secondary" onclick="markAll('present')">
                      <i class="fas fa-check-double me-1"></i>All Present
                    </button>
                    <button class="btn btn-sm btn-outline-secondary" onclick="markAll('absent')">
                      <i class="fas fa-times me-1"></i>All Absent
                    </button>
                  </div>
                </div>

                <div class="table-responsive">
                  <table class="table table-hover align-middle">
                    <thead class="table-light">
                      <tr>
                        <th>#</th>
                        <th>Student Name</th>
                        <th>ID</th>
                        <th>Status</th>
                        <th>Notes</th>
                      </tr>
                    </thead>
                    <tbody id="registerBody"></tbody>
                  </table>
                </div>

                <div class="d-flex justify-content-end mt-3 gap-2">
                  <button class="btn btn-success" onclick="saveRegister()">
                    <i class="fas fa-save me-1"></i> Save Register
                  </button>
                </div>
              </div>

              <div id="registerEmpty" class="text-center text-muted py-5">
                <i class="fas fa-clipboard fa-3x mb-3 d-block" style="opacity:.3"></i>
                Select a class and date to load the attendance register.
              </div>
            </div>
          </div>
        </div>

        <!-- ═══ TAB 2: VIEW RECORDS ══════════════════════════════════════ -->
        <div class="tab-pane fade" id="tabRecords">
          <div class="card shadow-sm border-0 mb-4">
            <div class="card-body">
              <div class="row g-2 align-items-end mb-3">
                <div class="col-md-3">
                  <label class="form-label fw-semibold">Class</label>
                  <select id="recClass" class="form-select">
                    <option value="">All Classes</option>
                  </select>
                </div>
                <div class="col-md-2">
                  <label class="form-label fw-semibold">From</label>
                  <input type="date" id="recFrom" class="form-control" value="<?= date('Y-m-01') ?>">
                </div>
                <div class="col-md-2">
                  <label class="form-label fw-semibold">To</label>
                  <input type="date" id="recTo" class="form-control" value="<?= date('Y-m-d') ?>">
                </div>
                <div class="col-md-2">
                  <label class="form-label fw-semibold">Status</label>
                  <select id="recStatus" class="form-select">
                    <option value="">All Statuses</option>
                    <option value="present">Present</option>
                    <option value="absent">Absent</option>
                    <option value="late">Late</option>
                    <option value="excused">Excused</option>
                  </select>
                </div>
                <div class="col-auto">
                  <button class="btn btn-outline-primary" onclick="loadRecords()">
                    <i class="fas fa-search me-1"></i> Search
                  </button>
                </div>
                <div class="col-auto ms-auto text-muted small" id="recCount"></div>
              </div>

              <div class="table-responsive">
                <table id="recordsTable" class="table table-hover align-middle">
                  <thead class="table-light">
                    <tr>
                      <th>#</th>
                      <th>Date</th>
                      <th>Student</th>
                      <th>Class</th>
                      <th>Status</th>
                      <th>Recorded By</th>
                      <th>Notes</th>
                    </tr>
                  </thead>
                  <tbody id="recordsBody">
                    <tr><td colspan="7" class="text-center text-muted py-4">Use filters above to view records.</td></tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>

        <!-- ═══ TAB 3: REPORTS ════════════════════════════════════════════ -->
        <div class="tab-pane fade" id="tabReports">
          <div class="card shadow-sm border-0 mb-4">
            <div class="card-body">
              <div class="row g-2 align-items-end mb-4">
                <div class="col-md-3">
                  <label class="form-label fw-semibold">Class (optional)</label>
                  <select id="rptClass" class="form-select">
                    <option value="">All Classes</option>
                  </select>
                </div>
                <div class="col-md-2">
                  <label class="form-label fw-semibold">From</label>
                  <input type="date" id="rptFrom" class="form-control" value="<?= date('Y-m-01') ?>">
                </div>
                <div class="col-md-2">
                  <label class="form-label fw-semibold">To</label>
                  <input type="date" id="rptTo" class="form-control" value="<?= date('Y-m-d') ?>">
                </div>
                <div class="col-auto">
                  <button class="btn btn-outline-primary" onclick="loadReport()">
                    <i class="fas fa-chart-bar me-1"></i> Generate
                  </button>
                </div>
              </div>

              <!-- Summary cards -->
              <div class="row g-3 mb-4" id="rptSummaryCards" style="display:none!important"></div>

              <!-- Table -->
              <div id="rptTableWrap">
                <div class="text-center text-muted py-5">
                  <i class="fas fa-chart-bar fa-3x mb-3 d-block" style="opacity:.3"></i>
                  Select filters and click Generate to view the attendance report.
                </div>
              </div>

              <!-- Calendar heatmap (shown for single-class view) -->
              <div id="rptCalendarWrap" class="mt-4" style="display:none"></div>
            </div>
          </div>
        </div>

        <!-- ═══ TAB 4: SMS ABSENTEES ══════════════════════════════════════ -->
        <div class="tab-pane fade" id="tabSMS">
          <div class="card shadow-sm border-0 mb-4">
            <div class="card-body">
              <p class="text-muted small mb-4">
                Select a class and date, preview absent students, then send SMS notifications to their parents.
              </p>
              <div class="row g-2 align-items-end mb-4">
                <div class="col-md-4">
                  <label class="form-label fw-semibold">Class</label>
                  <select id="smsClass" class="form-select">
                    <option value="">— Select Class —</option>
                  </select>
                </div>
                <div class="col-md-3">
                  <label class="form-label fw-semibold">Date</label>
                  <input type="date" id="smsDate" class="form-control" value="<?= date('Y-m-d') ?>"
                         max="<?= date('Y-m-d') ?>">
                </div>
                <div class="col-auto">
                  <button class="btn btn-outline-secondary" onclick="previewAbsentees()">
                    <i class="fas fa-eye me-1"></i> Preview
                  </button>
                </div>
              </div>

              <div id="smsPreviewArea" class="d-none">
                <div class="alert alert-info small">
                  <i class="fas fa-info-circle me-1"></i>
                  <strong><span id="smsAbsentCount">0</span> absent student(s)</strong> found.
                  SMS will be sent to linked parent accounts that have a phone number.
                </div>

                <div class="table-responsive mb-3">
                  <table class="table table-sm align-middle">
                    <thead class="table-light">
                      <tr><th>Student</th><th>ID</th><th>Parent Phone</th><th>Parent Name</th></tr>
                    </thead>
                    <tbody id="smsPreviewBody"></tbody>
                  </table>
                </div>

                <div class="mb-3">
                  <label class="form-label fw-semibold">Custom Message (optional)</label>
                  <textarea id="smsMessage" class="form-control" rows="3"
                    placeholder="Use {name} for student name, {class} for class, {date} for date. Leave blank for default message."></textarea>
                  <div class="form-text">Default: "Dear [Parent], your child [Student] was marked absent from [Class] on [Date]. Please contact the school if this is an error."</div>
                </div>

                <div class="d-flex gap-2 align-items-center">
                  <button class="btn btn-warning" onclick="sendSMSAbsentees()">
                    <i class="fas fa-paper-plane me-1"></i> Send SMS to Parents
                  </button>
                  <span id="smsResult" class="small text-muted"></span>
                </div>
              </div>

              <div id="smsEmpty" class="text-center text-muted py-5">
                <i class="fas fa-sms fa-3x mb-3 d-block" style="opacity:.3"></i>
                Select a class and date, then click Preview to see absent students.
              </div>
            </div>
          </div>
        </div>

      </div><!-- /tab-content -->
    </main>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>
<script src="js/main.js"></script>
<script>
const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));

// Teacher RBAC: restrict class dropdowns to assigned classes only
const TEACHER_CLASSES = <?= json_encode($_SESSION['teacher_classes'] ?? []) ?>;
const IS_TUTOR = <?= json_encode(($_SESSION['role'] ?? '') === 'tutor') ?>;

// ── STATUS BADGE ─────────────────────────────────────────────────────────────
function statusBadge(s) {
    const map = {
        present: 'bg-success-subtle text-success',
        absent:  'bg-danger-subtle text-danger',
        late:    'bg-warning-subtle text-warning',
        excused: 'bg-purple-subtle text-purple'
    };
    return `<span class="badge ${map[s] || 'bg-secondary-subtle text-secondary'}">${s}</span>`;
}

// ── LOAD CLASSES INTO ALL DROPDOWNS ─────────────────────────────────────────
async function loadClasses() {
    try {
        const res = await fetch('ajax/attendance.php?action=get_classes');
        let classes = await res.json();
        if (!Array.isArray(classes)) return;
        // Restrict to teacher's assigned classes if role = tutor
        if (IS_TUTOR && TEACHER_CLASSES.length > 0) {
            classes = classes.filter(c => TEACHER_CLASSES.includes(c));
        }
        ['regClass','recClass','rptClass','smsClass'].forEach(id => {
            const sel = document.getElementById(id);
            if (!sel) return;
            const all = sel.querySelector('option[value=""]');
            sel.innerHTML = '';
            if (all) sel.appendChild(all);
            classes.forEach(c => {
                const o = document.createElement('option');
                o.value = c; o.textContent = c;
                sel.appendChild(o);
            });
        });
    } catch (e) {
        console.error('loadClasses failed:', e);
    }
}

// ════════════════════════════════════════════════════════════════════════════
// TAB 1 — TAKE REGISTER
// ════════════════════════════════════════════════════════════════════════════
let registerStudents = [];

async function loadRegister() {
    const cls  = document.getElementById('regClass').value;
    const date = document.getElementById('regDate').value;
    if (!cls || !date) { alert('Please select a class and date.'); return; }

    const btn = document.querySelector('[onclick="loadRegister()"]');
    const emptyEl = document.getElementById('registerEmpty');
    if (btn) { btn.disabled = true; btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Loading…'; }

    try {
        const res = await fetch(`ajax/attendance.php?action=get_students&class=${encodeURIComponent(cls)}&date=${encodeURIComponent(date)}`);
        if (!res.ok) throw new Error(`Server error: ${res.status}`);
        const data = await res.json();
        if (!Array.isArray(data)) throw new Error('Unexpected response from server.');
        registerStudents = data;

        if (registerStudents.length === 0) {
            document.getElementById('registerArea').classList.add('d-none');
            emptyEl.classList.remove('d-none');
            emptyEl.innerHTML = '<i class="fas fa-users fa-3x mb-3 d-block" style="opacity:.3"></i>No active students found in this class.';
            return;
        }

        // Check if already submitted today
        const chk  = await fetch(`ajax/attendance.php?action=get_register&class=${encodeURIComponent(cls)}&date=${encodeURIComponent(date)}`);
        const saved = chk.ok ? await chk.json() : { submitted: false, records: [] };
        const statusEl = document.getElementById('registerStatus');
        if (saved.submitted) {
            statusEl.innerHTML = '<span class="badge bg-success"><i class="fas fa-check me-1"></i>Already submitted — editing</span>';
        } else {
            statusEl.innerHTML = '<span class="badge bg-secondary">Not yet submitted</span>';
        }

        // Pre-populate from saved data if exists
        if (saved.records && saved.records.length) {
            const map = {};
            saved.records.forEach(r => { map[r.student_id] = r; });
            registerStudents.forEach(s => {
                if (map[s.id]) { s.today_status = map[s.id].status; s.today_notes = map[s.id].notes; }
            });
        }

        renderRegister();
        document.getElementById('registerArea').classList.remove('d-none');
        emptyEl.classList.add('d-none');

    } catch (err) {
        emptyEl.classList.remove('d-none');
        emptyEl.innerHTML = `<i class="fas fa-exclamation-circle fa-2x mb-2 d-block text-danger"></i><span class="text-danger">Failed to load register: ${err.message}</span>`;
        document.getElementById('registerArea').classList.add('d-none');
    } finally {
        if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-search me-1"></i> Load'; }
    }
}

function renderRegister() {
    const tbody = document.getElementById('registerBody');
    const statuses = ['present','absent','late','excused'];
    const colors = { present:'success', absent:'danger', late:'warning', excused:'secondary' };

    tbody.innerHTML = registerStudents.map((s, i) => {
        const cur = s.today_status || 'present';
        const btns = statuses.map(st => {
            const active = cur === st ? 'active' : '';
            return `<button type="button" class="btn btn-sm btn-outline-${colors[st]} ${active}"
                    onclick="setStatus(${i}, '${st}')">${st.charAt(0).toUpperCase() + st.slice(1)}</button>`;
        }).join('');
        return `<tr class="register-row" id="row-${i}">
          <td>${i + 1}</td>
          <td><strong>${esc(s.full_name)}</strong></td>
          <td class="text-muted small">${esc(s.student_id_number || '—')}</td>
          <td><div class="btn-group status-btn-group" role="group">${btns}</div></td>
          <td><input type="text" class="form-control form-control-sm" id="notes-${i}"
               value="${esc(s.today_notes || '')}" placeholder="Optional note" style="max-width:180px"></td>
        </tr>`;
    }).join('');
    updateCounts();
}

function setStatus(idx, status) {
    registerStudents[idx].today_status = status;
    // Update buttons in that row
    const row = document.getElementById(`row-${idx}`);
    const colors = { present:'success', absent:'danger', late:'warning', excused:'secondary' };
    row.querySelectorAll('.status-btn-group .btn').forEach(btn => {
        const btnStatus = btn.textContent.trim().toLowerCase();
        btn.classList.toggle('active', btnStatus === status);
    });
    updateCounts();
}

function markAll(status) {
    registerStudents.forEach((_, i) => setStatus(i, status));
}

function updateCounts() {
    const counts = { present:0, absent:0, late:0, excused:0 };
    registerStudents.forEach(s => { counts[s.today_status || 'present']++; });
    document.getElementById('cntPresent').textContent = counts.present;
    document.getElementById('cntAbsent').textContent  = counts.absent;
    document.getElementById('cntLate').textContent    = counts.late;
    document.getElementById('cntExcused').textContent = counts.excused;
}

async function saveRegister() {
    const cls  = document.getElementById('regClass').value;
    const date = document.getElementById('regDate').value;
    const records = registerStudents.map((s, i) => ({
        id:     s.id,
        status: s.today_status || 'present',
        notes:  (document.getElementById(`notes-${i}`)?.value || '').trim()
    }));

    const body = new URLSearchParams({ action: 'save_register', class: cls, date });
    records.forEach((r, i) => {
        body.append(`records[${i}][id]`, r.id);
        body.append(`records[${i}][status]`, r.status);
        body.append(`records[${i}][notes]`, r.notes);
    });

    const res  = await fetch('ajax/attendance.php', { method: 'POST', body });
    const data = await res.json();
    if (data.success) {
        document.getElementById('registerStatus').innerHTML =
            '<span class="badge bg-success"><i class="fas fa-check me-1"></i>Saved successfully</span>';
        showToast(data.message, 'success');
    } else {
        alert(data.message);
    }
}

function showToast(msg, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type} position-fixed bottom-0 end-0 m-3 shadow`;
    toast.style.cssText = 'z-index:9999;min-width:280px;animation:fadeIn .3s';
    toast.innerHTML = `<i class="fas fa-${type === 'success' ? 'check' : 'exclamation'}-circle me-2"></i>${msg}`;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3500);
}

// ════════════════════════════════════════════════════════════════════════════
// TAB 2 — VIEW RECORDS
// ════════════════════════════════════════════════════════════════════════════
let dtRecords = null;

async function loadRecords() {
    const cls    = document.getElementById('recClass').value;
    const from   = document.getElementById('recFrom').value;
    const to     = document.getElementById('recTo').value;
    const status = document.getElementById('recStatus').value;

    const params = new URLSearchParams({ action: 'get_records', class: cls, from, to, status });
    let rows;
    try {
        const res = await fetch('ajax/attendance.php?' + params);
        if (!res.ok) throw new Error(`Server error: ${res.status}`);
        rows = await res.json();
        if (!Array.isArray(rows)) throw new Error('Unexpected server response.');
    } catch (err) {
        document.getElementById('recordsBody').innerHTML =
            `<tr><td colspan="7" class="text-center text-danger py-4"><i class="fas fa-exclamation-circle me-1"></i>Failed to load records: ${err.message}</td></tr>`;
        return;
    }

    document.getElementById('recCount').textContent = rows.length + ' record(s)';

    const tbody = document.getElementById('recordsBody');
    if (rows.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted py-4">No records found for the selected filters.</td></tr>';
        if (dtRecords) { dtRecords.destroy(); dtRecords = null; }
        return;
    }

    tbody.innerHTML = rows.map((r, i) => `
      <tr>
        <td>${i + 1}</td>
        <td>${esc(r.attendance_date)}</td>
        <td><strong>${esc(r.full_name)}</strong><br><small class="text-muted">${esc(r.student_id_number || '')}</small></td>
        <td>${esc(r.class_name)}</td>
        <td>${statusBadge(r.status)}</td>
        <td class="small text-muted">${esc(r.recorded_by_name || '—')}</td>
        <td class="small">${esc(r.notes || '')}</td>
      </tr>`).join('');

    if (dtRecords) { dtRecords.destroy(); dtRecords = null; }
    dtRecords = $('#recordsTable').DataTable({
        pageLength: 25, order: [[1, 'desc']],
        columnDefs: [{ orderable: false, targets: [] }]
    });
}

// ════════════════════════════════════════════════════════════════════════════
// TAB 3 — REPORTS
// ════════════════════════════════════════════════════════════════════════════
async function loadReport() {
    const cls  = document.getElementById('rptClass').value;
    const from = document.getElementById('rptFrom').value;
    const to   = document.getElementById('rptTo').value;

    const params = new URLSearchParams({ action: 'get_report', class: cls, from, to });
    let data;
    try {
        const res = await fetch('ajax/attendance.php?' + params);
        if (!res.ok) throw new Error(`Server error: ${res.status}`);
        data = await res.json();
    } catch (err) {
        document.getElementById('rptTableWrap').innerHTML =
            `<div class="text-center text-danger py-4"><i class="fas fa-exclamation-circle me-1"></i>Failed to load report: ${err.message}</div>`;
        return;
    }

    const wrap  = document.getElementById('rptTableWrap');
    const calWrap = document.getElementById('rptCalendarWrap');
    calWrap.style.display = 'none';

    if (data.type === 'all_classes') {
        if (!data.rows || data.rows.length === 0) {
            wrap.innerHTML = '<div class="text-center text-muted py-4">No attendance data found for this period.</div>';
            return;
        }
        let totalPresent = 0, totalAbsent = 0, totalLate = 0, totalExcused = 0;
        data.rows.forEach(r => {
            totalPresent += parseInt(r.present_count); totalAbsent  += parseInt(r.absent_count);
            totalLate    += parseInt(r.late_count);    totalExcused += parseInt(r.excused_count);
        });
        const totalAll = totalPresent + totalAbsent + totalLate + totalExcused;
        const pct = totalAll > 0 ? Math.round(totalPresent / totalAll * 100) : 0;

        document.getElementById('rptSummaryCards').style.removeProperty('display');
        document.getElementById('rptSummaryCards').innerHTML = `
          <div class="col-6 col-md-3"><div class="card border-0 bg-success-subtle text-center p-3">
            <div class="fs-2 fw-bold text-success">${totalPresent}</div>
            <div class="small text-muted">Total Present</div>
          </div></div>
          <div class="col-6 col-md-3"><div class="card border-0 bg-danger-subtle text-center p-3">
            <div class="fs-2 fw-bold text-danger">${totalAbsent}</div>
            <div class="small text-muted">Total Absent</div>
          </div></div>
          <div class="col-6 col-md-3"><div class="card border-0 bg-warning-subtle text-center p-3">
            <div class="fs-2 fw-bold text-warning">${totalLate}</div>
            <div class="small text-muted">Total Late</div>
          </div></div>
          <div class="col-6 col-md-3"><div class="card border-0 bg-primary-subtle text-center p-3">
            <div class="fs-2 fw-bold text-primary">${pct}%</div>
            <div class="small text-muted">Attendance Rate</div>
          </div></div>`;

        wrap.innerHTML = `
          <table class="table table-hover align-middle">
            <thead class="table-light"><tr>
              <th>#</th><th>Class</th><th>School Days</th><th>Students</th>
              <th>Present</th><th>Absent</th><th>Late</th><th>Rate</th>
            </tr></thead>
            <tbody>${data.rows.map((r, i) => {
                const total = parseInt(r.present_count) + parseInt(r.absent_count) + parseInt(r.late_count) + parseInt(r.excused_count);
                const rate  = total > 0 ? Math.round(parseInt(r.present_count) / total * 100) : 0;
                const bar   = `<div class="progress" style="height:6px"><div class="progress-bar bg-${rate>=80?'success':rate>=60?'warning':'danger'}" style="width:${rate}%"></div></div>`;
                return `<tr>
                  <td>${i+1}</td>
                  <td><strong>${esc(r.class_name)}</strong></td>
                  <td>${esc(r.school_days)}</td>
                  <td>${esc(r.total_students)}</td>
                  <td><span class="badge bg-success-subtle text-success">${r.present_count}</span></td>
                  <td><span class="badge bg-danger-subtle text-danger">${r.absent_count}</span></td>
                  <td><span class="badge bg-warning-subtle text-warning">${r.late_count}</span></td>
                  <td><div>${rate}%</div>${bar}</td>
                </tr>`;
            }).join('')}</tbody>
          </table>`;

    } else {
        // Single class — per-student table + calendar heatmap
        if (!data.rows || data.rows.length === 0) {
            wrap.innerHTML = '<div class="text-center text-muted py-4">No attendance data found.</div>';
            return;
        }
        document.getElementById('rptSummaryCards').style.removeProperty('display');

        let tp = 0, ta = 0, tl = 0, te = 0;
        data.rows.forEach(r => { tp += parseInt(r.present_count); ta += parseInt(r.absent_count); tl += parseInt(r.late_count); te += parseInt(r.excused_count); });
        const total = tp + ta + tl + te;
        const pct = total > 0 ? Math.round(tp / total * 100) : 0;

        document.getElementById('rptSummaryCards').innerHTML = `
          <div class="col-6 col-md-3"><div class="card border-0 bg-success-subtle text-center p-3">
            <div class="fs-2 fw-bold text-success">${tp}</div><div class="small text-muted">Present</div>
          </div></div>
          <div class="col-6 col-md-3"><div class="card border-0 bg-danger-subtle text-center p-3">
            <div class="fs-2 fw-bold text-danger">${ta}</div><div class="small text-muted">Absent</div>
          </div></div>
          <div class="col-6 col-md-3"><div class="card border-0 bg-warning-subtle text-center p-3">
            <div class="fs-2 fw-bold text-warning">${tl}</div><div class="small text-muted">Late</div>
          </div></div>
          <div class="col-6 col-md-3"><div class="card border-0 bg-primary-subtle text-center p-3">
            <div class="fs-2 fw-bold text-primary">${pct}%</div><div class="small text-muted">Attendance Rate</div>
          </div></div>`;

        wrap.innerHTML = `
          <h6 class="fw-semibold mb-2">Per-Student Breakdown — ${esc(data.class)}</h6>
          <div class="table-responsive">
          <table class="table table-hover table-sm align-middle">
            <thead class="table-light"><tr>
              <th>#</th><th>Student</th><th>ID</th><th>Present</th><th>Absent</th><th>Late</th><th>Excused</th><th>Rate</th>
            </tr></thead>
            <tbody>${data.rows.map((r, i) => {
                const tot = parseInt(r.present_count) + parseInt(r.absent_count) + parseInt(r.late_count) + parseInt(r.excused_count);
                const rt  = tot > 0 ? Math.round(parseInt(r.present_count) / tot * 100) : 0;
                return `<tr>
                  <td>${i+1}</td>
                  <td><strong>${esc(r.full_name)}</strong></td>
                  <td class="text-muted small">${esc(r.student_id_number || '—')}</td>
                  <td><span class="badge bg-success-subtle text-success">${r.present_count}</span></td>
                  <td><span class="badge bg-danger-subtle text-danger">${r.absent_count}</span></td>
                  <td><span class="badge bg-warning-subtle text-warning">${r.late_count}</span></td>
                  <td><span class="badge bg-secondary-subtle text-secondary">${r.excused_count}</span></td>
                  <td>
                    <div class="d-flex align-items-center gap-2">
                      <span class="fw-semibold ${rt>=80?'text-success':rt>=60?'text-warning':'text-danger'}">${rt}%</span>
                      <div class="progress flex-grow-1" style="height:6px">
                        <div class="progress-bar bg-${rt>=80?'success':rt>=60?'warning':'danger'}" style="width:${rt}%"></div>
                      </div>
                    </div>
                  </td>
                </tr>`;
            }).join('')}</tbody>
          </table></div>`;

        // Calendar heatmap
        if (data.calendar && data.calendar.length > 0) {
            renderCalendar(data.calendar, calWrap, data.from, data.to);
            calWrap.style.display = '';
        }
    }
}

function renderCalendar(calData, container, from, to) {
    const map = {};
    calData.forEach(d => { map[d.attendance_date] = d; });

    const fromD = new Date(from); fromD.setDate(1);
    const toD   = new Date(to);
    const days  = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];

    let html = `<h6 class="fw-semibold mb-3">Monthly Calendar Heatmap</h6>`;
    let cur = new Date(fromD.getFullYear(), fromD.getMonth(), 1);

    while (cur <= toD) {
        const yr = cur.getFullYear(), mo = cur.getMonth();
        const monthName = cur.toLocaleString('default', {month:'long', year:'numeric'});
        html += `<div class="mb-4"><div class="fw-semibold mb-2">${monthName}</div>
                 <div class="cal-grid">${days.map(d => `<div class="cal-cell header">${d}</div>`).join('')}`;

        const firstDay = new Date(yr, mo, 1).getDay();
        for (let i = 0; i < firstDay; i++) html += '<div></div>';

        const daysInMonth = new Date(yr, mo + 1, 0).getDate();
        for (let d = 1; d <= daysInMonth; d++) {
            const dateStr = `${yr}-${String(mo+1).padStart(2,'0')}-${String(d).padStart(2,'0')}`;
            const rec = map[dateStr];
            let cls = 'empty', title = dateStr;
            if (rec) {
                const p = parseInt(rec.present_count), a = parseInt(rec.absent_count);
                cls = a === 0 ? 'present' : p === 0 ? 'absent' : 'mixed';
                title = `P:${p} A:${a} L:${rec.late_count}`;
            }
            html += `<div class="cal-cell ${cls}" title="${dateStr}: ${title}">${d}</div>`;
        }
        html += '</div></div>';
        cur = new Date(yr, mo + 1, 1);
    }

    container.innerHTML = html;
}

// ════════════════════════════════════════════════════════════════════════════
// TAB 4 — SMS ABSENTEES
// ════════════════════════════════════════════════════════════════════════════
async function previewAbsentees() {
    const cls  = document.getElementById('smsClass').value;
    const date = document.getElementById('smsDate').value;
    if (!cls || !date) { alert('Please select a class and date.'); return; }

    const res  = await fetch(`ajax/attendance.php?action=get_absentees&class=${encodeURIComponent(cls)}&date=${encodeURIComponent(date)}`);
    const rows = await res.json();

    document.getElementById('smsAbsentCount').textContent = rows.length;
    const tbody = document.getElementById('smsPreviewBody');

    if (rows.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" class="text-center text-muted py-3">No absent students found.</td></tr>';
    } else {
        tbody.innerHTML = rows.map(r => `
          <tr>
            <td>${esc(r.full_name)}</td>
            <td class="text-muted small">${esc(r.student_id_number || '—')}</td>
            <td>${r.parent_phone ? esc(r.parent_phone) : '<span class="text-danger">No phone</span>'}</td>
            <td>${esc(r.parent_name || '—')}</td>
          </tr>`).join('');
    }

    document.getElementById('smsPreviewArea').classList.remove('d-none');
    document.getElementById('smsEmpty').classList.add('d-none');
}

async function sendSMSAbsentees() {
    const cls  = document.getElementById('smsClass').value;
    const date = document.getElementById('smsDate').value;
    const msg  = document.getElementById('smsMessage').value;
    const res  = document.getElementById('smsResult');

    if (!cls || !date) { alert('Please select a class and date.'); return; }
    if (!confirm('Send SMS to all parents of absent students for this class on this date?')) return;

    res.textContent = 'Sending...';
    const body = new URLSearchParams({ action: 'sms_absentees', class: cls, date, message: msg });
    const r    = await fetch('ajax/attendance.php', { method: 'POST', body });
    const data = await r.json();

    if (data.success) {
        res.textContent = data.message;
        showToast(data.message, 'success');
    } else {
        res.textContent = data.message;
        alert(data.message);
    }
}

// ── INIT ─────────────────────────────────────────────────────────────────────
loadClasses();
</script>
</body>
</html>
