<?php

declare(strict_types=1);

if (\PHP_OS_FAMILY === 'Windows' && \function_exists('sapi_windows_cp_set')) {
    @\sapi_windows_cp_set(65001);
}

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

session_name($config['session_name']);
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

spl_autoload_register(static function (string $class): void {
    $prefix = 'Lab\\';
    if (! str_starts_with($class, $prefix)) {
        return;
    }
    $relative = str_replace('\\', '/', substr($class, strlen($prefix)));
    $path = __DIR__ . '/src/' . $relative . '.php';
    if (is_file($path)) {
        require $path;
    }
});

$configuredBase = $config['base_path'] ?? 'auto';
if ($configuredBase === 'auto' || $configuredBase === null) {
    $config['base_path'] = \Lab\Helpers::detectBasePath(__DIR__);
} else {
    $config['base_path'] = (string) $configuredBase;
}

\Lab\Helpers::setBasePath((string) $config['base_path']);
$config = \Lab\Helpers::prepareWritableData($config);
\Lab\I18n::boot();

foreach (['uploads_dir', 'orders_dir', 'hotfolder_dir', 'print_dir'] as $dirKey) {
    $dir = (string) $config[$dirKey];
    if (! is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
}

return $config;
