<?php
ini_set('session.gc_maxlifetime', 30 * 24 * 60 * 60); // 30 jours en secondes
ini_set('session.cookie_lifetime', 30 * 24 * 60 * 60);

session_set_cookie_params([
    'lifetime' => 30 * 24 * 60 * 60,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);

session_start();

class Config {
    private static $config = null;
    
    public static function load() {
        if (self::$config === null) {
            $configFile = __DIR__ . '/../config.json';
            if (!file_exists($configFile)) {
                throw new Exception('Configuration file not found');
            }
            self::$config = json_decode(file_get_contents($configFile), true);
        }
        return self::$config;
    }
    
    public static function get($key, $default = null) {
        $config = self::load();
        return $config[$key] ?? $default;
    }

    public static function fixImagePaths($content) {
        return preg_replace('/(src|url)=(["\'])\.\.\//i', '$1=$2', $content);
    }

    public static function save($newConfig) {
        $configFile = __DIR__ . '/../config.json';
        
        // S'assurer que le fichier est accessible en écriture
        if (!is_writable($configFile)) {
            throw new Exception('Le fichier de configuration n\'est pas accessible en écriture');
        }
        
        // Sauvegarder avec un formatage JSON lisible
        $success = file_put_contents(
            $configFile,
            json_encode($newConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
        );
        
        if ($success === false) {
            throw new Exception('Erreur lors de la sauvegarde de la configuration');
        }
        
        // Mettre à jour la configuration en mémoire
        self::$config = $newConfig;
        
        return true;
    }
}