<?php
/**
 * Validate a student identity QR token (Type 1 — fee desk only).
 * POST: token
 * Returns: student_id, name, class_name, photo_url, student_code, outstanding_fees[]
 * Rate limit: 10 requests / 5 seconds / IP
 */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

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

// ── Auth ──────────────────────────────────────────────────────────────────────
if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Not authenticated.']);
    exit;
}
canteen_require_role(['admin', 'headteacher', 'accountant', 'cashier', 'registrar'], true);
canteen_require_active();

// ── Rate limit: 10 requests / 5 seconds / IP ─────────────────────────────────
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
if (!canteen_rate_limit('identity_' . $ip, 10, 5)) {
    http_response_code(429);
    echo json_encode(['success' => false, 'message' => 'Too many requests. Please slow down.']);
    exit;
}

// ── Input ─────────────────────────────────────────────────────────────────────
$token = trim((string) ($_POST['token'] ?? ''));
if ($token === '') {
    echo json_encode(['success' => false, 'message' => 'No token provided.']);
    exit;
}

// ── Validate token or manual student_id lookup ────────────────────────────────
$student_db_id = false;

if (str_starts_with($token, '__MANUAL__')) {
    // Manual 5-digit Student ID fallback
    $manual_code   = trim(substr($token, 10));
    $conn          = getDBConnection();
    $lookup        = $conn->prepare("SELECT id FROM students WHERE student_id = ? AND status = 'active' LIMIT 1");
    $lookup->bind_param('s', $manual_code);
    $lookup->execute();
    $lrow          = $lookup->get_result()->fetch_assoc();
    $lookup->close();
    $student_db_id = $lrow ? (int) $lrow['id'] : false;
    if ($student_db_id === false) {
        echo json_encode(['success' => false, 'message' => 'Student ID not found.']);
        exit;
    }
} elseif (str_starts_with($token, '__BYID__')) {
    // Direct lookup by internal database ID (used after biometric identification)
    $db_id = (int) trim(substr($token, 8));
    $student_db_id = $db_id > 0 ? $db_id : false;
    if ($student_db_id === false) {
        echo json_encode(['success' => false, 'message' => 'Invalid ID.']);
        exit;
    }
} else {
    $student_db_id = canteen_validate_identity_token($token);
    if ($student_db_id === false) {
        echo json_encode(['success' => false, 'message' => 'Invalid or unrecognised QR code.']);
        exit;
    }
}

// ── Fetch student record ──────────────────────────────────────────────────────
$conn = getDBConnection();

$stmt = $conn->prepare(
    "SELECT id, student_id, first_name, last_name, class, section, photo_path, phone
     FROM students
     WHERE id = ? AND status = 'active'
     LIMIT 1"
);
$stmt->bind_param('i', $student_db_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

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

// ── Build photo URL ───────────────────────────────────────────────────────────
$photo_url = '';
if (!empty($student['photo_path'])) {
    $photo_url = rtrim(BASE_URL, '/') . '/' . ltrim($student['photo_path'], '/');
} else {
    $photo_url = rtrim(BASE_URL, '/') . '/assets/img/student_placeholder.png';
}

// ── Outstanding fees for this student's class ─────────────────────────────────
$class        = $student['class'];
$academic_year = getAcademicYear();

$fee_rows = rbcStudentFeeBreakdown($conn, $student_db_id, $class, $academic_year);

$outstanding_fees = [];
foreach ($fee_rows as $row) {
    if ($row['remaining'] <= 0.005) {
        continue;
    }
    $outstanding_fees[] = [
        'fee_structure_id' => $row['id'],
        'fee_type'         => $row['fee_type'],
        'amount'           => $row['amount'],
        'paid'             => $row['paid'],
        'remaining'        => $row['remaining'],
        'is_feeding'       => $row['is_feeding'],
    ];
}

echo json_encode([
    'success'          => true,
    'student_id'       => (int) $student['id'],
    'student_code'     => $student['student_id'],
    'name'             => $student['first_name'] . ' ' . $student['last_name'],
    'class_name'       => $student['class'] . ($student['section'] ? ' ' . $student['section'] : ''),
    'photo_url'        => $photo_url,
    'phone'            => $student['phone'] ?? '',
    'outstanding_fees' => $outstanding_fees,
]);
