<?php
/**
 * API - Liste des buses
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json');

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

try {
    $conn = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $sql = "SELECT 
        b.id,
        b.matricule,
        COALESCE(l.name, 'Non assigné') as ligne_name,
        COALESCE(o.name, 'Non assigné') as operator_name
    FROM buses b
    LEFT JOIN lignes l ON b.id_ligne = l.ligne_code
    LEFT JOIN operators o ON b.id_operateur = o.id
    WHERE b.type = 'Bus' AND b.actif = 1
    ORDER BY b.matricule ASC";

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $buses = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($buses);
    
} catch (PDOException $e) {
    echo json_encode([
        'error' => $e->getMessage(),
        'errorInfo' => $e->getTraceAsString()
    ]);
}
