<?php
/**
 * Bus Check-in API - Unified Router (Pointage Only)
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

// Chargement du fichier .env manuellement
if (file_exists(__DIR__ . '/.env')) {
    $lines = file(__DIR__ . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        list($name, $value) = explode('=', $line, 2);
        $name = trim($name);
        $value = trim($value);
        if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
            putenv(sprintf('%s=%s', $name, $value));
            $_ENV[$name] = $value;
            $_SERVER[$name] = $value;
        }
    }
}

// Activer le rapport d'erreurs pour le debug (à désactiver en production)
error_reporting(E_ALL);
ini_set('display_errors', 0); // Ne pas afficher sur la sortie standard (JSON)
ini_set('log_errors', 1); // Loguer dans error_log du cPanel

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

// Chargement des helpers et middleware
require_once 'middleware/Auth.php';
require_once 'middleware/InputValidator.php';

// Chargement de la configuration
$databaseConfig = require_once 'config/database_secure.php';
define('DB_HOST', getenv('DB_HOST') ?: $databaseConfig['DB_HOST']);
define('DB_NAME', getenv('DB_NAME') ?: $databaseConfig['DB_NAME']);
define('DB_USER', getenv('DB_USER') ?: $databaseConfig['DB_USER']);
define('DB_PASS', getenv('DB_PASS') ?: $databaseConfig['DB_PASS']);

try {
    $db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec("set names utf8");
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'Erreur de connexion à la base de données',
        'error' => $e->getMessage() // À masquer en production si nécessaire
    ]);
    exit;
}

// Routage basé sur PATH_INFO
$pathInfo = $_SERVER['PATH_INFO'] ?? '';
$pathParts = explode('/', trim($pathInfo, '/'));
$controllerName = $pathParts[0] ?? '';
$actionName = $pathParts[1] ?? '';

// Gestion des routes avec capture d'erreurs
try {
    switch ($controllerName) {
        case 'auth':
            require_once 'controllers/AuthController.php';
            $controller = new AuthController($db);
            if ($actionName === 'login') $controller->login();
            elseif ($actionName === 'logout') $controller->logout();
            elseif ($actionName === 'verify') $controller->verifyToken();
            elseif ($actionName === 'profile') $controller->getProfile();
            else echo json_encode(['success' => false, 'message' => 'Action Auth invalide']);
            break;

        case 'buses':
            require_once 'controllers/BusController.php';
            $controller = new BusController($db);
            if ($actionName === 'scan') $controller->scanQR();
            elseif ($actionName === 'list') $controller->getAll();
            elseif ($actionName === 'get') $controller->getById($pathParts[2] ?? 0);
            else echo json_encode(['success' => false, 'message' => 'Action Bus invalide']);
            break;

        case 'dashboard':
            require_once 'controllers/DashboardController.php';
            $controller = new DashboardController($db);
            if ($actionName === 'stats') $controller->getSummary();
            elseif ($actionName === 'report') $controller->getDailyReport();
            elseif ($actionName === 'absent') $controller->getAbsentBuses();
            elseif ($actionName === 'operators') $controller->getOperatorStats();
            elseif ($actionName === 'lines') $controller->getLineStats();
            else echo json_encode(['success' => false, 'message' => 'Action Dashboard invalide']);
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Route non trouvée: ' . $controllerName]);
            break;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Erreur fatale lors de l\'exécution de la requête',
        'error' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine()
    ]);
} catch (Error $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Erreur système critique',
        'error' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine()
    ]);
}