<?php
require_once __DIR__ . '/src/functions.php';
require_once __DIR__ . '/src/Router.php';

// Cargar controladores
require_once __DIR__ . '/src/controllers/AuthController.php';
require_once __DIR__ . '/src/controllers/DashboardController.php';
require_once __DIR__ . '/src/controllers/FriendsController.php';
require_once __DIR__ . '/src/controllers/InvitesController.php';
require_once __DIR__ . '/src/controllers/ProfileController.php';
require_once __DIR__ . '/src/controllers/PhotoController.php';
require_once __DIR__ . '/src/controllers/LikeController.php';
require_once __DIR__ . '/src/controllers/CommentController.php';
require_once __DIR__ . '/src/controllers/NotificationController.php';

session_start();

// Inicializar base de datos
if (!function_exists('init_db')) {
    function init_db() {
        global $DB;
        if (!isset($DB)) {
            try {
                $host = env('DB_HOST', 'localhost');
                $dbname = env('DB_NAME', 'thirty');
                $user = env('DB_USER', 'root');
                $pass = env('DB_PASS', '');
                
                $DB = new PDO(
                    "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
                    $user,
                    $pass,
                    [
                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
                    ]
                );
            } catch (PDOException $e) {
                http_response_code(500);
                die("Error de conexión a la base de datos");
            }
        }
        return $DB;
    }
}

init_db();

$router = new Thirty\Router();
require_once __DIR__ . '/src/routes.php';

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);

// Ajustar ruta si está en subdirectorio
$basePath = '/eventos';
if (strpos($path, $basePath) === 0) {
    $path = substr($path, strlen($basePath));
}

if ($path === '') {
    $path = '/';
}

$router->dispatch($method, $path);