<?php
declare(strict_types=1);

// Basic error reporting (keep strict in dev)
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

// Determine APP_ENV consistently:
// 1) Prefer environment variable.
// 2) If not set, try root config files to define APP_ENV.
$appEnvFromEnv = getenv('APP_ENV');
if (!$appEnvFromEnv) {
    $rootDomain = __DIR__ . '/domaindata.php';
    $rootSettings = __DIR__ . '/settings.php';
    if (file_exists($rootDomain)) {
        require_once $rootDomain;
    }
    if (file_exists($rootSettings)) {
        require_once $rootSettings;
    }
}

$appEnv = $appEnvFromEnv ?: (defined('APP_ENV') ? (string) APP_ENV : 'prod');
$envDir = rtrim(__DIR__, '/\\') . '/' . $appEnv;

foreach (['domaindata.php','settings.php'] as $cfgFile) {
    $rootPath = __DIR__ . '/' . $cfgFile;
    $envPath  = $envDir . '/' . $cfgFile;

    if (file_exists($rootPath)) {
        require_once $rootPath;
    } elseif (file_exists($envPath)) {
        require_once $envPath;
    } else {
        throw new \RuntimeException("Missing required config file: $cfgFile (looked for $rootPath or $envPath)");
    }
}


// Environment: staging|prod|local (example)
if (!defined('APP_ENV')) {
    define('APP_ENV', 'local');
}

// Asset versioning
if (!defined('ASSET_VERSION')) {
    define('ASSET_VERSION', 'dev-' . date('Ymd-His'));
}

// Primary domain + URL
if (!defined('APP_DOMAIN_PRIMARY')) {
    define('APP_DOMAIN_PRIMARY', APP_DOMAIN_NAME);
}
if (!defined('APP_URL_PRIMARY')) {
    define('APP_URL_PRIMARY', 'https://' . APP_DOMAIN_PRIMARY);
}

// API base (example)
if (!defined('APP_API_BASE')) {
    define('APP_API_BASE', 'https://api.' . APP_DOMAIN_PRIMARY);
}

// Feature toggles
if (!defined('APP_DB_ENABLED')) {
    define('APP_DB_ENABLED', false); // set true to enable DB connection
}
