<?php
/**
 * Manual canteen override — requires PIN + student lookup.
 * POST: pin, search (student name or 5-digit ID), reason, session_id
 */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

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;
}

if (!canteen_rate_limit('canteen_override_' . md5($_SERVER['REMOTE_ADDR'] ?? ''), 5, 60)) {
    http_response_code(429);
    echo json_encode(['success' => false, 'message' => 'Too many override attempts.']);
    exit;
}

$pin        = trim((string)($_POST['pin']        ?? ''));
$search     = trim((string)($_POST['search']     ?? ''));
$reason     = trim((string)($_POST['reason']     ?? 'other'));
$session_id = (int)($_POST['session_id'] ?? 0);

$allowed_reasons = ['qr_damaged', 'phone_flat', 'late_payment', 'other'];
if (!in_array($reason, $allowed_reasons, true)) $reason = 'other';

if ($pin === '' || $search === '' || $session_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'PIN, student, and session are required.']);
    exit;
}

$conn     = getDBConnection();
$settings = canteen_get_settings();
$hash     = $settings['scanner_pin_hash'] ?? '';

if ($hash === '' || !password_verify($pin, $hash)) {
    echo json_encode(['success' => false, 'message' => 'Incorrect PIN.']);
    $conn->close();
    exit;
}

// Find student by student_id code or name
$stmt = $conn->prepare(
    "SELECT id, first_name, last_name, class, student_id AS student_code
     FROM students
     WHERE status = 'active' AND (student_id = ? OR CONCAT(first_name,' ',last_name) LIKE ?)
     LIMIT 1"
);
$like = '%' . $search . '%';
$stmt->bind_param('ss', $search, $like);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$student) {
    echo json_encode(['success' => false, 'message' => 'Student not found.']);
    $conn->close();
    exit;
}

$student_id   = (int)$student['id'];
$student_name = trim($student['first_name'] . ' ' . $student['last_name']);
$actor_id     = $is_role_session ? (int)$_SESSION['user_id'] : 0;
$now          = date('Y-m-d H:i:s');

// Check if already confirmed today
$chk = $conn->prepare(
    "SELECT id FROM canteen_scans WHERE session_id = ? AND student_id = ? AND scan_result = 'success' LIMIT 1"
);
$chk->bind_param('ii', $session_id, $student_id);
$chk->execute();
$already = $chk->get_result()->fetch_assoc();
$chk->close();

if ($already) {
    echo json_encode(['success' => false, 'message' => 'Student already confirmed for this session.']);
    $conn->close();
    exit;
}

// Upsert entitlement (create if missing, mark confirmed)
$conn->begin_transaction();
try {
    // Find or create entitlement
    $ent = $conn->prepare(
        "SELECT id, status FROM canteen_entitlements WHERE session_id = ? AND student_id = ? LIMIT 1"
    );
    $ent->bind_param('ii', $session_id, $student_id);
    $ent->execute();
    $entRow = $ent->get_result()->fetch_assoc();
    $ent->close();

    $entitlement_id = 0;
    if ($entRow) {
        $entitlement_id = (int)$entRow['id'];
        $upd = $conn->prepare(
            "UPDATE canteen_entitlements SET status = 'confirmed', confirmed_at = ?,
             verification_method = 'manual_id', confirmed_by = ? WHERE id = ?"
        );
        $upd->bind_param('sii', $now, $actor_id, $entitlement_id);
        $upd->execute();
        $upd->close();
    } else {
        // Create entitlement on the fly
        $token = canteen_generate_session_token($student_id, $session_id);
        $exp   = date('Y-m-d') . ' 23:59:59';
        $ins = $conn->prepare(
            "INSERT INTO canteen_entitlements (student_id, session_id, qr_token, qr_token_expires_at, status, confirmed_at)
             VALUES (?, ?, ?, ?, 'confirmed', ?)"
        );
        $ins->bind_param('iisss', $student_id, $session_id, $token, $exp, $now);
        $ins->execute();
        $entitlement_id = (int)$conn->insert_id;
        $ins->close();
    }

    $scan = $conn->prepare(
        "INSERT INTO canteen_scans (session_id, student_id, entitlement_id, scan_result, override_reason, verification_method, scanned_by)
         VALUES (?, ?, ?, 'manual_override', ?, 'manual_id', ?)"
    );
    $scan->bind_param('iiisi', $session_id, $student_id, $entitlement_id, $reason, $actor_id);
    $scan->execute();
    $scan->close();

    $conn->commit();
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    $conn->close();
    exit;
}

logActivity($conn, $actor_id, 'canteen_manual_override',
    "Session #{$session_id} | Student: {$student_name} | Reason: {$reason}");

echo json_encode(['success' => true, 'student_name' => $student_name]);
$conn->close();
