<?php

declare(strict_types=1);

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

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

load_env(base_path('.env'));

$timezone = (string) config('app.timezone', 'Europe/Paris');
date_default_timezone_set($timezone);

if ((bool) config('app.debug', true)) {
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
} else {
    ini_set('display_errors', '0');
    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
}

$runtimeDirs = [
    '',
    'cache',
    'cache/data',
    'cache/images',
    'cache/thumbs',
    'cache/rate',
];

$ensureRuntimeTree = static function () use ($runtimeDirs): void {
    foreach ($runtimeDirs as $dir) {
        ensure_dir(runtime_path($dir));
    }
};

try {
    $ensureRuntimeTree();
} catch (Throwable) {
    $fallbackRuntime = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'camparts_runtime';
    $_ENV['CAMPARTS_RUNTIME_PATH'] = $fallbackRuntime;
    $_SERVER['CAMPARTS_RUNTIME_PATH'] = $fallbackRuntime;
    putenv('CAMPARTS_RUNTIME_PATH=' . $fallbackRuntime);
    $ensureRuntimeTree();
}

$sessionName = (string) config('app.session_name', 'camparts_session');
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.use_strict_mode', '1');
    ini_set('session.use_only_cookies', '1');
    ini_set('session.cookie_httponly', '1');

    $secureConfig = strtolower((string) config('app.session_cookie_secure', 'auto'));
    $isHttps = (
        (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off')
        || (int) ($_SERVER['SERVER_PORT'] ?? 0) === 443
    );
    $secureCookie = $secureConfig === '1'
        || $secureConfig === 'true'
        || $secureConfig === 'yes'
        || ($secureConfig === 'auto' && $isHttps);

    session_name($sessionName);
    session_set_cookie_params([
        'lifetime' => (int) config('app.session_cookie_lifetime', 0),
        'path' => (string) config('app.session_cookie_path', '/'),
        'domain' => (string) config('app.session_cookie_domain', ''),
        'secure' => $secureCookie,
        'httponly' => true,
        'samesite' => (string) config('app.session_cookie_samesite', 'Lax'),
    ]);
    session_start();
}
