<?php
/**
 * Canteen Cook Dashboard Stats
 * Auth: canteen_cook_authenticated OR valid EduTrack role
 * Cached: 15 seconds server-side (file cache)
 */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');
header('Cache-Control: no-store');

require_once '../config.php';
require_once '../includes/canteen_helpers.php';

canteen_require_active();

$is_cook    = !empty($_SESSION['canteen_cook_authenticated']);
$is_role    = !empty($_SESSION['user_id']);
if (!$is_cook && !$is_role) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Not authenticated.']);
    exit;
}

// 15-second file cache
$today     = date('Y-m-d');
$cacheFile = sys_get_temp_dir() . '/edutrack_canteen_stats_' . md5($today) . '.json';
$cacheAge  = 15;

if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheAge) {
    echo file_get_contents($cacheFile);
    exit;
}

$conn = getDBConnection();

// Load today's sessions (non-cancelled)
$sessStmt = $conn->prepare(
    "SELECT id, session_name, start_time, end_time, status, total_enrolled,
            (SELECT COUNT(*) FROM canteen_entitlements
             WHERE session_id = canteen_sessions.id AND status = 'confirmed') AS confirmed_count
     FROM canteen_sessions
     WHERE session_date = ? AND school_id = 1 AND status != 'cancelled'
     ORDER BY start_time ASC"
);
$sessStmt->bind_param('s', $today);
$sessStmt->execute();
$sessions_raw = $sessStmt->get_result()->fetch_all(MYSQLI_ASSOC);
$sessStmt->close();

$sessions = [];
$now_ts   = time();

foreach ($sessions_raw as $s) {
    $session_id = (int)$s['id'];
    $enrolled   = (int)$s['total_enrolled'];
    $confirmed  = (int)$s['confirmed_count'];
    $absent     = $enrolled - $confirmed;
    $pct        = $enrolled > 0 ? round(($confirmed / $enrolled) * 100, 1) : 0.0;

    // Determine if we're past halfway through the session
    $start_ts     = strtotime($today . ' ' . $s['start_time']);
    $end_ts       = strtotime($today . ' ' . $s['end_time']);
    $duration     = max(1, $end_ts - $start_ts);
    $elapsed_pct  = $now_ts >= $start_ts ? min(100, (($now_ts - $start_ts) / $duration) * 100) : 0;
    $past_halfway = $elapsed_pct >= 50;

    // Per-class breakdown
    $clsStmt = $conn->prepare(
        "SELECT s.class,
                COUNT(*) AS enrolled,
                SUM(CASE WHEN ce.status = 'confirmed' THEN 1 ELSE 0 END) AS confirmed
         FROM canteen_entitlements ce
         JOIN students s ON s.id = ce.student_id
         WHERE ce.session_id = ?
         GROUP BY s.class
         ORDER BY s.class"
    );
    $clsStmt->bind_param('i', $session_id);
    $clsStmt->execute();
    $classes_raw = $clsStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $clsStmt->close();

    $classes = [];
    foreach ($classes_raw as $c) {
        $c_enrolled  = (int)$c['enrolled'];
        $c_confirmed = (int)$c['confirmed'];
        $c_pct       = $c_enrolled > 0 ? round(($c_confirmed / $c_enrolled) * 100, 1) : 0.0;
        $c_expected  = $c_enrolled - $c_confirmed;

        if ($c_pct >= 80) {
            $row_class = 'success';
        } elseif ($c_pct >= 40) {
            $row_class = 'warning';
        } else {
            $row_class = $past_halfway ? 'danger' : 'warning';
        }

        $classes[] = [
            'class_name'  => $c['class'],
            'enrolled'    => $c_enrolled,
            'confirmed'   => $c_confirmed,
            'expected'    => $c_expected,
            'pct'         => $c_pct,
            'row_class'   => $row_class,
        ];
    }

    // 15-minute interval arrival counts
    $intStmt = $conn->prepare(
        "SELECT
            FLOOR(TIME_TO_SEC(TIMEDIFF(cs.scanned_at, ?)) / 900) AS slot,
            COUNT(*) AS count
         FROM canteen_scans cs
         WHERE cs.session_id = ? AND cs.scan_result = 'success'
           AND cs.scanned_at >= ?
         GROUP BY slot
         ORDER BY slot ASC"
    );
    $start_str  = $today . ' ' . $s['start_time'];
    $start_dt   = $today . ' 00:00:00';
    $intStmt->bind_param('sis', $start_str, $session_id, $start_dt);
    $intStmt->execute();
    $intervals_raw = $intStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $intStmt->close();

    // Build labelled intervals
    $intervals = [];
    $max_in_slot = 1;
    foreach ($intervals_raw as $iv) {
        $slot     = (int)$iv['slot'];
        $slot_ts  = $start_ts + ($slot * 900);
        $label    = date('H:i', $slot_ts);
        $count    = (int)$iv['count'];
        if ($count > $max_in_slot) $max_in_slot = $count;
        $intervals[] = ['label' => $label, 'count' => $count, 'slot' => $slot];
    }

    // Arrival rate projection (linear extrapolation from confirmed + elapsed time)
    $projected = $confirmed;
    if ($elapsed_pct > 5 && $elapsed_pct < 100) {
        $projected = (int)round(($confirmed / ($elapsed_pct / 100)));
        $projected = min($projected, $enrolled); // cap at enrolled
    }

    $sessions[] = [
        'session_id'    => $session_id,
        'session_name'  => $s['session_name'],
        'start_time'    => date('H:i', strtotime($s['start_time'])),
        'end_time'      => date('H:i', strtotime($s['end_time'])),
        'status'        => $s['status'],
        'enrolled'      => $enrolled,
        'confirmed'     => $confirmed,
        'absent'        => $absent,
        'pct'           => $pct,
        'projected'     => $projected,
        'elapsed_pct'   => round($elapsed_pct, 1),
        'past_halfway'  => $past_halfway,
        'classes'       => $classes,
        'intervals'     => $intervals,
        'max_slot_count'=> $max_in_slot,
    ];
}

$conn->close();

$payload = json_encode([
    'success'    => true,
    'date'       => $today,
    'generated'  => date('H:i:s'),
    'sessions'   => $sessions,
]);

file_put_contents($cacheFile, $payload);
echo $payload;
