<?php
/**
 * NIGERIA IMMIGRATION SERVICE - MIGRANT e-REGISTRATION
 * Front Controller - LIVE SERVER FIXED VERSION
 */

// Start output buffering
ob_start();

// Start session with secure settings for live server
ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1);
session_start();

// Define base paths
define('BASE_PATH', __DIR__);
define('APP_PATH', BASE_PATH . '/app');
define('CONFIG_PATH', BASE_PATH . '/config');
define('PUBLIC_PATH', BASE_PATH . '/public');
define('STORAGE_PATH', BASE_PATH . '/storage');

// Load configuration
require_once CONFIG_PATH . '/app.php';
require_once CONFIG_PATH . '/database.php';
require_once CONFIG_PATH . '/security.php';

// Set timezone
date_default_timezone_set(APP_TIMEZONE);

// Error handling for live server
if (defined('APP_DEBUG') && APP_DEBUG) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', STORAGE_PATH . '/logs/error.log');
}

/**
 * FIXED AUTOLOADER FOR LIVE SERVER
 * Handles namespace to file path conversion correctly
 */
spl_autoload_register(function ($class) {
    // Remove the root namespace (App\) if present
    if (strpos($class, 'App\\') === 0) {
        $class = substr($class, 4);
    }
    
    // Convert namespace separators to directory separators
    $class = str_replace('\\', '/', $class);
    
    // Map namespaces to directories
    $paths = [
        APP_PATH . '/core/' . basename($class) . '.php',      // For Core classes: Controller.php, Request.php
        APP_PATH . '/controllers/' . basename($class) . '.php', // For Controller classes: AuthController.php
        APP_PATH . '/models/' . basename($class) . '.php',    // For Model classes: User.php
        APP_PATH . '/' . $class . '.php',                      // Direct path
    ];
    
    // For Core namespace specifically
    if (strpos($class, 'Core/') === 0) {
        $className = str_replace('Core/', '', $class);
        $paths[] = APP_PATH . '/core/' . $className . '.php';
    }
    
    // For Controllers namespace specifically
    if (strpos($class, 'Controllers/') === 0) {
        $className = str_replace('Controllers/', '', $class);
        $paths[] = APP_PATH . '/controllers/' . $className . '.php';
    }
    
    // Try each path
    foreach ($paths as $file) {
        if (file_exists($file)) {
            require_once $file;
            return true;
        }
    }
    
    // If still not found, try direct mapping for common classes
    $directMappings = [
        'Core/Controller' => APP_PATH . '/core/Controller.php',
        'Core/Model' => APP_PATH . '/core/Model.php',
        'Core/Request' => APP_PATH . '/core/Request.php',
        'Core/Response' => APP_PATH . '/core/Response.php',
        'Core/Router' => APP_PATH . '/core/Router.php',
        'Controllers/AuthController' => APP_PATH . '/controllers/AuthController.php',
        'Controllers/DashboardController' => APP_PATH . '/controllers/DashboardController.php',
        'Controllers/MigrantController' => APP_PATH . '/controllers/MigrantController.php',
        'Controllers/UserController' => APP_PATH . '/controllers/UserController.php',
    ];
    
    if (isset($directMappings[$class])) {
        $file = $directMappings[$class];
        if (file_exists($file)) {
            require_once $file;
            return true;
        }
    }
    
    // Log error for debugging
    error_log("Autoloader failed to load: $class");
    return false;
});

// Load helpers
if (file_exists(APP_PATH . '/helpers/Helpers.php')) {
    require_once APP_PATH . '/helpers/Helpers.php';
}

// MANUALLY LOAD CORE CLASSES FIRST (critical for live server)
$coreClasses = [
    'Request' => APP_PATH . '/core/Request.php',
    'Response' => APP_PATH . '/core/Response.php',
    'Controller' => APP_PATH . '/core/Controller.php',
    'Model' => APP_PATH . '/core/Model.php',
    'Router' => APP_PATH . '/core/Router.php',
];

foreach ($coreClasses as $name => $file) {
    if (file_exists($file)) {
        require_once $file;
    } else {
        error_log("Core class file not found: $file");
    }
}

// Get the URL from query string (from .htaccess rewrite)
$url = isset($_GET['url']) ? $_GET['url'] : '';

// Log for debugging (remove in production)
error_log("Index.php - URL from GET: " . ($url ?: 'ROOT'));

// Clean the URL
$url = rtrim($url, '/');
$url = filter_var($url, FILTER_SANITIZE_URL);

// Split into parts
$urlParts = empty($url) ? [] : explode('/', $url);

// Load routes - this creates the $router object
$routesFile = BASE_PATH . '/routes/web.php';
if (!file_exists($routesFile)) {
    die("Error: Routes file not found at: " . $routesFile);
}
require_once $routesFile;

// Check if router was created
if (!isset($router) || !($router instanceof App\Core\Router)) {
    // Try to create router if not set
    if (class_exists('App\Core\Router')) {
        $router = new App\Core\Router();
        error_log("Router created manually");
    } else {
        die("Error: Router not properly initialized in routes/web.php");
    }
}

// Dispatch request
try {
    $router->dispatch($_SERVER['REQUEST_METHOD'], $urlParts);
} catch (Exception $e) {
    error_log("Dispatch error: " . $e->getMessage());
    error_log("Stack trace: " . $e->getTraceAsString());
    
    if (defined('APP_DEBUG') && APP_DEBUG) {
        echo "<h1>Application Error</h1>";
        echo "<p><strong>Message:</strong> " . $e->getMessage() . "</p>";
        echo "<p><strong>File:</strong> " . $e->getFile() . ":" . $e->getLine() . "</p>";
        echo "<h3>Stack Trace:</h3>";
        echo "<pre>" . $e->getTraceAsString() . "</pre>";
    } else {
        header("HTTP/1.0 500 Internal Server Error");
        $errorFile = APP_PATH . '/views/errors/500.php';
        if (file_exists($errorFile)) {
            include $errorFile;
        } else {
            echo "500 Internal Server Error";
        }
    }
}

// Flush output buffer
ob_end_flush();