<?php
namespace App\Core;

class Config
{
    private static array $data = [];
    private static bool $loaded = false;
    private static bool $dbLoaded = false;

    private static function load(): void
    {
        if (self::$loaded) return;
        $base = realpath(__DIR__ . '/../../config');
        if ($base && is_dir($base)) {
            foreach (glob($base . '/*.php') as $file) {
                $key = basename($file, '.php');
                $val = include $file;
                if (is_array($val)) {
                    self::$data[$key] = $val;
                }
            }
        }
        // .env support (simple)
        $envFile = realpath(__DIR__ . '/../../.env');
        if ($envFile && is_file($envFile)) {
            $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '' || str_starts_with($line, '#')) continue;
                if (strpos($line, '=') === false) continue;
                [$k, $v] = array_map('trim', explode('=', $line, 2));
                self::$data['env'][$k] = $v;
            }
        }
        self::$loaded = true;
    }

    public static function get(string $key, $default = null)
    {
        self::load();
        // Charger les paramètres DB (table settings) à la première demande
        self::loadDbSettings();
        // ENV override priority
        if (isset(self::$data['env'][$key])) return self::$data['env'][$key];
        // DB settings (table settings) doivent surcharger les fichiers de config
        if (isset(self::$data['settings']) && is_array(self::$data['settings']) && array_key_exists($key, self::$data['settings'])) {
            return self::$data['settings'][$key];
        }
        // search in sections
        foreach (self::$data as $section) {
            if (is_array($section) && array_key_exists($key, $section)) {
                return $section[$key];
            }
        }
        return $default;
    }

    public static function set(string $key, $value): void
    {
        self::load();
        if (!isset(self::$data['env'])) {
            self::$data['env'] = [];
        }
        self::$data['env'][$key] = $value;
    }

    private static function loadDbSettings(): void
    {
        if (self::$dbLoaded) return;
        self::$dbLoaded = true;
        // Charger depuis la table settings si elle existe
        try {
            // Appeler Database dynamiquement pour éviter dépendance forte si non disponible en CLI
            if (class_exists('App\\Core\\Database')) {
                $pdo = \App\Core\Database::pdo();
                if ($pdo) {
                    $st = $pdo->query('SHOW TABLES LIKE "settings"');
                    if ($st && $st->fetchColumn()) {
                        $rows = $pdo->query('SELECT `key`, `value` FROM settings')->fetchAll();
                        $kv = [];
                        foreach ($rows as $r) { $kv[$r['key']] = $r['value']; }
                        self::$data['settings'] = $kv;
                    }
                }
            }
        } catch (\Throwable $e) {
            // Ignorer silencieusement si indisponible (ex: installation ou droits limités)
        }
    }

    public static function baseUrl(): string
    {
        $url = rtrim((string)self::get('app_url', ''), '/');
        if ($url !== '') {
            return $url;
        }
        // Fallback dynamique: construire https://host[/public] si app_url vide
        $host = $_SERVER['HTTP_HOST'] ?? '';
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $script = $_SERVER['SCRIPT_NAME'] ?? '';
        $scriptDir = rtrim(dirname($script), '/');
        if ($scriptDir === '/' || $scriptDir === '\\' || $scriptDir === '.') { $scriptDir = ''; }
        return ($host ? ($scheme . '://' . $host) : '') . ($scriptDir ? $scriptDir : '');
    }

    public static function publicPath(): string
    {
        $path = realpath(__DIR__ . '/../../public') ?: (__DIR__ . '/../../public');
        return $path;
    }

    public static function storagePath(string $sub = ''): string
    {
        $root = realpath(__DIR__ . '/../../public/storage') ?: (__DIR__ . '/../../public/storage');
        return rtrim($root, DIRECTORY_SEPARATOR) . ($sub !== '' ? DIRECTORY_SEPARATOR . ltrim($sub, DIRECTORY_SEPARATOR) : '');
    }
}
