<?php

namespace App\Core;

class Config
{
    private static array $settings = [];

    public static function load(string $basePath): void
    {
        $dotenv = \Dotenv\Dotenv::createImmutable($basePath);
        $dotenv->load();
    }

    public static function get(string $key, mixed $default = null): mixed
    {
        return $_ENV[$key] ?? $default;
    }

    public static function getDbSetting(string $key, mixed $default = null): mixed
    {
        if (empty(self::$settings)) {
            self::loadDbSettings();
        }
        return self::$settings[$key] ?? $default;
    }

    public static function setDbSetting(string $key, ?string $value): void
    {
        $db = Database::getInstance();
        $stmt = $db->prepare("INSERT INTO settings (`key`, value) VALUES (:key, :value) ON DUPLICATE KEY UPDATE value = :value2");
        $stmt->execute(['key' => $key, 'value' => $value, 'value2' => $value]);
        self::$settings[$key] = $value;
    }

    private static function loadDbSettings(): void
    {
        try {
            $db = Database::getInstance();
            $stmt = $db->query("SELECT `key`, value FROM settings");
            while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
                self::$settings[$row['key']] = $row['value'];
            }
        } catch (\Exception $e) {
            self::$settings = [];
        }
    }

    public static function clearCache(): void
    {
        self::$settings = [];
    }
}
