<?php
/**
 * Store a MediaPipe facial descriptor after enrollment.
 * POST: student_id, descriptor (JSON string of 468-point landmark array)
 * Auth: admin / headteacher only
 */
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();
canteen_require_role(['admin', 'headteacher'], true);

$student_id     = (int)($_POST['student_id']   ?? 0);
$descriptor_raw = trim($_POST['descriptor']    ?? '');

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

// Validate descriptor is valid JSON array
$descriptor = json_decode($descriptor_raw, true);
if (!is_array($descriptor) || count($descriptor) < 100) {
    echo json_encode(['success' => false, 'message' => 'Invalid descriptor format.']);
    exit;
}

// Re-encode as clean JSON (strip any injected keys etc.)
$clean_descriptor = json_encode(array_values(array_map(function ($pt) {
    if (is_array($pt)) {
        return [
            'x' => (float)($pt['x'] ?? 0),
            'y' => (float)($pt['y'] ?? 0),
            'z' => (float)($pt['z'] ?? 0),
        ];
    }
    return (float)$pt;
}, $descriptor)));

$conn = getDBConnection();

// Verify student exists
$chk = $conn->prepare('SELECT id, first_name, last_name FROM students WHERE id = ? LIMIT 1');
$chk->bind_param('i', $student_id);
$chk->execute();
$student = $chk->get_result()->fetch_assoc();
$chk->close();

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

$now         = date('Y-m-d H:i:s');
$enrolled_by = (int)($_SESSION['user_id'] ?? 0);

$stmt = $conn->prepare(
    'INSERT INTO canteen_biometric_credentials (student_id, facial_descriptor, facial_enrolled_at, enrolled_by)
     VALUES (?, ?, ?, ?)
     ON DUPLICATE KEY UPDATE
       facial_descriptor   = VALUES(facial_descriptor),
       facial_enrolled_at  = VALUES(facial_enrolled_at),
       enrolled_by         = VALUES(enrolled_by)'
);
$stmt->bind_param('issi', $student_id, $clean_descriptor, $now, $enrolled_by);
$stmt->execute();
$stmt->close();

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

logActivity($conn, $enrolled_by, 'canteen_facial_enroll',
    'Facial descriptor enrolled for student #' . $student_id .
    ' (' . $student['first_name'] . ' ' . $student['last_name'] . ')');

$conn->close();

echo json_encode([
    'success' => true,
    'message' => 'Facial data enrolled for ' . $student['first_name'] . ' ' . $student['last_name'] . '.',
]);
