<?php global $CONFIG_DB, $DEBUG, $ENCRYPTION_KEY, $CORS, $ECONOMIC_API, $WORDPRESS_STATIC_TOKEN, $EMAIL_WASH_CERTIFICATE_TOKEN, $MINIO, $REDIS_CONFIG, $WORDPRESS_API_URL, $SLACK_DEFAULT_WEBHOOK, $ALL_CONFIG;

$runtimeEnvironment = getenv();
if (is_array($runtimeEnvironment) && $runtimeEnvironment !== []) {
    $_ENV = array_merge($_ENV ?? [], $runtimeEnvironment);
}

/**
 * Check if the environment variables are set (If we are running in a Docker container)
 */
if (strtolower(trim((string)($_ENV['USE_ENV'] ?? getenv('USE_ENV') ?? ''))) === 'true') {
    $readEnv = static function (string $key, string $default = ''): string {
        $value = $_ENV[$key] ?? getenv($key);
        if ($value === false || $value === null) {
            return $default;
        }
        return trim((string)$value);
    };

    // Set the configuration from the environment variables
    $ENV_VARIABLES = [
        'CONFIG_DB_HOST' => 'host',
        'CONFIG_DB_USER' => 'user',
        'CONFIG_DB_PASSWORD' => 'password',
        'CONFIG_DB_DATABASE' => 'database',
        'CONFIG_DB_PORT' => 'port',
        'DEBUG' => 'DEBUG',
        'ENCRYPTION_KEY' => 'ENCRYPTION_KEY',
        'CORS' => 'CORS',
        'ECONOMIC_API_APP_ACCESS_GRANT' => 'app_access_grant',
        'ECONOMIC_API_APP_ACCESS_GRANT2' => 'app_access_grant2',
        'ECONOMIC_API_APP_SECRET_TOKEN' => 'app_secret_token',
        'WORDPRESS_STATIC_TOKEN' => 'WORDPRESS_STATIC_TOKEN',
        'EMAIL_WASH_CERTIFICATE_TOKEN' => 'EMAIL_WASH_CERTIFICATE_TOKEN',
        'WORDPRESS_API_URL' => 'WORDPRESS_API_URL',
        'MINIO_ENDPOINT' => 'endpoint',
        'MINIO_ACCESS_KEY' => 'access_key',
        'MINIO_SECRET_KEY' => 'secret_key',
        'SLACK_DEFAULT_WEBHOOK' => 'SLACK_DEFAULT_WEBHOOK',
        'REDIS_CONFIG_HOST' => 'host',
        'REDIS_CONFIG_DATABASE' => 'database',
        'REDIS_CONFIG_PASSWORD' => 'password',
        'REDIS_CONFIG_PORT' => 'port',
        'REDIS_CONFIG_USER' => 'user',
        'REDIS_CONFIG_DEBUG_PASSWORD' => 'debug_password'
    ];
    $dbTarget = strtolower(trim($readEnv('CONFIG_DB_TARGET', 'live')));
    if ($dbTarget !== 'live' && $dbTarget !== 'debug') {
        $dbTarget = 'live';
    }

    $resolveDbValue = function (string $key) use ($dbTarget, $readEnv): string {
        $liveKey = 'CONFIG_DB_' . $key;
        $debugKey = 'CONFIG_DB_DEBUG_' . $key;
        $liveValue = $readEnv($liveKey);
        $debugValue = $readEnv($debugKey);

        if ($dbTarget === 'debug' && $debugValue !== '') {
            return $debugValue;
        }

        return $liveValue;
    };

    /**
     * Set the db configuration from selected target (live/debug)
     */
    $CONFIG_DB = [
        'host' => $resolveDbValue('HOST'),
        'user' => $resolveDbValue('USER'),
        'password' => $resolveDbValue('PASSWORD'),
        'database' => $resolveDbValue('DATABASE'),
        'port' => (int)($resolveDbValue('PORT') ?: 3306),
        'ssl_mode' => $resolveDbValue('SSL_MODE') ?: 'DISABLED'
    ];
    /**
     * Set the debug configuration
     */
    $DEBUG = $readEnv('DEBUG');
    /**
     * Set the encryption key
     */
    $ENCRYPTION_KEY = $readEnv('ENCRYPTION_KEY');
    /**
     * Set the CORS configuration
     */
    $CORS = $readEnv('CORS');
    /**
     * Set the economic API configuration
     */
    $economicPrimaryGrant = $readEnv('ECONOMIC_API_APP_ACCESS_GRANT');
    $economicSecondaryGrant = $readEnv('ECONOMIC_API_APP_ACCESS_GRANT2');
    $economicSecretToken = $readEnv('ECONOMIC_API_APP_SECRET_TOKEN');

    if ($economicPrimaryGrant === '' || $economicSecretToken === '') {
        error_log('[config] Economic API is missing required credentials. Set ECONOMIC_API_APP_ACCESS_GRANT and ECONOMIC_API_APP_SECRET_TOKEN, then recreate php containers.');
    }
    if ($economicSecondaryGrant === '') {
        error_log('[config] ECONOMIC_API_APP_ACCESS_GRANT2 is not set. Secondary e-conomic token requests will fall back to ECONOMIC_API_APP_ACCESS_GRANT.');
    }

    $ECONOMIC_API = [
        'app_access_grant' => $economicPrimaryGrant,
        'app_access_grant2' => $economicSecondaryGrant,
        'app_secret_token' => $economicSecretToken
    ];
    /**
     * Set the WordPress static token
     */
    $WORDPRESS_STATIC_TOKEN = $readEnv('WORDPRESS_STATIC_TOKEN');
    /**
     * Set the email wash certificate token
     */
    $EMAIL_WASH_CERTIFICATE_TOKEN = $readEnv('EMAIL_WASH_CERTIFICATE_TOKEN');
    /**
     * Set the WordPress API URL
     */
    $WORDPRESS_API_URL = $readEnv('WORDPRESS_API_URL');
    /**
     * Set the Minio configuration
     */
    $MINIO = [
        'endpoint' => $readEnv('MINIO_ENDPOINT'),
        'access_key' => $readEnv('MINIO_ACCESS_KEY'),
        'secret_key' => $readEnv('MINIO_SECRET_KEY')
    ];
    /**
     * Set the Slack default webhook
     */
    $SLACK_DEFAULT_WEBHOOK = $readEnv('SLACK_DEFAULT_WEBHOOK');
    $resolveRedisValue = function (string $key) use ($dbTarget, $readEnv): string {
        $liveKey = 'REDIS_CONFIG_' . $key;
        $debugKey = 'REDIS_CONFIG_DEBUG_' . $key;
        $liveValue = $readEnv($liveKey);
        $debugValue = $readEnv($debugKey);

        if ($dbTarget === 'debug' && $debugValue !== '') {
            return $debugValue;
        }

        return $liveValue;
    };

    /**
     * Set the Redis configuration
     */
    $REDIS_CONFIG = [
        'host' => $resolveRedisValue('HOST'),
        'user' => $resolveRedisValue('USER'),
        'database' => $resolveRedisValue('DATABASE'),
        'password' => $resolveRedisValue('PASSWORD'),
        'port' => (int)($resolveRedisValue('PORT') ?: 6379)
    ];

    // Set the timezone
    $timezone = $readEnv('CONFIG_TIMEZONE', 'Europe/Copenhagen');
    date_default_timezone_set($timezone);

    // Set the all config
    $ALL_CONFIG = $_ENV; // This is used by the backup job.

} else {
    // Throw an error if the environment variables are not set
    throw new Exception('Environment variables are not set');
}

require_once __DIR__ . '/classes/replication_secret_box.php';
require_once __DIR__ . '/classes/replication_bootstrap_config.php';
require_once __DIR__ . '/classes/replica_failover_manager.php';
$replicationBootstrapSnapshot = \classes\replication_bootstrap_config::loadSnapshot();
\classes\replication_bootstrap_config::applyToGlobals($replicationBootstrapSnapshot);
try {
    \classes\replica_failover_manager::applyStartupFailoverFromSnapshot();
} catch (Throwable $throwable) {
    error_log('[replication-bootstrap] Startup failover skipped: ' . $throwable->getMessage());
}
