<?php
$server_config = [];
$serverConfigFile = __DIR__ . '/server.php';
if (is_file($serverConfigFile)) {
    $loadedServerConfig = require $serverConfigFile;
    if (is_array($loadedServerConfig)) {
        $server_config = $loadedServerConfig;
    }
}

if (!function_exists('app_env')) {
    function app_env($key, $default = '') {
        global $server_config;
        $value = getenv($key);
        if ($value !== false && $value !== '') {
            return $value;
        }
        if (isset($server_config[$key]) && $server_config[$key] !== '') {
            return $server_config[$key];
        }
        return $default;
    }
}

if (!function_exists('app_detect_url')) {
    function app_detect_url() {
        $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
        $scheme = $https ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';

        $projectRoot = realpath(__DIR__ . '/..');
        $documentRoot = isset($_SERVER['DOCUMENT_ROOT']) ? realpath($_SERVER['DOCUMENT_ROOT']) : false;
        $basePath = '';

        if ($projectRoot && $documentRoot && strpos($projectRoot, $documentRoot) === 0) {
            $basePath = str_replace('\\', '/', substr($projectRoot, strlen($documentRoot)));
        }

        $basePath = trim($basePath, '/');
        return $scheme . '://' . $host . ($basePath ? '/' . $basePath : '') . '/';
    }
}

$app_name = app_env('CAR_RENTAL_APP_NAME', 'Car Rental');
$app_url = rtrim(app_env('CAR_RENTAL_APP_URL', app_detect_url()), '/') . '/';

$db_config = [
    'host' => app_env('CAR_RENTAL_DB_HOST', '127.0.0.1'),
    'name' => app_env('CAR_RENTAL_DB_NAME', 'car_rental'),
    'user' => app_env('CAR_RENTAL_DB_USER', 'root'),
    'pass' => app_env('CAR_RENTAL_DB_PASS', ''),
    'port' => app_env('CAR_RENTAL_DB_PORT', '3306'),
    'timezone' => app_env('CAR_RENTAL_DB_TIMEZONE', '+06:30'),
];

if (!defined('APP_URL')) {
    define('APP_URL', $app_url);
}
?>
