<?php
// Main API Entry Point

// Load Config
require_once 'config/settings.php';
require_once 'config/database.php';
require_once 'helpers/Response.php';
require_once 'config/jwt.php';

try {
    // Connect to Database
    $database = new Database();
    $db = $database->getConnection();

    // Router Logic
    $route = isset($_GET['route']) ? $_GET['route'] : '';
    $route = rtrim($route, '/');
    $routeParts = explode('/', $route);

    // Default Controller/Action
    $controllerName = 'Home';
    $actionName = 'index';

    if (!empty($routeParts[0])) {
        // Convention: route=controller/action
        // e.g. auth/register -> AuthController->register()
        // e.g. users -> UserController->index() (if implemented)

        // Capitalize first letter to match Class naming convention
        // e.g. auth -> Auth
        $controllerName = ucfirst($routeParts[0]) . 'Controller';

        if (isset($routeParts[1])) {
            $actionName = $routeParts[1];
        }
    }

    // Controller File Path
    $controllerPath = 'controllers/' . $controllerName . '.php';

    if (file_exists($controllerPath)) {
        require_once $controllerPath;

        // Check if class exists
        if (class_exists($controllerName)) {
            $controller = new $controllerName($db);

            // Check if action exists
            if (method_exists($controller, $actionName)) {
                $controller->{$actionName}();
            } else {
                // Action not found
                Response::error("Ação '$actionName' não encontrada em '$controllerName'.", 404);
            }
        } else {
            // Class not found
            Response::error("Classe do controlador '$controllerName' não encontrada.", 404);
        }
    } else {
        // File not found
        Response::error("Endpoint não encontrado.", 404);
    }
} catch (Throwable $e) {
    Response::error("Erro interno do servidor: " . $e->getMessage(), 500);
}

?>