<?php
/// file: bootstrap/app.php

declare(strict_types=1);

use App\Core\App;
use App\Core\Config;
use App\Core\Database;
use App\Core\Env;
use App\Core\ErrorHandler;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;

$basePath = dirname(__DIR__);

if (is_file($basePath . '/vendor/autoload.php')) {
    require $basePath . '/vendor/autoload.php';
} else {
    spl_autoload_register(static function (string $class) use ($basePath): void {
        $prefix = 'App\\';
        if (! str_starts_with($class, $prefix)) {
            return;
        }
        $relative = str_replace('\\', '/', substr($class, strlen($prefix)));
        $file = $basePath . '/app/' . $relative . '.php';
        if (is_file($file)) {
            require $file;
        }
    });
}
require $basePath . '/app/Helpers/functions.php';

Env::load($basePath . '/.env');

$configApp = [
    'name' => Env::get('APP_NAME', 'SANEKSA'),
    'env' => Env::get('APP_ENV', 'local'),
    'debug' => Env::bool('APP_DEBUG', true),
    'url' => Env::get('APP_URL', 'http://localhost'),
    'locale' => Env::get('DEFAULT_LOCALE', 'en'),
];
Config::load($basePath . '/config');
Config::set('app', $configApp);

$debug = Config::get('app.debug', true);
ErrorHandler::register($basePath, (bool) $debug);

$dbConfig = Config::get('database.connections.mysql', []);
if (is_array($dbConfig) && ($dbConfig['database'] ?? '') !== '') {
    Database::connect($dbConfig);
}

$sessionName = Env::get('SESSION_NAME', 'saneksa_session') ?? 'saneksa_session';
$sessionPath = $basePath . '/storage/sessions';
Session::start($sessionName, $sessionPath);

$defaultLocale = Config::get('app.locale', 'en');
if (! Session::get('locale')) {
    Session::set('locale', is_string($defaultLocale) ? $defaultLocale : 'en');
}

$app = new App($basePath, (bool) $debug);
$GLOBALS['saneksa_app'] = $app;

$router = $app->router();
require $basePath . '/routes/web.php';
require $basePath . '/routes/api.php';

$request = Request::fromGlobals();
$response = $router->dispatch($request, $app);
$response->send();
