<?php
require_once 'config.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(['success' => false, 'message' => 'POST requise']));
}

// Vérification token
$auth = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$token = trim(str_replace('Bearer ', '', $auth));
$payload = verifyToken($token);
if (!$payload) {
    http_response_code(401);
    die(json_encode(['success' => false, 'message' => 'Authentification requise']));
}

$data = json_decode(file_get_contents('php://input'), true) ?? [];

// Validation / assainissement (anti-XSS, injections)
$code_bus = filter_var(trim($data['code_bus'] ?? ''), FILTER_SANITIZE_STRING);
$type = filter_var($data['type'] ?? 'entree', FILTER_SANITIZE_STRING);

if (!$code_bus || !in_array($type, ['entree', 'sortie']) || strlen($code_bus) > 50) {
    http_response_code(400);
    die(json_encode(['success' => false, 'message' => 'Données invalides']));
}

// Rate limiting par IP + user
$key = $_SERVER['REMOTE_ADDR'] . '_' . $payload['user_id'];
if (!checkRateLimit($key)) {
    http_response_code(429);
    die(json_encode(['success' => false, 'message' => 'Trop de requêtes']));
}

$pdo = getPDO();

$stmt = $pdo->prepare("SELECT id FROM bus WHERE code_bus = ? AND actif = 1");
$stmt->execute([$code_bus]);
$bus = $stmt->fetch();

if (!$bus) {
    http_response_code(404);
    die(json_encode(['success' => false, 'message' => 'Bus non trouvé']));
}

$stmt = $pdo->prepare("INSERT INTO pointage (bus_id, id_utilisateur, type_pointage) VALUES (?, ?, ?)");
$stmt->execute([$bus['id'], $payload['user_id'], $type]);

logAction('SCAN', 'Success : ' . $code_bus, ['user_id' => $payload['user_id']]);

echo json_encode([
    'success' => true,
    'message' => ucfirst($type) . ' enregistrée'
]);
?>