<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");
error_log("Proxy entry: " . ($_SERVER['REQUEST_METHOD'] ?? 'UNKNOWN') . " " . ($_GET['endpoint'] ?? 'no-endpoint'));

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

// En local, utiliser les fichiers API locaux sans authentification
$host = $_SERVER['HTTP_HOST'] ?? '';
$isLocal = in_array($host, ['localhost', '127.0.0.1']);

// Mode local: utiliser les fichiers API locaux (apiggr/Includes)
$endpoint = isset($_GET['endpoint']) ? trim($_GET['endpoint']) : '';
if ($endpoint === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'endpoint manquant']);
    exit;
}
// endpoint est déjà du type "Includes/Tables/Bus_api.php"
$localFile = __DIR__ . '/' . $endpoint;

// Robustesse: essayer d'ajouter .php si non trouvé
if (!file_exists($localFile) && !empty($endpoint)) {
    if (file_exists($localFile . '.php')) {
        $localFile .= '.php';
    } else {
        // Essayer dans le dossier Includes/
        $includesFile = __DIR__ . '/Includes/' . $endpoint;
        if (file_exists($includesFile)) {
            $localFile = $includesFile;
        } elseif (file_exists($includesFile . '.php')) {
            $localFile = $includesFile . '.php';
        }
    }
}

if (file_exists($localFile)) {
    // Pour les appels locaux, ne pas inclure auth_check.php
    include $localFile;
    exit;
} else {
    http_response_code(404);
    echo json_encode(['success' => false, 'message' => 'Fichier API non trouvé: ' . $endpoint]);
    exit;
}