<?php
session_start();

require_once '../app/Config/config.php';
require_once '../app/Core/Session.php';
require_once '../vendor/autoload.php';
require_once '../app/config/routes.php';



// Autoload Controllers, Models, Core, Helpers, Libraries
spl_autoload_register(function($class) {
    $class = str_replace('App\\', '', $class);  // Remove o namespace 'App'
    $paths = [
        '../app/Controllers/' . $class . '.php',
        '../app/Models/' . $class . '.php',
        '../app/Core/' . $class . '.php',
        '../app/Helpers/' . $class . '.php',
        '../app/Libraries/' . $class . '.php',
    ];
    foreach ($paths as $file) {
        if (file_exists($file)) {
            require_once $file;
            return;
        }
    }
});


// Captura URL amigável (exemplo: usuarios/login)
$url = $_GET['url'] ?? 'usuarios/login';
$url = rtrim($url, '/');
$url = explode('/', $url);

// Controller, método e parâmetros
$controllerName = ucfirst($url[0]) . 'Controller';
$action = $url[1] ?? 'index';
$params = array_slice($url, 2);

try {
    if (class_exists($controllerName)) {
        $controller = new $controllerName();
        if (method_exists($controller, $action)) {
            call_user_func_array([$controller, $action], $params);
        } else {
            throw new Exception("Método '$action' não encontrado em $controllerName.");
        }
    } else {
        throw new Exception("Controller '$controllerName' não encontrado.");
    }
} catch (Exception $e) {
    // Layout simples para erros
    ?>
    <!DOCTYPE html>
    <html lang="pt-br">
    <head>
        <meta charset="UTF-8">
        <title>Erro - <?= APP_NOME ?></title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.2.1/dist/css/bootstrap.min.css">
    </head>
    <body>
    <div class="container mt-5">
        <div class="alert alert-danger">
            <h3>Erro!</h3>
            <p><?= htmlspecialchars($e->getMessage()) ?></p>
        </div>
    </div>
    </body>
    </html>
    <?php
}
