<?php
require_once 'db_config.php';
require_once 'security.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Valider le token et appliquer rate limiting/whitelist
$auth = new ApiSecurity();
$tokenData = $auth->requireAuth(true);
header('X-RateLimit-Remaining: ' . ($auth->checkRateLimit()['remaining'] ?? 'unknown'));

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendError('Méthode non autorisée');
}

$id_operateur = isset($_POST['id_operateur']) ? trim($_POST['id_operateur']) : '';
$type = isset($_POST['type']) ? trim($_POST['type']) : '';
$siteID = isset($_POST['siteID']) ? trim($_POST['siteID']) : '';

if (empty($id_operateur) || empty($type) || empty($siteID)) {
    sendError('Paramètres requis manquants');
}

$conn = getConnectionPointage();
if (!$conn) {
    sendError('Erreur de connexion à la base de données');
}

$sql = "SELECT id, matricule, id_operateur, type, status, id_type_vehicule, SiteID 
        FROM vehicules_circuits 
        WHERE id_operateur = ? AND type = ? AND status = 'Active' AND SiteID = ?
        ORDER BY matricule ASC";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    sendError('Erreur de préparation de la requête');
}

$stmt->bind_param("iss", $id_operateur, $type, $siteID);
$stmt->execute();
$result = $stmt->get_result();

$matricules = array();
while ($row = $result->fetch_assoc()) {
    $matricules[] = array(
        'id' => $row['id'],
        'matricule' => $row['matricule'],
        'id_operateur' => $row['id_operateur'],
        'type' => $row['type'],
        'status' => $row['status'],
        'id_type_vehicule' => $row['id_type_vehicule'],
        'SiteID' => $row['SiteID']
    );
}

sendResponse($matricules, true, 'Matricules récupérés avec succès');

$stmt->close();
$conn->close();
?>