<?php
$config = require __DIR__ . '/config/config.php';

date_default_timezone_set($config['timezone'] ?? 'America/Bahia');

if (session_status() === PHP_SESSION_NONE) {
    session_set_cookie_params([
        'httponly' => true,
        'samesite' => 'Lax',
        'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
    ]);
    session_start();
}

define('ROOT_PATH', __DIR__);
define('APP_PATH', ROOT_PATH . '/app');
define('PUBLIC_PATH', ROOT_PATH);
define('STORAGE_PATH', ROOT_PATH . '/storage');
define('UPLOAD_PATH', ROOT_PATH . '/uploads');

if (!is_dir(STORAGE_PATH)) {
    mkdir(STORAGE_PATH, 0775, true);
}
if (!is_dir(UPLOAD_PATH)) {
    mkdir(UPLOAD_PATH, 0775, true);
}

$GLOBALS['config'] = $config;

require_once APP_PATH . '/Core/helpers.php';

spl_autoload_register(function ($class) {
    $folders = ['Core', 'Models', 'Controllers'];
    foreach ($folders as $folder) {
        $file = APP_PATH . '/' . $folder . '/' . $class . '.php';
        if (file_exists($file)) {
            require_once $file;
            return;
        }
    }
});


try {
    Database::migrate();
} catch (Throwable $e) {
    // O instalador cria as tabelas quando o banco ainda está vazio.
}
