<?php
/**
 * Action: Return a canteen daily meal report for a given date.
 */

if (!defined('DB_HOST')) {
    require_once __DIR__ . '/../../config.php';
}
require_once __DIR__ . '/../../includes/canteen_helpers.php';

function action_canteen_daily_report(array $params): array
{
    if (!canteen_is_active()) {
        return ['success' => false, 'error' => 'Canteen module is not active.'];
    }

    $conn = getDBConnection();
    $date = trim((string) ($params['date'] ?? date('Y-m-d')));

    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
        $date = date('Y-m-d');
    }

    $stmt = $conn->prepare(
        "SELECT cs.id, cs.session_name, cs.start_time, cs.end_time, cs.status,
                cs.total_enrolled,
                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 = ? AND cs.status != 'cancelled'
         GROUP BY cs.id
         ORDER BY cs.start_time ASC"
    );
    $stmt->bind_param('s', $date);
    $stmt->execute();
    $sessions = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    $conn->close();

    if (empty($sessions)) {
        return [
            'success' => true,
            'date'    => $date,
            'sessions'=> [],
            'summary' => "No canteen sessions found for {$date}.",
        ];
    }

    $total_enrolled  = (int) array_sum(array_column($sessions, 'total_enrolled'));
    $total_confirmed = (int) array_sum(array_column($sessions, 'confirmed'));
    $total_absent    = (int) array_sum(array_column($sessions, 'absent'));
    $total_pending   = (int) array_sum(array_column($sessions, 'pending'));
    $total_revenue   = array_sum(array_column($sessions, 'revenue'));

    $session_lines = [];
    foreach ($sessions as $s) {
        $pct = $s['total_enrolled'] > 0
            ? round($s['confirmed'] / $s['total_enrolled'] * 100) : 0;
        $session_lines[] = "{$s['session_name']}: {$s['confirmed']}/{$s['total_enrolled']} confirmed ({$pct}%), GHS " . number_format((float)$s['revenue'], 2);
    }

    $overall_pct = $total_enrolled > 0 ? round($total_confirmed / $total_enrolled * 100) : 0;

    return [
        'success'         => true,
        'date'            => $date,
        'sessions'        => $sessions,
        'total_enrolled'  => $total_enrolled,
        'total_confirmed' => $total_confirmed,
        'total_absent'    => $total_absent,
        'total_pending'   => $total_pending,
        'total_revenue'   => $total_revenue,
        'overall_pct'     => $overall_pct,
        'summary'         => implode('; ', $session_lines)
            . " | Overall: {$total_confirmed}/{$total_enrolled} ({$overall_pct}%), GHS " . number_format($total_revenue, 2),
    ];
}
