<?php
declare(strict_types=1);
namespace App;

use App\Core\View;

// HEADERS DE SEGURANÇA E CORS
header('Content-Type: text/html; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: no-referrer');
header('Permissions-Policy: geolocation=(self)');
header('Access-Control-Allow-Origin: *'); // Ajuste em produção
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

// Inicia sessão
session_start();

// Responder OPTIONS para CORS
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit();
}

// Tratamento global de erros
set_error_handler(static function ($severity, $message, $file, $line) {
    throw new \ErrorException($message, 0, $severity, $file, $line);
});

try {
    // Carregar roteador
    require_once __DIR__ . '/../app/Controllers/LoginController.php';
    require_once __DIR__ . '/../app/Controllers/EventsController.php';
    require_once __DIR__ . '/../app/Controllers/CurlController.php';
    require_once __DIR__ . '/../app/Controllers/QrcodeController.php';
    require_once __DIR__ . '/../app/Controllers/UserController.php';

    require_once __DIR__ . '/../app/Views/View.php';
    require_once __DIR__ . '/../app/Routes/Router.php';

    $router = new \App\Router();

    // =========================
    // ROTAS DE PÁGINAS
    // =========================

    // GET /eventos/ — verifica login e redireciona
    $router->add('GET', '/', function() {
        if (isset($_SESSION['token'])) {
            header('Location: /conteudo');
        } else {
            header('Location: /login');
        }
        exit;
    });

    // GET /eventos/login
    $router->add('GET', '/login', function() {
        View::render('login');
    });

    // POST /eventos/login
    $router->add('POST', '/login', function() {
        $loginController = new \App\Controllers\LoginController();
        $result = $loginController->doLogin();
        if ($result['success']) {
            $_SESSION['token'] = $result['data']['auth_token'];
            header('Location: /conteudo');
            exit;
        }
        View::render('login', ['erro' => $result['errors']['api'] ?? 'Usuário inválido']);
    });

    // GET /eventos/conteudo — somente logados
    $router->add('GET', '/conteudo', function() {
        if (!isset($_SESSION['token'])) {
            header('Location: /login');
            exit;
        }

        $eventsController = new \App\Controllers\EventsController();
        $result = $eventsController->getList();

        View::render('conteudo', [
            'token' => $_SESSION['token'],
            'events' => $result['data'] ?? [],
        ]);
    });

    // GET /eventos/logout — encerra sessão
    $router->add('GET', '/logout', function() {
        session_destroy();
        header('Location: /login');
        exit;
    });

    // =========================
    // ROTAS DE API
    // =========================
    $router->add('GET', '/api/ping', fn() => [
        'status' => 'success',
        'message' => 'pong',
        'time' => date('Y-m-d H:i:s')
    ]);

    $router->add('GET', '/api/qrcode', fn() => (new \App\Controllers\QrcodeController())->getQrcode());
    $router->add('GET', '/api/user/dados', fn() => (new \App\Controllers\UserController())->getUserData());

    // =========================
    // PROCESSAR REQUISIÇÃO
    // =========================
    $requestUri = $_SERVER['REQUEST_URI'] ?? '/';
    $requestMethod = $_SERVER['REQUEST_METHOD'] ?? 'GET';

    // Remove prefixo /eventos para roteamento interno
    $cleanUri = parse_url(preg_replace('#^/eventos#', '', $requestUri), PHP_URL_PATH) ?: '/';

    // Debug log (aparece no PHP-FPM error_log)
    error_log("DEBUG: URI=$requestUri | Clean=$cleanUri | Method=$requestMethod");

    $result = $router->dispatch($cleanUri, $requestMethod);

    if ($result === null) {
        http_response_code(404);
        echo "<h1>404 - Página não encontrada</h1>";
        exit;
    }

    // Se for array/objeto → retorna JSON (API)
    if (is_array($result) || is_object($result)) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }

} catch (\Exception $e) {
    http_response_code(500);
    echo "<h1>Erro interno do servidor</h1>";
    echo "<pre>" . htmlspecialchars($e->getMessage()) . "</pre>";
} catch (\Error $e) {
    http_response_code(500);
    echo "<h1>Erro fatal do servidor</h1>";
    echo "<pre>" . htmlspecialchars($e->getMessage()) . "</pre>";
}
