<?php
/**
 * API PHP pour DTW Boumerdes - Pointage Bus
 * Endpoint: apidtw_buses_by_operator.php
 * 
 * Cette API récupère les buses d'un opérateur avec le nom de la ligne
 */

$db_host = 'localhost';
$db_name = 'transubd_PointageBus';
$db_user = 'transubd_transub_user';
$db_pass = 'Tr@nsub2@24';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

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

// Récupérer les paramètres
$operator_id = isset($_GET['operator_id']) ? intval($_GET['operator_id']) : 0;
$type = isset($_GET['type']) ? $_GET['type'] : null;

if ($operator_id == 0) {
    http_response_code(400);
    echo json_encode(['error' => 'operator_id requis']);
    exit;
}

try {
    $conn = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Construire la requête SQL
    $sql = "
        SELECT 
            b.id,
            b.code_bus,
            b.type,
            b.matricule,
            b.modele,
            b.id_ligne,
            b.actif,
            COALESCE(l.name, 'Non assigné') as ligne_name
        FROM buses b
        LEFT JOIN lignes l ON b.id_ligne = l.ligne_code
        WHERE b.id_operateur = :operator_id
    ";
    
    // Ajouter le filtre de type si spécifié
    if ($type !== null) {
        $sql .= " AND b.type = :type";
    }
    
    $sql .= " ORDER BY b.matricule ASC";
    
    $stmt = $conn->prepare($sql);
    
    // Binder les paramètres
    if ($type !== null) {
        $stmt->bindParam(':operator_id', $operator_id, PDO::PARAM_INT);
        $stmt->bindParam(':type', $type, PDO::PARAM_STR);
    } else {
        $stmt->bindParam(':operator_id', $operator_id, PDO::PARAM_INT);
    }
    
    $stmt->execute();
    
    $buses = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($buses);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
