<?php
/**
 * API pour la gestion des Bus
 * Répertoire: Includes/Tables/
 * Sécurisée avec authentification
 */

// Configuration API distante
$REMOTE_API_BASE = "https://api.transub.dz/apiggr";

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$siteFilter = $_GET['site'] ?? null;

require_once __DIR__ . '/../../../config/database.php';

try {
    $db = Database::getInstance();

    if ($method === 'GET') {
        if ($action === 'list') {
            $query = "SELECT * FROM BusGares WHERE 1=1";
            $params = [];

            // Filtrer par SiteID (GR01, GR05, etc.)
            if ($siteFilter && $siteFilter !== 'Siège') {
                $query .= " AND Site = ?";
                $params[] = $siteFilter;
            }

            $query .= " ORDER BY BusID";
            $result = $db->select($query, $params);
            
            echo json_encode(['success' => true, 'data' => $result]);
            exit;
        }

        if ($action === 'get' && isset($_GET['id'])) {
            $query = "SELECT * FROM BusGares WHERE BusID = ?";
            $result = $db->selectOne($query, [$_GET['id']]);
            
            echo json_encode(['success' => true, 'data' => $result]);
            exit;
        }

        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Action GET invalide']);
        exit;
    }

    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Méthode non supportée']);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erreur API Bus: ' . $e->getMessage()]);
}