<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }
require_once '../config.php';
require_once '../includes/canteen_check.php';
require_once '../vendor/autoload.php';
use Dompdf\Dompdf;
use Dompdf\Options;
canteen_require_role(['admin', 'headteacher', 'accountant']);

$conn = getDBConnection();

// ── Filter params ─────────────────────────────────────────────────────────────
$report    = $_GET['report']    ?? 'daily_meal';
$date_from = $_GET['date_from'] ?? date('Y-m-d');
$date_to   = $_GET['date_to']   ?? date('Y-m-d');
$export    = $_GET['export']    ?? '';

// Clamp dates
if ($date_from > $date_to) { $tmp = $date_from; $date_from = $date_to; $date_to = $tmp; }

$settings = canteen_get_settings();

// ── Query runners ─────────────────────────────────────────────────────────────

function q_daily_meal($conn, $from, $to): array {
    $stmt = $conn->prepare(
        "SELECT cs.session_date, cs.session_name,
                cs.total_enrolled,
                COUNT(ce.id)                                              AS total_entitlements,
                SUM(ce.status = 'confirmed')                              AS confirmed,
                SUM(ce.status = 'absent')                                 AS absent,
                SUM(ce.status = 'pending')                                AS pending,
                cs.price_per_meal,
                SUM(ce.status = 'confirmed') * cs.price_per_meal          AS revenue,
                SUM(cscan.verification_method = 'qr')                     AS by_qr,
                SUM(cscan.verification_method = 'fingerprint')            AS by_fp,
                SUM(cscan.verification_method = 'facial')                 AS by_face,
                SUM(cscan.verification_method = 'manual_id')              AS by_manual
         FROM canteen_sessions cs
         LEFT JOIN canteen_entitlements ce ON ce.session_id = cs.id
         LEFT JOIN canteen_scans cscan
               ON cscan.session_id = cs.id AND cscan.scan_result = 'success'
         WHERE cs.school_id = 1
           AND cs.session_date BETWEEN ? AND ?
           AND cs.status != 'cancelled'
         GROUP BY cs.id
         ORDER BY cs.session_date ASC, cs.start_time ASC"
    );
    $stmt->bind_param('ss', $from, $to);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    return $rows;
}

function q_student_attendance($conn, $from, $to): array {
    $stmt = $conn->prepare(
        "SELECT s.id AS student_id,
                CONCAT(s.first_name,' ',s.last_name) AS student_name,
                s.class,
                s.student_id                                AS student_code,
                COUNT(ce.id)                                AS sessions_enrolled,
                SUM(ce.status = 'confirmed')                AS sessions_confirmed,
                SUM(ce.status = 'absent')                   AS sessions_absent,
                ROUND(SUM(ce.status = 'absent') / NULLIF(COUNT(ce.id),0) * 100, 1) AS absence_rate
         FROM students s
         JOIN canteen_entitlements ce ON ce.student_id = s.id
         JOIN canteen_sessions cs ON cs.id = ce.session_id
         WHERE cs.school_id = 1
           AND cs.session_date BETWEEN ? AND ?
           AND cs.status != 'cancelled'
         GROUP BY s.id
         ORDER BY absence_rate DESC, student_name ASC"
    );
    $stmt->bind_param('ss', $from, $to);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    // Calculate longest absence streak per student
    $streak_stmt = $conn->prepare(
        "SELECT ce.student_id, cs.session_date, ce.status
         FROM canteen_entitlements ce
         JOIN canteen_sessions cs ON cs.id = ce.session_id
         WHERE cs.school_id = 1
           AND cs.session_date BETWEEN ? AND ?
           AND cs.status != 'cancelled'
         ORDER BY ce.student_id, cs.session_date ASC"
    );
    $streak_stmt->bind_param('ss', $from, $to);
    $streak_stmt->execute();
    $all = $streak_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $streak_stmt->close();

    $streaks = [];
    $cur_id = null; $cur_streak = 0; $max_streak = 0;
    foreach ($all as $r) {
        if ($r['student_id'] !== $cur_id) {
            if ($cur_id !== null) $streaks[$cur_id] = $max_streak;
            $cur_id = $r['student_id']; $cur_streak = 0; $max_streak = 0;
        }
        if ($r['status'] === 'absent') { $cur_streak++; if ($cur_streak > $max_streak) $max_streak = $cur_streak; }
        else $cur_streak = 0;
    }
    if ($cur_id !== null) $streaks[$cur_id] = $max_streak;

    foreach ($rows as &$row) {
        $row['longest_streak'] = $streaks[$row['student_id']] ?? 0;
    }
    return $rows;
}

function q_financial_reconciliation($conn, $from, $to): array {
    // Payments for feeding/canteen fee types
    $stmt = $conn->prepare(
        "SELECT s.id AS student_id,
                CONCAT(s.first_name,' ',s.last_name) AS student_name,
                s.class,
                COUNT(DISTINCT p.id)                     AS payment_count,
                COALESCE(SUM(p.amount_paid), 0)          AS fees_collected,
                COUNT(DISTINCT ce.id)                    AS entitlements_created,
                SUM(ce.status = 'confirmed')             AS meals_confirmed,
                SUM(ce.status = 'absent')                AS meals_absent
         FROM students s
         JOIN payments p ON p.student_id = s.id
         JOIN fee_structures fs ON fs.id = p.fee_structure_id
         LEFT JOIN canteen_entitlements ce ON ce.fee_payment_id = p.id
         WHERE p.payment_date BETWEEN ? AND ?
           AND (fs.fee_type REGEXP 'feeding|canteen|meal')
         GROUP BY s.id
         ORDER BY fees_collected DESC"
    );
    $stmt->bind_param('ss', $from, $to);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    // Flag discrepancies: paid but no entitlement
    foreach ($rows as &$row) {
        $row['discrepancy'] = ($row['fees_collected'] > 0 && $row['entitlements_created'] == 0);
    }
    return $rows;
}

