<?php
date_default_timezone_set('Africa/Dar_es_Salaam');
define("DS", DIRECTORY_SEPARATOR);
define("ROOT", dirname(__FILE__));

require_once(ROOT . DS . 'config' . DS . 'config.php');
require_once(ROOT . DS . 'app' . DS . 'lib' . DS . 'helpers' . DS . 'functions.php');

function pacific_autoload($class_name) {
    $paths = [
        ROOT . DS . 'core'        . DS . $class_name . '.php',
        ROOT . DS . 'app' . DS . 'controllers' . DS . $class_name . '.php',
        ROOT . DS . 'app' . DS . 'models'      . DS . $class_name . '.php',
        ROOT . DS . 'app' . DS . 'lib'         . DS . $class_name . '.php',
    ];
    foreach ($paths as $p) {
        if (file_exists($p)) { require_once($p); return; }
    }
}
spl_autoload_register('pacific_autoload');

// ---- Session hardening (must run BEFORE session_start) ----
ini_set('session.use_strict_mode', '1');
ini_set('session.cookie_httponly',  '1');
ini_set('session.cookie_samesite',  'Lax');
ini_set('session.cookie_secure',    APP_ENV === 'prod' ? '1' : '0');
ini_set('session.use_only_cookies', '1');
if (defined('SESSION_NAME')) { session_name(SESSION_NAME); }
session_start();

// ---- Error display: never leak stack traces to the browser in prod ----
if (APP_ENV === 'prod') {
    ini_set('display_errors', '0');
    ini_set('log_errors', '1');
    ini_set('error_log', ROOT . DS . 'logs' . DS . 'php_errors.log');
    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
} elseif (DEBUG) {
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
}

$url = [];
if (!empty($_SERVER['REQUEST_URI'])) {
    $requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?? '';
    if (PROOT !== '/' && strpos($requestPath, PROOT) === 0) {
        $requestPath = substr($requestPath, strlen(PROOT));
    }
    $requestPath = preg_replace('#^/?index\.php/?#', '', $requestPath);
    $requestPath = trim($requestPath, '/');
    if ($requestPath !== '') {
        $url = explode('/', $requestPath);
    }
}

Router::route($url);
