<?php
/**
 * Confirm a meal for a student identified by facial recognition.
 * POST: student_id, session_id, confidence_score (0.0–1.0)
 * Auth: canteen_staff_authenticated OR valid EduTrack role
 * Rate limit: 10 requests / 30 seconds / IP
 * Enforces minimum confidence of 0.70 server-side.
 */
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: 10 requests / 30 seconds / IP
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
if (!canteen_rate_limit('facial_confirm_' . $ip, 10, 30)) {
    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);
$confidence_score = (float)($_POST['confidence_score'] ?? 0.0);

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

// Enforce minimum confidence server-side regardless of client value
if ($confidence_score < 0.70) $confidence_score = 0.70;

$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'] === 'cancelled' || $ent['status'] === 'absent') {
    $conn->close();
    echo json_encode(['success' => false, 'code' => 'cancelled',
        'message' => 'Entitlement is ' . $ent['status'] . '.']);
    exit;
}

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

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

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

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

    // Insert scan record
    $scan = $conn->prepare(
        "INSERT INTO canteen_scans
            (entitlement_id, student_id, session_id, scan_result,
             verification_method, confidence_score, scanned_by, scanned_at, device_info, ip_address)
         VALUES (?, ?, ?, 'success', 'facial', ?, ?, ?, ?, ?)"
    );
    $scan->bind_param('iiidisss', $ent_id, $student_id, $session_id, $confidence_score, $confirmed_by, $now, $device_info, $ip_addr);
    $scan->execute();
    $scan->close();

    // Log biometric access
    $log = $conn->prepare(
        'INSERT INTO canteen_biometric_access_log (student_id, accessed_by, action, method, result)
         VALUES (?, ?, "verify", "facial", "success")'
    );
    $log->bind_param('ii', $student_id, $confirmed_by);
    $log->execute();
    $log->close();

    $conn->commit();
} catch (Throwable $e) {
    $conn->rollback();
    $conn->close();
    echo json_encode(['success' => false, 'message' => 'Confirmation failed. Please try again.']);
    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,
]);