function q_express_stats($conn, $from, $to): array {
    $stmt = $conn->prepare(
        "SELECT fs.fee_type,
                s.class,
                COUNT(CASE WHEN p.recorded_via = 'express_scanner' THEN 1 END) AS express_count,
                COUNT(CASE WHEN p.recorded_via != 'express_scanner' OR p.recorded_via IS NULL THEN 1 END) AS standard_count,
                COUNT(p.id) AS total_count,
                COALESCE(SUM(CASE WHEN p.recorded_via = 'express_scanner' THEN p.amount_paid END), 0) AS express_revenue,
                COALESCE(SUM(p.amount_paid), 0) AS total_revenue
         FROM payments p
         JOIN students s ON s.id = p.student_id
         JOIN fee_structures fs ON fs.id = p.fee_structure_id
         WHERE p.payment_date BETWEEN ? AND ?
         GROUP BY fs.fee_type, s.class
         ORDER BY express_count DESC"
    );
    $stmt->bind_param('ss', $from, $to);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $totals = ['express_count' => 0, 'standard_count' => 0, 'total_count' => 0,
               'express_revenue' => 0, 'total_revenue' => 0];
    foreach ($rows as $r) {
        $totals['express_count']   += $r['express_count'];
        $totals['standard_count']  += $r['standard_count'];
        $totals['total_count']     += $r['total_count'];
        $totals['express_revenue'] += $r['express_revenue'];
        $totals['total_revenue']   += $r['total_revenue'];
    }
    return ['rows' => $rows, 'totals' => $totals];
}

function q_biometric_usage($conn, $from, $to): array {
    $stmt = $conn->prepare(
        "SELECT
            cscan.verification_method,
            COUNT(*)                                          AS total_scans,
            SUM(cscan.scan_result = 'success')               AS success_count,
            SUM(cscan.scan_result != 'success')              AS failure_count,
            ROUND(SUM(cscan.scan_result = 'success') / NULLIF(COUNT(*),0) * 100, 1) AS success_rate,
            ROUND(AVG(cscan.confidence_score), 3)            AS avg_confidence
         FROM canteen_scans cscan
         JOIN canteen_sessions cs ON cs.id = cscan.session_id
         WHERE cs.session_date BETWEEN ? AND ?
           AND cscan.verification_method IS NOT NULL
         GROUP BY cscan.verification_method
         ORDER BY total_scans DESC"
    );
    $stmt->bind_param('ss', $from, $to);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    return $rows;
}

// ── Load report data ──────────────────────────────────────────────────────────
$data = [];
$express_totals = [];

switch ($report) {
    case 'daily_meal':
        $data = q_daily_meal($conn, $date_from, $date_to);
        break;
    case 'student_attendance':
        $data = q_student_attendance($conn, $date_from, $date_to);
        break;
    case 'financial_reconciliation':
        $data = q_financial_reconciliation($conn, $date_from, $date_to);
        break;
    case 'express_stats':
        $result = q_express_stats($conn, $date_from, $date_to);
        $data = $result['rows'];
        $express_totals = $result['totals'];
        break;
    case 'biometric_usage':
        $data = q_biometric_usage($conn, $date_from, $date_to);
        break;
}

