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

// Turn on error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

// Simple autoloader
spl_autoload_register(function ($class) {
    // Convert namespace to file path
    $class = str_replace('App\\', '', $class);
    $class = str_replace('\\', '/', $class);
    $file = APP_PATH . '/' . $class . '.php';
    
    if (file_exists($file)) {
        require_once $file;
    }
});

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

// Set timezone
date_default_timezone_set(APP_TIMEZONE);

// Start session
session_name(SESSION_NAME);
session_start();

// Simple routing
$request_uri = $_SERVER['REQUEST_URI'];
$script_name = $_SERVER['SCRIPT_NAME'];
$base_path = str_replace('index.php', '', $script_name);

// Remove base path and query string
$uri = str_replace($base_path, '', $request_uri);
if (($pos = strpos($uri, '?')) !== false) {
    $uri = substr($uri, 0, $pos);
}
$uri = trim($uri, '/');

// Define routes
$routes = [
    '' => ['controller' => 'AuthController', 'action' => 'showLogin'],
    'login' => ['controller' => 'AuthController', 'action' => 'showLogin'],
    'login-post' => ['controller' => 'AuthController', 'action' => 'login', 'method' => 'POST'],
    'logout' => ['controller' => 'AuthController', 'action' => 'logout'],
    'dashboard' => ['controller' => 'DashboardController', 'action' => 'index'],
    'migrants/create' => ['controller' => 'MigrantController', 'action' => 'create'],
    'migrants/store' => ['controller' => 'MigrantController', 'action' => 'store', 'method' => 'POST'],
    'migrants/search' => ['controller' => 'MigrantController', 'action' => 'search'],
    'profile' => ['controller' => 'ProfileController', 'action' => 'index'],
    'profile/update' => ['controller' => 'ProfileController', 'action' => 'update', 'method' => 'POST'],
];

// Check for dynamic routes
if (preg_match('/migrants\/([^\/]+)$/', $uri, $matches)) {
    $_GET['id'] = $matches[1];
    $route_key = 'migrants/show';
} elseif (preg_match('/migrants\/([^\/]+)\/edit$/', $uri, $matches)) {
    $_GET['id'] = $matches[1];
    $route_key = 'migrants/edit';
} elseif (preg_match('/migrants\/([^\/]+)\/submit$/', $uri, $matches)) {
    $_GET['id'] = $matches[1];
    $route_key = 'migrants/submit';
} elseif (preg_match('/migrants\/([^\/]+)\/review$/', $uri, $matches)) {
    $_GET['id'] = $matches[1];
    $route_key = 'migrants/review';
} else {
    $route_key = $uri;
}

// Simple route dispatcher
try {
    $method = $_SERVER['REQUEST_METHOD'];
    
    if (isset($routes[$route_key])) {
        $route = $routes[$route_key];
        
        // Check method
        if (isset($route['method']) && $route['method'] !== $method) {
            throw new Exception('Method not allowed', 405);
        }
        
        $controller_name = 'App\\Controllers\\' . $route['controller'];
        $action = $route['action'];
        
        if (class_exists($controller_name)) {
            $controller = new $controller_name();
            if (method_exists($controller, $action)) {
                $controller->$action();
                exit;
            }
        }
    }
    
    // If no route found
    header("HTTP/1.0 404 Not Found");
    echo "<h1>404 Not Found</h1>";
    echo "<p>The requested URL was not found on this server.</p>";
    echo "<p><a href='/nis-migrant-ereg/'>Go to Home</a></p>";
    
} catch (Exception $e) {
    header("HTTP/1.0 500 Internal Server Error");
    echo "<h1>500 Internal Server Error</h1>";
    echo "<p>" . $e->getMessage() . "</p>";
}