<?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']) : '';
$siteID = isset($_POST['siteID']) ? trim($_POST['siteID']) : '';

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

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

$sql = "SELECT DISTINCT v.type, t.id_article, t.ttc, t.libelle
        FROM vehicules_circuits v
        LEFT JOIN tarifs_circuits t ON v.type = t.type
        WHERE v.id_operateur = ? AND v.SiteID = ?
        GROUP BY v.type
        ORDER BY v.type ASC";

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

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

$types = array();
while ($row = $result->fetch_assoc()) {
    $types[] = array(
        'type' => $row['type'],
        'id_article' => $row['id_article'],
        'ttc' => $row['ttc'],
        'libelle' => $row['libelle']
    );
}

sendResponse($types, true, 'Types récupérés avec succès');

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