// ── School info ───────────────────────────────────────────────────────────────
$school = [];
$sRes = $conn->query("SELECT setting_key, setting_value FROM settings
                      WHERE setting_key IN ('school_name','school_address','school_phone')");
while ($row = $sRes->fetch_assoc()) $school[$row['setting_key']] = $row['setting_value'];
$school_name = $school['school_name'] ?? 'School';

$conn->close();

// ── Report metadata ───────────────────────────────────────────────────────────
$report_titles = [
    'daily_meal'               => 'Daily Meal Report',
    'student_attendance'       => 'Student Meal Attendance',
    'financial_reconciliation' => 'Financial Reconciliation',
    'express_stats'            => 'Express Collection Statistics',
    'biometric_usage'          => 'Biometric Usage Report',
];
$report_title = $report_titles[$report] ?? 'Canteen Report';

// ── CSV Export ────────────────────────────────────────────────────────────────
if ($export === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="canteen_' . $report . '_' . $date_from . '_' . $date_to . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['EduTrack — ' . $report_title]);
    fputcsv($out, ['School:', $school_name, 'Period:', $date_from . ' to ' . $date_to]);
    fputcsv($out, []);

    switch ($report) {
        case 'daily_meal':
            fputcsv($out, ['Date','Session','Enrolled','Confirmed','Absent','Pending','Revenue (GHS)','By QR','By Fingerprint','By Face','By Manual']);
            foreach ($data as $r) {
                fputcsv($out, [$r['session_date'], $r['session_name'], $r['total_enrolled'],
                    $r['confirmed'], $r['absent'], $r['pending'],
                    number_format((float)$r['revenue'], 2),
                    $r['by_qr'], $r['by_fp'], $r['by_face'], $r['by_manual']]);
            }
            break;
        case 'student_attendance':
            fputcsv($out, ['Student','Class','Student ID','Sessions Enrolled','Confirmed','Absent','Absence Rate %','Longest Absence Streak']);
            foreach ($data as $r) {
                fputcsv($out, [$r['student_name'], $r['class'], $r['student_code'],
                    $r['sessions_enrolled'], $r['sessions_confirmed'], $r['sessions_absent'],
                    $r['absence_rate'], $r['longest_streak']]);
            }
            break;
        case 'financial_reconciliation':
            fputcsv($out, ['Student','Class','Payments','Fees Collected (GHS)','Entitlements Created','Meals Confirmed','Meals Absent','Discrepancy']);
            foreach ($data as $r) {
                fputcsv($out, [$r['student_name'], $r['class'], $r['payment_count'],
                    number_format((float)$r['fees_collected'], 2),
                    $r['entitlements_created'], $r['meals_confirmed'], $r['meals_absent'],
                    $r['discrepancy'] ? 'YES' : '']);
            }
            break;
        case 'express_stats':
            fputcsv($out, ['Fee Type','Class','Express Payments','Standard Payments','Total','Express Revenue (GHS)','Total Revenue (GHS)']);
            foreach ($data as $r) {
                fputcsv($out, [$r['fee_type'], $r['class'], $r['express_count'], $r['standard_count'],
                    $r['total_count'], number_format((float)$r['express_revenue'], 2),
                    number_format((float)$r['total_revenue'], 2)]);
            }
            break;
        case 'biometric_usage':
            fputcsv($out, ['Method','Total Scans','Successes','Failures','Success Rate %','Avg Confidence']);
            foreach ($data as $r) {
                fputcsv($out, [$r['verification_method'], $r['total_scans'], $r['success_count'],
                    $r['failure_count'], $r['success_rate'],
                    $r['avg_confidence'] !== null ? number_format((float)$r['avg_confidence'] * 100, 1).'%' : '—']);
            }
            break;
    }
    fclose($out);
    exit;
}

// ── PDF Export ────────────────────────────────────────────────────────────────
if ($export === 'pdf') {
    $options = new Options();
    $options->set('defaultFont', 'Helvetica');
    $options->set('isHtml5ParserEnabled', true);
    $dompdf = new Dompdf($options);

    $pdf_html  = '<!DOCTYPE html><html><head><meta charset="UTF-8"><style>';
    $pdf_html .= 'body{font-family:Helvetica,Arial,sans-serif;font-size:11px;margin:1cm;color:#1e293b}';
    $pdf_html .= 'h1{font-size:16px;margin:0 0 2px}h2{font-size:12px;margin:0 0 12px;color:#475569;font-weight:normal}';
    $pdf_html .= 'table{width:100%;border-collapse:collapse;margin-top:10px}';
    $pdf_html .= 'th{background:#1e3a5f;color:#fff;padding:6px 8px;text-align:left;font-size:10px}';
    $pdf_html .= 'td{padding:5px 8px;border-bottom:1px solid #e2e8f0;font-size:10px}';
    $pdf_html .= 'tr:nth-child(even) td{background:#f8fafc}';
    $pdf_html .= '.disc{background:#fee2e2!important;color:#dc2626;font-weight:bold}';
    $pdf_html .= '.badge-warn{color:#b45309;font-weight:bold}.footer{margin-top:20px;font-size:9px;color:#94a3b8;border-top:1px solid #e2e8f0;padding-top:6px}';
    $pdf_html .= '</style></head><body>';
    $pdf_html .= '<h1>' . htmlspecialchars($report_title) . '</h1>';
    $pdf_html .= '<h2>' . htmlspecialchars($school_name) . ' &nbsp;|&nbsp; '
              . htmlspecialchars($date_from) . ' to ' . htmlspecialchars($date_to) . '</h2>';

    switch ($report) {
        case 'daily_meal':
            $pdf_html .= '<table><tr><th>Date</th><th>Session</th><th>Enrolled</th><th>Confirmed</th><th>Absent</th><th>Revenue (GHS)</th><th>QR</th><th>FP</th><th>Face</th><th>Manual</th></tr>';
            $total_rev = 0;
            foreach ($data as $r) {
                $total_rev += (float)$r['revenue'];
                $pdf_html .= '<tr><td>' . htmlspecialchars($r['session_date']) . '</td>'
                    . '<td>' . htmlspecialchars($r['session_name']) . '</td>'
                    . '<td>' . (int)$r['total_enrolled'] . '</td>'
                    . '<td>' . (int)$r['confirmed'] . '</td>'
                    . '<td>' . (int)$r['absent'] . '</td>'
                    . '<td>' . number_format((float)$r['revenue'], 2) . '</td>'
                    . '<td>' . (int)$r['by_qr'] . '</td>'
                    . '<td>' . (int)$r['by_fp'] . '</td>'
                    . '<td>' . (int)$r['by_face'] . '</td>'
                    . '<td>' . (int)$r['by_manual'] . '</td></tr>';
            }
            $pdf_html .= '<tr><td colspan="5"><strong>Total Revenue</strong></td><td><strong>' . number_format($total_rev, 2) . '</strong></td><td colspan="4"></td></tr>';
            $pdf_html .= '</table>';
            break;
        case 'student_attendance':
            $pdf_html .= '<table><tr><th>Student</th><th>Class</th><th>ID</th><th>Enrolled</th><th>Confirmed</th><th>Absent</th><th>Absence %</th><th>Longest Streak</th></tr>';
            foreach ($data as $r) {
                $at_risk = $r['longest_streak'] >= 3;
                $pdf_html .= '<tr><td' . ($at_risk ? ' class="disc"' : '') . '>' . htmlspecialchars($r['student_name']) . '</td>'
                    . '<td>' . htmlspecialchars($r['class']) . '</td>'
                    . '<td>' . htmlspecialchars($r['student_code']) . '</td>'
                    . '<td>' . (int)$r['sessions_enrolled'] . '</td>'
                    . '<td>' . (int)$r['sessions_confirmed'] . '</td>'
                    . '<td>' . (int)$r['sessions_absent'] . '</td>'
                    . '<td>' . $r['absence_rate'] . '%</td>'
                    . '<td>' . (int)$r['longest_streak'] . '</td></tr>';
            }
            $pdf_html .= '</table>';
            break;
        case 'financial_reconciliation':
            $pdf_html .= '<table><tr><th>Student</th><th>Class</th><th>Payments</th><th>Collected (GHS)</th><th>Entitlements</th><th>Confirmed</th><th>Absent</th><th>Flag</th></tr>';
            foreach ($data as $r) {
                $cls = $r['discrepancy'] ? ' class="disc"' : '';
                $pdf_html .= '<tr' . $cls . '><td>' . htmlspecialchars($r['student_name']) . '</td>'
                    . '<td>' . htmlspecialchars($r['class']) . '</td>'
                    . '<td>' . (int)$r['payment_count'] . '</td>'
                    . '<td>' . number_format((float)$r['fees_collected'], 2) . '</td>'
                    . '<td>' . (int)$r['entitlements_created'] . '</td>'
                    . '<td>' . (int)$r['meals_confirmed'] . '</td>'
                    . '<td>' . (int)$r['meals_absent'] . '</td>'
                    . '<td>' . ($r['discrepancy'] ? '⚠ No entitlement' : '') . '</td></tr>';
            }
            $pdf_html .= '</table>';
            break;
        case 'express_stats':
            $pdf_html .= '<table><tr><th>Fee Type</th><th>Class</th><th>Express</th><th>Standard</th><th>Total</th><th>Express Rev (GHS)</th><th>Total Rev (GHS)</th></tr>';
            foreach ($data as $r) {
                $pdf_html .= '<tr><td>' . htmlspecialchars($r['fee_type']) . '</td>'
                    . '<td>' . htmlspecialchars($r['class']) . '</td>'
                    . '<td>' . (int)$r['express_count'] . '</td>'
                    . '<td>' . (int)$r['standard_count'] . '</td>'
                    . '<td>' . (int)$r['total_count'] . '</td>'
                    . '<td>' . number_format((float)$r['express_revenue'], 2) . '</td>'
                    . '<td>' . number_format((float)$r['total_revenue'], 2) . '</td></tr>';
            }
            $pdf_html .= '</table>';
            break;
        case 'biometric_usage':
            $pdf_html .= '<table><tr><th>Method</th><th>Total Scans</th><th>Successes</th><th>Failures</th><th>Success Rate</th><th>Avg Confidence</th></tr>';
            foreach ($data as $r) {
                $pdf_html .= '<tr><td>' . htmlspecialchars($r['verification_method']) . '</td>'
                    . '<td>' . (int)$r['total_scans'] . '</td>'
                    . '<td>' . (int)$r['success_count'] . '</td>'
                    . '<td>' . (int)$r['failure_count'] . '</td>'
                    . '<td>' . $r['success_rate'] . '%</td>'
                    . '<td>' . ($r['avg_confidence'] !== null ? number_format((float)$r['avg_confidence'] * 100, 1) . '%' : '—') . '</td></tr>';
            }
            $pdf_html .= '</table>';
            break;
    }

    $pdf_html .= '<div class="footer">Generated by EduTrack Canteen Module — '
              . date('d M Y, H:i') . ' — ' . htmlspecialchars($school_name) . '</div>';
    $pdf_html .= '</body></html>';

    $dompdf->loadHtml($pdf_html);
    $dompdf->setPaper('A4', 'landscape');
    $dompdf->render();
    $dompdf->stream('canteen_' . $report . '_' . $date_from . '_' . $date_to . '.pdf',
                    ['Attachment' => true]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canteen Reports — EduTrack</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .report-card { background: #fff; border-radius: 12px; padding: 1.5rem; box-shadow: 0 1px 4px rgba(0,0,0,.07); }
        .report-nav .nav-link { border-radius: 8px; font-size: .85rem; padding: .45rem 1rem; color: #475569; }
        .report-nav .nav-link.active { background: #1e3a5f; color: #fff; }
        .report-nav .nav-link:hover:not(.active) { background: #f1f5f9; }
        .stat-pill { display: inline-flex; align-items: center; gap: .35rem; background: #f1f5f9; border-radius: 20px; padding: .25rem .75rem; font-size: .8rem; color: #475569; }
        .stat-pill.green { background: #dcfce7; color: #15803d; }
        .stat-pill.red   { background: #fee2e2; color: #dc2626; }
        .stat-pill.amber { background: #fef3c7; color: #b45309; }
        .method-badge { font-size: .7rem; border-radius: 4px; padding: 2px 6px; text-transform: uppercase; font-weight: 600; }
        .method-qr   { background:#dcfce7; color:#15803d; }
        .method-fingerprint { background:#dbeafe; color:#1d4ed8; }
        .method-facial  { background:#f3e8ff; color:#7c3aed; }
        .method-manual_id { background:#fff7ed; color:#c2410c; }
        .table-sm td, .table-sm th { font-size: .82rem; vertical-align: middle; }
        .disc-row td { background: #fef2f2 !important; }
        .at-risk td:first-child { color: #dc2626; font-weight: 600; }
        .empty-state { text-align: center; padding: 3rem 1rem; color: #94a3b8; }
        .summary-bar { background: #f8fafc; border-radius: 10px; padding: .75rem 1.25rem; display: flex; gap: 2rem; flex-wrap: wrap; align-items: center; margin-bottom: 1rem; font-size: .85rem; }
        .summary-bar span { color: #64748b; }
        .summary-bar strong { color: #1e293b; }
    </style>
</head>
<body>
<div class="wrapper">
    <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar('canteen/reports.php'); ?>
    </nav>
    <div class="main-content">
        <header class="header">
            <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
            <div class="header-right">
                <div class="dropdown">
                    <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string)($_SESSION['full_name'] ?? '')); ?>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="../settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="../logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                    </ul>
                </div>
            </div>
        </header>
        <div class="content">

            <div class="d-flex align-items-center gap-3 mb-4">
                <div style="background:linear-gradient(135deg,#1e3a5f,#1e40af);width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center">
                    <i class="fas fa-chart-bar text-white fs-5"></i>
                </div>
                <div>
                    <h4 class="mb-0 fw-bold">Canteen Reports</h4>
                    <p class="mb-0 text-muted small">Analytics and export tools for canteen data</p>
                </div>
            </div>

            <!-- Filters bar -->
            <div class="report-card mb-3">
                <form method="GET" class="row g-2 align-items-end">
                    <input type="hidden" name="report" value="<?php echo htmlspecialchars($report); ?>">
                    <div class="col-sm-auto">
                        <label class="form-label small mb-1 text-muted">From</label>
                        <input type="date" name="date_from" class="form-control form-control-sm"
                               value="<?php echo htmlspecialchars($date_from); ?>">
                    </div>
                    <div class="col-sm-auto">
                        <label class="form-label small mb-1 text-muted">To</label>
                        <input type="date" name="date_to" class="form-control form-control-sm"
                               value="<?php echo htmlspecialchars($date_to); ?>">
                    </div>
                    <div class="col-sm-auto">
                        <button type="submit" class="btn btn-primary btn-sm">
                            <i class="fas fa-filter me-1"></i>Apply
                        </button>
                    </div>
                    <div class="col-sm-auto ms-auto">
                        <a href="?report=<?php echo urlencode($report); ?>&date_from=<?php echo urlencode($date_from); ?>&date_to=<?php echo urlencode($date_to); ?>&export=csv"
                           class="btn btn-outline-secondary btn-sm">
                            <i class="fas fa-file-csv me-1"></i>Export CSV
                        </a>
                        <a href="?report=<?php echo urlencode($report); ?>&date_from=<?php echo urlencode($date_from); ?>&date_to=<?php echo urlencode($date_to); ?>&export=pdf"
                           class="btn btn-outline-danger btn-sm ms-1" target="_blank">
                            <i class="fas fa-file-pdf me-1"></i>Export PDF
                        </a>
                    </div>
                </form>
            </div>

            <div class="row">
                <!-- Report navigation -->
                <div class="col-md-2 mb-3">
                    <nav class="report-nav d-flex flex-column gap-1">
                        <?php
                        foreach ($report_titles as $key => $title) {
                            $active = ($key === $report) ? ' active' : '';
                            $icon_map = [
                                'daily_meal'               => 'fa-utensils',
                                'student_attendance'       => 'fa-user-check',
                                'financial_reconciliation' => 'fa-scale-balanced',
                                'express_stats'            => 'fa-bolt',
                                'biometric_usage'          => 'fa-fingerprint',
                            ];
                            $icon = $icon_map[$key] ?? 'fa-chart-bar';
                            echo '<a href="?report=' . urlencode($key) . '&date_from=' . urlencode($date_from)
                               . '&date_to=' . urlencode($date_to) . '" class="nav-link' . $active . '">'
                               . '<i class="fas ' . $icon . ' me-2"></i>' . htmlspecialchars($title) . '</a>';
                        }
                        ?>
                    </nav>
                </div>

                <!-- Report content -->
                <div class="col-md-10">
                    <div class="report-card">
                        <h5 class="fw-bold mb-3"><?php echo htmlspecialchars($report_title); ?>
                            <small class="text-muted fw-normal fs-6 ms-2">
                                <?php echo htmlspecialchars($date_from === $date_to
                                    ? date('d M Y', strtotime($date_from))
                                    : date('d M Y', strtotime($date_from)) . ' – ' . date('d M Y', strtotime($date_to))); ?>
                            </small>
                        </h5>

                        <?php if (empty($data) && $report !== 'express_stats'): ?>
                            <div class="empty-state">
                                <i class="fas fa-inbox fa-2x mb-2"></i>
                                <p class="mb-0">No data for this period.</p>
                            </div>

                        <?php elseif ($report === 'daily_meal'): ?>
                            <?php
                            $total_enrolled  = array_sum(array_column($data, 'total_enrolled'));
                            $total_confirmed = array_sum(array_column($data, 'confirmed'));
                            $total_absent    = array_sum(array_column($data, 'absent'));
                            $total_revenue   = array_sum(array_column($data, 'revenue'));
                            ?>
                            <div class="summary-bar">
                                <div><span>Sessions</span> <strong><?php echo count($data); ?></strong></div>
                                <div><span>Total Enrolled</span> <strong><?php echo $total_enrolled; ?></strong></div>
                                <div><span>Confirmed</span> <strong class="text-success"><?php echo $total_confirmed; ?></strong></div>
                                <div><span>Absent</span> <strong class="text-danger"><?php echo $total_absent; ?></strong></div>
                                <div><span>Revenue</span> <strong>GHS <?php echo number_format($total_revenue, 2); ?></strong></div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-hover table-sm">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Date</th><th>Session</th><th>Enrolled</th>
                                            <th>Confirmed</th><th>Absent</th><th>%</th>
                                            <th>Revenue (GHS)</th>
                                            <th colspan="4">Verification</th>
                                        </tr>
                                        <tr class="table-secondary" style="font-size:.7rem">
                                            <th colspan="7"></th>
                                            <th><span class="method-badge method-qr">QR</span></th>
                                            <th><span class="method-badge method-fingerprint">FP</span></th>
                                            <th><span class="method-badge method-facial">Face</span></th>
                                            <th><span class="method-badge method-manual_id">Manual</span></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php foreach ($data as $r):
                                        $pct = $r['total_enrolled'] > 0 ? round($r['confirmed'] / $r['total_enrolled'] * 100) : 0;
                                        $pct_cls = $pct >= 80 ? 'text-success' : ($pct >= 40 ? 'text-warning' : 'text-danger');
                                    ?>
                                        <tr>
                                            <td><?php echo date('d M', strtotime($r['session_date'])); ?></td>
                                            <td><?php echo htmlspecialchars($r['session_name']); ?></td>
                                            <td><?php echo (int)$r['total_enrolled']; ?></td>
                                            <td class="text-success fw-semibold"><?php echo (int)$r['confirmed']; ?></td>
                                            <td class="text-danger"><?php echo (int)$r['absent']; ?></td>
                                            <td class="<?php echo $pct_cls; ?> fw-semibold"><?php echo $pct; ?>%</td>
                                            <td><?php echo number_format((float)$r['revenue'], 2); ?></td>
                                            <td><?php echo (int)$r['by_qr']; ?></td>
                                            <td><?php echo (int)$r['by_fp']; ?></td>
                                            <td><?php echo (int)$r['by_face']; ?></td>
                                            <td><?php echo (int)$r['by_manual']; ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr class="table-light fw-bold">
                                            <td colspan="2">Total</td>
                                            <td><?php echo $total_enrolled; ?></td>
                                            <td class="text-success"><?php echo $total_confirmed; ?></td>
                                            <td class="text-danger"><?php echo $total_absent; ?></td>
                                            <td><?php echo $total_enrolled > 0 ? round($total_confirmed / $total_enrolled * 100) : 0; ?>%</td>
                                            <td>GHS <?php echo number_format($total_revenue, 2); ?></td>
                                            <td><?php echo array_sum(array_column($data, 'by_qr')); ?></td>
                                            <td><?php echo array_sum(array_column($data, 'by_fp')); ?></td>
                                            <td><?php echo array_sum(array_column($data, 'by_face')); ?></td>
                                            <td><?php echo array_sum(array_column($data, 'by_manual')); ?></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>

                        <?php elseif ($report === 'student_attendance'): ?>
                            <?php
                            $at_risk_count = count(array_filter($data, fn($r) => $r['longest_streak'] >= 3));
                            ?>
                            <div class="summary-bar">
                                <div><span>Students</span> <strong><?php echo count($data); ?></strong></div>
                                <div><span>At Risk (≥3 consecutive absences)</span>
                                    <strong class="text-danger"><?php echo $at_risk_count; ?></strong></div>
                            </div>
                            <?php if ($at_risk_count > 0): ?>
                            <div class="alert alert-warning py-2 mb-3" style="font-size:.85rem">
                                <i class="fas fa-triangle-exclamation me-1"></i>
                                <strong><?php echo $at_risk_count; ?> student<?php echo $at_risk_count > 1 ? 's' : ''; ?></strong>
                                highlighted in red have 3 or more consecutive absent sessions.
                            </div>
                            <?php endif; ?>
                            <div class="table-responsive">
                                <table class="table table-hover table-sm">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Student</th><th>Class</th><th>ID</th>
                                            <th>Enrolled</th><th>Confirmed</th><th>Absent</th>
                                            <th>Absence Rate</th><th>Longest Streak</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php foreach ($data as $r):
                                        $at_risk = $r['longest_streak'] >= 3;
                                        $rate_cls = (float)$r['absence_rate'] >= 50 ? 'text-danger' : ((float)$r['absence_rate'] >= 25 ? 'text-warning' : 'text-success');
                                    ?>
                                        <tr class="<?php echo $at_risk ? 'at-risk' : ''; ?>">
                                            <td><?php echo htmlspecialchars($r['student_name']); ?></td>
                                            <td><?php echo htmlspecialchars($r['class']); ?></td>
                                            <td><?php echo htmlspecialchars($r['student_code']); ?></td>
                                            <td><?php echo (int)$r['sessions_enrolled']; ?></td>
                                            <td class="text-success"><?php echo (int)$r['sessions_confirmed']; ?></td>
                                            <td class="text-danger"><?php echo (int)$r['sessions_absent']; ?></td>
                                            <td class="<?php echo $rate_cls; ?> fw-semibold"><?php echo $r['absence_rate']; ?>%</td>
                                            <td><?php echo $at_risk ? '<span class="badge bg-danger">' . (int)$r['longest_streak'] . '</span>' : (int)$r['longest_streak']; ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                        <?php elseif ($report === 'financial_reconciliation'): ?>
                            <?php $disc_count = count(array_filter($data, fn($r) => $r['discrepancy'])); ?>
                            <div class="summary-bar">
                                <div><span>Students with feeding payments</span> <strong><?php echo count($data); ?></strong></div>
                                <div><span>Discrepancies (paid, no entitlement)</span>
                                    <strong class="<?php echo $disc_count > 0 ? 'text-danger' : 'text-success'; ?>">
                                        <?php echo $disc_count; ?></strong></div>
                                <div><span>Total Collected</span>
                                    <strong>GHS <?php echo number_format(array_sum(array_column($data, 'fees_collected')), 2); ?></strong></div>
                            </div>
                            <?php if ($disc_count > 0): ?>
                            <div class="alert alert-danger py-2 mb-3" style="font-size:.85rem">
                                <i class="fas fa-circle-exclamation me-1"></i>
                                <strong><?php echo $disc_count; ?> discrepanc<?php echo $disc_count > 1 ? 'ies' : 'y'; ?></strong>
                                found — feeding fee recorded but no canteen entitlement was created. Rows highlighted in red.
                            </div>
                            <?php endif; ?>
                            <div class="table-responsive">
                                <table class="table table-hover table-sm">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Student</th><th>Class</th><th>Payments</th>
                                            <th>Collected (GHS)</th><th>Entitlements</th>
                                            <th>Confirmed</th><th>Absent</th><th>Flag</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php foreach ($data as $r): ?>
                                        <tr class="<?php echo $r['discrepancy'] ? 'disc-row' : ''; ?>">
                                            <td><?php echo htmlspecialchars($r['student_name']); ?></td>
                                            <td><?php echo htmlspecialchars($r['class']); ?></td>
                                            <td><?php echo (int)$r['payment_count']; ?></td>
                                            <td><?php echo number_format((float)$r['fees_collected'], 2); ?></td>
                                            <td><?php echo (int)$r['entitlements_created']; ?></td>
                                            <td class="text-success"><?php echo (int)$r['meals_confirmed']; ?></td>
                                            <td class="text-danger"><?php echo (int)$r['meals_absent']; ?></td>
                                            <td><?php echo $r['discrepancy']
                                                ? '<span class="badge bg-danger"><i class="fas fa-triangle-exclamation me-1"></i>No entitlement</span>'
                                                : ''; ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                        <?php elseif ($report === 'express_stats'): ?>
                            <?php if (empty($data)): ?>
                                <div class="empty-state">
                                    <i class="fas fa-inbox fa-2x mb-2"></i>
                                    <p class="mb-0">No payment data for this period.</p>
                                </div>
                            <?php else: ?>
                            <?php
                            $pct_express = $express_totals['total_count'] > 0
                                ? round($express_totals['express_count'] / $express_totals['total_count'] * 100, 1) : 0;
                            $saved_seconds = $express_totals['express_count'] * 45;
                            $saved_mins    = floor($saved_seconds / 60);
                            ?>
                            <div class="summary-bar">
                                <div><span>Total Payments</span> <strong><?php echo $express_totals['total_count']; ?></strong></div>
                                <div><span>Via Express Scanner</span>
                                    <strong class="text-success"><?php echo $express_totals['express_count']; ?> (<?php echo $pct_express; ?>%)</strong></div>
                                <div><span>Standard</span> <strong><?php echo $express_totals['standard_count']; ?></strong></div>
                                <div><span>Total Revenue</span> <strong>GHS <?php echo number_format($express_totals['total_revenue'], 2); ?></strong></div>
                                <div><span>Est. Time Saved</span> <strong class="text-primary"><?php echo $saved_mins; ?> mins</strong>
                                    <small class="text-muted">(45s per express payment)</small></div>
                            </div>
                            <!-- Progress visualisation -->
                            <div class="mb-3">
                                <div class="d-flex justify-content-between small text-muted mb-1">
                                    <span>Express vs Standard</span>
                                    <span><?php echo $pct_express; ?>% via scanner</span>
                                </div>
                                <div class="progress" style="height:8px">
                                    <div class="progress-bar bg-success" style="width:<?php echo $pct_express; ?>%"></div>
                                    <div class="progress-bar bg-secondary" style="width:<?php echo 100 - $pct_express; ?>%"></div>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-hover table-sm">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Fee Type</th><th>Class</th>
                                            <th>Express</th><th>Standard</th><th>Total</th>
                                            <th>Express Revenue (GHS)</th><th>Total Revenue (GHS)</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php foreach ($data as $r): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($r['fee_type']); ?></td>
                                            <td><?php echo htmlspecialchars($r['class']); ?></td>
                                            <td class="text-success fw-semibold"><?php echo (int)$r['express_count']; ?></td>
                                            <td><?php echo (int)$r['standard_count']; ?></td>
                                            <td><?php echo (int)$r['total_count']; ?></td>
                                            <td><?php echo number_format((float)$r['express_revenue'], 2); ?></td>
                                            <td><?php echo number_format((float)$r['total_revenue'], 2); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr class="table-light fw-bold">
                                            <td colspan="2">Total</td>
                                            <td class="text-success"><?php echo $express_totals['express_count']; ?></td>
                                            <td><?php echo $express_totals['standard_count']; ?></td>
                                            <td><?php echo $express_totals['total_count']; ?></td>
                                            <td><?php echo number_format($express_totals['express_revenue'], 2); ?></td>
                                            <td><?php echo number_format($express_totals['total_revenue'], 2); ?></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                            <?php endif; ?>

                        <?php elseif ($report === 'biometric_usage'): ?>
                            <?php if (empty($data)): ?>
                                <div class="empty-state">
                                    <i class="fas fa-fingerprint fa-2x mb-2"></i>
                                    <p class="mb-0">No biometric scan data for this period.</p>
                                    <?php if (!$settings['fingerprint_enabled'] && !$settings['facial_recognition_enabled']): ?>
                                    <p class="small text-muted mt-1">Biometrics are not currently enabled in
                                        <a href="settings.php?tab=biometrics">Settings</a>.</p>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover table-sm">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Verification Method</th><th>Total Scans</th>
                                            <th>Successes</th><th>Failures</th>
                                            <th>Success Rate</th><th>Avg Confidence</th>
                                            <th>Distribution</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php
                                    $grand_total = array_sum(array_column($data, 'total_scans'));
                                    foreach ($data as $r):
                                        $dist_pct = $grand_total > 0 ? round($r['total_scans'] / $grand_total * 100, 1) : 0;
                                        $badge_cls = 'method-' . $r['verification_method'];
                                    ?>
                                        <tr>
                                            <td><span class="method-badge <?php echo $badge_cls; ?>"><?php echo htmlspecialchars($r['verification_method']); ?></span></td>
                                            <td><?php echo (int)$r['total_scans']; ?></td>
                                            <td class="text-success fw-semibold"><?php echo (int)$r['success_count']; ?></td>
                                            <td class="text-danger"><?php echo (int)$r['failure_count']; ?></td>
                                            <td>
                                                <div class="d-flex align-items-center gap-2">
                                                    <div class="progress flex-grow-1" style="height:6px;min-width:60px">
                                                        <div class="progress-bar bg-success" style="width:<?php echo $r['success_rate']; ?>%"></div>
                                                    </div>
                                                    <span class="fw-semibold"><?php echo $r['success_rate']; ?>%</span>
                                                </div>
                                            </td>
                                            <td><?php echo $r['avg_confidence'] !== null
                                                ? number_format((float)$r['avg_confidence'] * 100, 1) . '%'
                                                : '—'; ?></td>
                                            <td>
                                                <div class="progress" style="height:6px;min-width:80px">
                                                    <div class="progress-bar bg-primary" style="width:<?php echo $dist_pct; ?>%"></div>
                                                </div>
                                                <small class="text-muted"><?php echo $dist_pct; ?>% of all scans</small>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr class="table-light fw-bold">
                                            <td>Total</td>
                                            <td><?php echo $grand_total; ?></td>
                                            <td class="text-success"><?php echo array_sum(array_column($data, 'success_count')); ?></td>
                                            <td class="text-danger"><?php echo array_sum(array_column($data, 'failure_count')); ?></td>
                                            <td colspan="3"></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                            <?php endif; ?>
                        <?php endif; ?>

                    </div><!-- /report-card -->
                </div><!-- /col -->
            </div><!-- /row -->

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

<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="../js/main.js"></script>
<script>
// Report type selector — update hidden input and submit
document.querySelectorAll('.report-nav .nav-link').forEach(link => {
    link.addEventListener('click', e => {
        // Allow normal navigation
    });
});

// Quick preset buttons
document.querySelectorAll('[data-preset]').forEach(btn => {
    btn.addEventListener('click', function () {
        const preset = this.dataset.preset;
        const today = new Date();
        let from, to;
        if (preset === 'today') {
            from = to = today.toISOString().slice(0, 10);
        } else if (preset === 'week') {
            const day = today.getDay() || 7;
            const mon = new Date(today); mon.setDate(today.getDate() - day + 1);
            from = mon.toISOString().slice(0, 10);
            to   = today.toISOString().slice(0, 10);
        } else if (preset === 'month') {
            from = today.toISOString().slice(0, 8) + '01';
            to   = today.toISOString().slice(0, 10);
        }
        document.querySelector('[name="date_from"]').value = from;
        document.querySelector('[name="date_to"]').value   = to;
        document.querySelector('form').submit();
    });
});
</script>
</body>
</html>
