<?php

declare(strict_types=1);

define('BASE_PATH', dirname(__DIR__));

require_once BASE_PATH . '/app/helpers.php';

spl_autoload_register(static function (string $class): void {
    $prefix = 'FatBottom\\';
    if (!str_starts_with($class, $prefix)) {
        return;
    }

    $relative = str_replace('\\', '/', substr($class, strlen($prefix)));
    $path = BASE_PATH . '/app/' . $relative . '.php';
    if (is_file($path)) {
        require $path;
    }
});

use FatBottom\Core\Config;
use FatBottom\Core\Database;

$config = new Config(
    require BASE_PATH . '/config/defaults.php',
    BASE_PATH . '/storage/config/settings.json'
);

if ((string) $config->get('app.key', '') === '') {
    $config->set('app.key', bin2hex(random_bytes(32)));
    $config->save();
}

date_default_timezone_set((string) $config->get('app.timezone', 'America/New_York'));

if (session_status() !== PHP_SESSION_ACTIVE) {
    $sessionPath = BASE_PATH . '/storage/sessions';
    if (!is_dir($sessionPath)) {
        mkdir($sessionPath, 0775, true);
    }
    session_save_path($sessionPath);
    session_name('fatbottom_session');
    session_set_cookie_params([
        'lifetime' => 60 * 60 * 24 * 14,
        'path' => '/',
        'secure' => !empty($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
    session_start();
}

$database = new Database($config);
$database->migrate();

return [
    'config' => $config,
    'db' => $database,
];
