<?php
namespace App\Core;

use App\Shared\Helpers\MetricCollector;

class Router
{
    private static function handleCors()
    {
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');
        }

        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
            }
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
            }
            exit(0);
        }
    }

    public static function dispatch()
    {
        MetricCollector::clear();
        self::handleCors();
        
        $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
        $host = $_SERVER['HTTP_HOST'];
        
        $script_dir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
        $base_dir = str_replace('/public', '', $script_dir);
        $base_dir = rtrim($base_dir, '/');

        if(!defined('BASE_URL')){
            define('BASE_URL', $protocol . "://" . $host . ($base_dir ?: ''));
        }

        $request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

        if ($base_dir !== '' && strpos($request_uri, $base_dir) === 0) {
            $path = substr($request_uri, strlen($base_dir));
        } else {
            $path = $request_uri;
        }

        $url = trim($path, '/');

        $parts = explode('/', $url);
        $mod = !empty($parts[0]) ? ucfirst($parts[0]) : 'Auth';
        $act = $parts[1] ?? 'index';
        $params = array_slice($parts, 2);

        $ctrlClass = 'App\\Modules\\' . $mod . '\\Controllers\\' . $mod . 'Controller';
        if (!class_exists($ctrlClass)) {
            http_response_code(404);
            die('Modulo nao encontrado');
        }
        $ctrl = new $ctrlClass();
        if (property_exists($ctrl, 'middleware')) {
            foreach ($ctrl->middleware as $m) {
                (new $m())->handle();
            }
        }
        
        if (!method_exists($ctrl, $act)) {
            http_response_code(404);
            die('Acao nao encontrada');
        }

        call_user_func_array([$ctrl, $act], $params);
    }
}