<?php
/**
 * Canteen entitlement prefetch — morning offline cache download.
 * Returns today's token blob signed with a daily HMAC key.
 * Auth: canteen_staff_authenticated OR valid EduTrack role
 */
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_pin_session  = !empty($_SESSION['canteen_staff_authenticated']);
$is_role_session = !empty($_SESSION['user_id']);
if (!$is_pin_session && !$is_role_session) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Not authenticated.']);
    exit;
}

$conn     = getDBConnection();
$today    = date('Y-m-d');
$settings = canteen_get_settings();
$include_facial = !empty($settings['facial_recognition_enabled']);

// Fetch all pending/active entitlements for today
$stmt = $conn->prepare(
    "SELECT ce.qr_token, ce.student_id, ce.session_id, ce.status,
            s.first_name, s.last_name, s.class, s.student_id AS student_code, s.photo_path,
            cs.session_name
     FROM canteen_entitlements ce
     JOIN students s             ON s.id  = ce.student_id
     JOIN canteen_sessions cs    ON cs.id = ce.session_id
     WHERE cs.session_date = ? AND cs.status != 'cancelled'
     ORDER BY cs.start_time ASC, s.last_name ASC"
);
$stmt->bind_param('s', $today);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Pre-load facial descriptors if enabled (one query for all students)
$face_map = [];
if ($include_facial && !empty($rows)) {
    $student_ids = array_unique(array_column($rows, 'student_id'));
    $placeholders = implode(',', array_fill(0, count($student_ids), '?'));
    $types = str_repeat('i', count($student_ids));
    $fstmt = $conn->prepare(
        "SELECT student_id, facial_descriptor FROM canteen_biometric_credentials
         WHERE student_id IN ({$placeholders}) AND facial_descriptor IS NOT NULL"
    );
    $fstmt->bind_param($types, ...$student_ids);
    $fstmt->execute();
    $frows = $fstmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $fstmt->close();
    foreach ($frows as $fr) {
        $face_map[(int)$fr['student_id']] = json_decode($fr['facial_descriptor'], true);
    }
}

$conn->close();

$entries = [];
foreach ($rows as $row) {
    $photoData = '';
    if (!empty($row['photo_path'])) {
        $photoFile = __DIR__ . '/../uploads/students/' . basename($row['photo_path']);
        if (is_file($photoFile) && filesize($photoFile) < 200000) {
            $mime      = mime_content_type($photoFile) ?: 'image/jpeg';
            $photoData = 'data:' . $mime . ';base64,' . base64_encode(file_get_contents($photoFile));
        }
    }

    $entry = [
        'qr_token'        => $row['qr_token'],
        'student_id'      => (int)$row['student_id'],
        'session_id'      => (int)$row['session_id'],
        'student_name'    => trim($row['first_name'] . ' ' . $row['last_name']),
        'student_code'    => $row['student_code'],
        'class_name'      => $row['class'],
        'session_name'    => $row['session_name'],
        'status'          => $row['status'],
        'photo_data_url'  => $photoData,
    ];

    if ($include_facial) {
        $entry['facial_descriptor'] = $face_map[(int)$row['student_id']] ?? null;
    }

    $entries[] = $entry;
}

// Sign the blob with a daily-derived HMAC key so the SW can detect tampering
$blob_json  = json_encode($entries);
$daily_key  = hash_hmac('sha256', 'PREFETCH|' . $today, CANTEEN_SECRET_KEY);
$signature  = base64_encode(hash_hmac('sha256', $blob_json, $daily_key, true));

echo json_encode([
    'success'    => true,
    'date'       => $today,
    'signature'  => $signature,
    'daily_key'  => $daily_key,
    'entries'    => $entries,
    'count'      => count($entries),
    'generated_at' => date('H:i:s'),
]);
