<?php
/**
 * API - Liste complète des buses
 */

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

$logfile = '/tmp/api_debug.log';
file_put_contents($logfile, "Start: " . date('Y-m-d H:i:s') . "\n");

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

try {
    file_put_contents($logfile, "Connecting to DB...\n", FILE_APPEND);
    
    $conn = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    file_put_contents($logfile, "Connected. Running query...\n", FILE_APPEND);
    
    $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->query($sql);
    $buses = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    file_put_contents($logfile, "Found: " . count($buses) . " buses\n", FILE_APPEND);
    
    header('Content-Type: application/json');
    echo json_encode($buses);
    
} catch (Exception $e) {
    file_put_contents($logfile, "Error: " . $e->getMessage() . "\n", FILE_APPEND);
    header('Content-Type: application/json');
    echo json_encode(['error' => $e->getMessage()]);
}
