<?php
/**
 * Settings Manager - Handles system settings
 */
class SettingsManager {
    private $pdo;
    private $settings = [];
    private static $instance = null;

    public function __construct() {
        $this->pdo = Database::getInstance()->getConnection();
        $this->loadSettings();
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function loadSettings() {
        try {
            $stmt = $this->pdo->query("SELECT setting_key, setting_value, setting_type FROM system_settings");
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($results as $row) {
                $this->settings[$row['setting_key']] = $this->parseValue($row['setting_value'], $row['setting_type']);
            }
        } catch (PDOException $e) {
            error_log("Settings load error: " . $e->getMessage());
        }
    }

    private function parseValue($value, $type) {
        switch ($type) {
            case 'json':
                return json_decode($value, true) ?: [];
            case 'boolean':
                return (bool)$value;
            case 'integer':
                return (int)$value;
            default:
                return $value;
        }
    }

    public function get($key, $default = null) {
        return $this->settings[$key] ?? $default;
    }

    public function set($key, $value, $type = 'string') {
        $serializedValue = $this->serializeValue($value, $type);
        
        try {
            $stmt = $this->pdo->prepare(
                "INSERT INTO system_settings (setting_key, setting_value, setting_type) 
                 VALUES (?, ?, ?) 
                 ON DUPLICATE KEY UPDATE setting_value = ?, setting_type = ?, updated_at = CURRENT_TIMESTAMP"
            );
            
            $stmt->execute([$key, $serializedValue, $type, $serializedValue, $type]);
            $this->settings[$key] = $value;
            return true;
        } catch (PDOException $e) {
            error_log("Settings save error: " . $e->getMessage());
            return false;
        }
    }

    private function serializeValue($value, $type) {
        switch ($type) {
            case 'json':
                return json_encode($value);
            case 'boolean':
                return $value ? '1' : '0';
            default:
                return (string)$value;
        }
    }

    public function getAll() {
        return $this->settings;
    }
}
?>