<?php
/**
 * Confirm a canteen meal by student_id + session_id.
 * Used after fingerprint biometric identifies the student server-side.
 * POST: student_id, session_id, method ('fingerprint'|'facial')
 * 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_staff = !empty($_SESSION['canteen_staff_authenticated']);
$is_role  = !empty($_SESSION['user_id']);
if (!$is_staff && !$is_role) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Not authenticated.']);
    exit;
}

// Rate limit: 2 requests / second / IP (same as main validate endpoint)
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
if (!canteen_rate_limit('confirm_by_student_' . $ip, 4, 2)) {
    http_response_code(429);
    echo json_encode(['success' => false, 'message' => 'Too many requests.']);
    exit;
}

$student_id = (int)($_POST['student_id'] ?? 0);
$session_id = (int)($_POST['session_id'] ?? 0);
$method     = in_array($_POST['method'] ?? '', ['fingerprint', 'facial']) ? $_POST['method'] : 'fingerprint';

if (!$student_id || !$session_id) {
    echo json_encode(['success' => false, 'message' => 'Missing student_id or session_id.']);
    exit;
}

$conn = getDBConnection();

// Look up entitlement
$ent_stmt = $conn->prepare(
    "SELECT ce.id AS ent_id, ce.status, ce.qr_token_expires_at,
            cs.session_date, cs.status AS session_status, cs.session_name,
            s.first_name, s.last_name, s.class, s.photo_path
     FROM canteen_entitlements ce
     JOIN canteen_sessions cs ON cs.id = ce.session_id
     JOIN students s ON s.id = ce.student_id
     WHERE ce.student_id = ? AND ce.session_id = ?
     LIMIT 1"
);
$ent_stmt->bind_param('ii', $student_id, $session_id);
$ent_stmt->execute();
$ent = $ent_stmt->get_result()->fetch_assoc();
$ent_stmt->close();

if (!$ent) {
    $conn->close();
    echo json_encode(['success' => false, 'code' => 'not_enrolled',
        'message' => 'Student not enrolled in this session.']);
    exit;
}

if ($ent['status'] === 'confirmed') {
    $conn->close();
    echo json_encode(['success' => false, 'code' => 'already_confirmed',
        'message' => 'Already confirmed.',
        'student_name' => trim($ent['first_name'] . ' ' . $ent['last_name']),
        'class_name'   => $ent['class'],
    ]);
    exit;
}

if ($ent['status'] !== 'pending') {
    $conn->close();
    echo json_encode(['success' => false, 'message' => 'Entitlement is ' . $ent['status'] . '.']);
    exit;
}

if ($ent['session_status'] === 'cancelled') {
    $conn->close();
    echo json_encode(['success' => false, 'message' => 'Session is cancelled.']);
    exit;
}

if (strtotime($ent['qr_token_expires_at']) < time()) {
    $conn->close();
    echo json_encode(['success' => false, 'code' => 'expired', 'message' => 'Pass has expired.']);
    exit;
}

$confirmed_by = (int)($_SESSION['user_id'] ?? 0);
$now          = date('Y-m-d H:i:s');
$device_info  = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255);
$ent_id       = (int)$ent['ent_id'];

$conn->begin_transaction();
try {
    $upd = $conn->prepare(
        "UPDATE canteen_entitlements
         SET status = 'confirmed', verification_method = ?,
             confirmed_at = ?, confirmed_by = ?
         WHERE id = ? AND status = 'pending'"
    );
    $upd->bind_param('ssii', $method, $now, $confirmed_by, $ent_id);
    $upd->execute();
    $upd->close();

    $scan = $conn->prepare(
        "INSERT INTO canteen_scans
            (entitlement_id, student_id, session_id, scan_result,
             verification_method, scanned_by, scanned_at, device_info, ip_address)
         VALUES (?, ?, ?, 'success', ?, ?, ?, ?, ?)"
    );
    $scan->bind_param('iiisisss', $ent_id, $student_id, $session_id, $method, $confirmed_by, $now, $device_info, $ip);
    $scan->execute();
    $scan->close();

    $conn->commit();
} catch (Throwable $e) {
    $conn->rollback();
    $conn->close();
    echo json_encode(['success' => false, 'message' => 'Confirmation failed.']);
    exit;
}

$photo_url = '';
if (!empty($ent['photo_path'])) {
    $photo_url = 'uploads/students/' . basename($ent['photo_path']);
}

$conn->close();

echo json_encode([
    'success'      => true,
    'student_id'   => $student_id,
    'student_name' => trim($ent['first_name'] . ' ' . $ent['last_name']),
    'class_name'   => $ent['class'],
    'session_name' => $ent['session_name'],
    'photo_url'    => $photo_url,
    'confirmed_at' => $now,
]);
