<?php
// public/index.php
// --- Error Logging Setup ---
$logDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'logs';
if (!is_dir($logDir)) {
    mkdir($logDir, 0777, true);
}
$logFile = $logDir . DIRECTORY_SEPARATOR . 'error.log';

// Log all errors to our file
ini_set('log_errors', 1);
ini_set('error_log', $logFile);
error_reporting(E_ALL);

// Catch uncaught exceptions
set_exception_handler(function ($e) use ($logFile) {
    $message = "[" . date("Y-m-d H:i:s") . "] [Exception] " . $e->getMessage() .
               " in " . $e->getFile() . ":" . $e->getLine() . "\n" .
               $e->getTraceAsString() . "\n\n";
    error_log($message, 3, $logFile);

    http_response_code(500);
    echo "<h1>500 Internal Server Error</h1><p>Something went wrong. Please check the logs.</p>";
});

// Catch fatal errors
register_shutdown_function(function () use ($logFile) {
    $error = error_get_last();
    if ($error !== null) {
        $message = "[" . date("Y-m-d H:i:s") . "] [Fatal Error] " .
                   $error['message'] . " in " . $error['file'] . ":" . $error['line'] . "\n\n";
        error_log($message, 3, $logFile);

        http_response_code(500);
        echo "<h1>500 Internal Server Error</h1><p>A fatal error occurred. Please check the logs.</p>";
    }
});

// --- Load the main framework bootstrap file ---
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'bootstrap.php';


// At this point, all core framework components and configurations are loaded.
// session_start() has been called within bootstrap.php.
// If $_GET['run_htaccess_check'] was true, the script would have exited already.

// --- Maintenance Mode Check ---
$isMaintenanceModeActive = $maintenanceConfig['enabled'];
$isBypassAttempt = (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], $maintenanceConfig['bypass_path']) !== false);
$hasBypassSession = (isset($_SESSION['maintenance_bypass']) && $_SESSION['maintenance_bypass'] === true);

// --- CORRECT URI CALCULATION ---
// This is the most reliable way to get the project's web root path.
// It works by deriving the project's root from the script's location.

// Get the full web path to the currently executed script (e.g., /CoreFlux/public/index.php)
$scriptName = $_SERVER['SCRIPT_NAME'];

// The project's web root is the parent directory of the 'public' folder.
$projectWebRootPath = dirname(dirname($scriptName));

// Normalize the project's web root path to ensure correct leading/trailing slashes.
if ($projectWebRootPath === '/' || $projectWebRootPath === '\\') {
    $projectWebRootPath = '/';
} else {
    $projectWebRootPath .= '/';
}

// Get the full request URI (e.g., /CoreFlux/about, /CoreFlux/public/assets/css/style.css)
$fullRequestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Trim the project's web root path from the full request URI to get the path for routing.
// This is the clean URI that your Router expects (e.g., "about", "posts/123", "api/v1/products").
$uri = trim(substr($fullRequestUri, strlen($projectWebRootPath)), '/');


// For debugging (uncomment to see path calculations):
// echo "Script Name: " . htmlspecialchars($scriptName) . "<br>";
// echo "Calculated Project Web Root Path: " . htmlspecialchars($projectWebRootPath) . "<br>";
// echo "Full Request URI: " . htmlspecialchars($fullRequestUri) . "<br>";
// echo "Trimmed URI (for routing): " . htmlspecialchars($uri) . "<br>";
// exit;

$isCurrentPathBypassPath = ($uri === ltrim($maintenanceConfig['bypass_path'], '/'));

// Check for excluded paths in maintenance mode
$isExcludedPath = false;

foreach ($maintenanceConfig['excluded_paths'] as $excludedPath) {
    if (strpos($uri, ltrim($excludedPath, '/')) === 0) {
        $isExcludedPath = true;
        break;
    }
}

// echo $isExcludedPath;

// --- Logic Flow for Maintenance Mode ---
if ($isMaintenanceModeActive) { // Only proceed if maintenance is ON
    if ($hasBypassSession) {
        // User has successfully bypassed maintenance, allow normal routing.
        // Do nothing here, script proceeds to regular routing below.
    } elseif ($isCurrentPathBypassPath) {
        // Maintenance is active, no bypass session, and user is requesting the bypass path.
        // This is where the bypass form should be displayed.
        $controller = new Core\Maintenance($maintenanceConfig); // Ensure this is Maintenance
        $controller->bypass(); // This method displays the form and calls exit().
    } elseif ($isExcludedPath) {
        // Maintenance is active, no bypass session, but user is requesting another excluded path.
        // This path will only be taken for EXCLUDED_PATHS *other than* the bypass path,
        // because the bypass path is handled in the elseif above.
        // Allow normal routing to continue for this specific excluded path.
        // Do nothing here, script proceeds to regular routing below.
    } else {
        // Maintenance is active, no bypass session, and not an excluded/bypass path.
        // Show the generic "Site Under Construction" page.
        $controller = new Core\Maintenance($maintenanceConfig); // Ensure this is Maintenance
        $controller->show(); // This method displays the generic page and calls exit().
    }
}


// --- Regular Routing Logic ---
$router = new Core\Router(); 
$router->loadRoutes(FS_APP_PATH . '/routes/web.php');

$config = require FS_CONFIG_PATH . DIRECTORY_SEPARATOR . 'app.php';

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

// Strip base path
$basePath = $config['base_path'] ?? '';
if ($basePath) {
    $uri = preg_replace('#^' . preg_quote($basePath, '#') . '#', '', $uri);
}

// Normalize
$uri = rtrim($uri, '/');
if ($uri === '') {
    $uri = '/';
}

$dispatchResult = $router->dispatch($uri, $_SERVER['REQUEST_METHOD']);
// use ;
// View::make('error/404')->with()->setLayout('error')->render();
// exit;
$appData = require FS_CONFIG_PATH . DIRECTORY_SEPARATOR . 'app.php';
$globalData = require FS_CONFIG_PATH . DIRECTORY_SEPARATOR . 'globalViewData.php';

\Core\View::setGlobalData(array_merge($appData, $globalData));

if ($dispatchResult) {
    list($controllerClass, $method, $params) = $dispatchResult;

    if (class_exists($controllerClass)) {
        $controllerInstance = new $controllerClass();

        if (method_exists($controllerInstance, $method)) {
            call_user_func_array([$controllerInstance, $method], $params);
        } else {
            // http_response_code(500); 
            // echo "<h1>500 Internal Server Error</h1>";
            // echo "<p>Method '{$method}' not found in controller {$controllerClass}.</p>";

            Core\Response::abort(500);
        }
    } else {
        // http_response_code(500); 
        // echo "<h1>500 Internal Server Error</h1>";
        // echo "<p>Controller class '{$controllerClass}' not found.</p>";
        Core\Response::abort(500);
    }
} else {
    // http_response_code(404);
    // echo "<h1>404 Not Found</h1>";
    // echo "<p>The requested page '{$uri}' could not be found.</p>";

    // if (isset($router->routes[$_SERVER['REQUEST_METHOD']])) {
    //     echo "<pre>Available routes: " . print_r(array_keys($router->routes[$_SERVER['REQUEST_METHOD']]), true) . "</pre>";
    // }
    echo $dispatchResult;
    Core\Response::abort(404);
}

?>