<?php
// models/SiteSetting.php
// Site settings model

require_once 'BaseModel.php';

class SiteSetting extends BaseModel {
    protected $table = 'site_settings';

    // Get setting by key
    public function getByKey($key) {
        $sql = "SELECT * FROM {$this->table} WHERE setting_key = :key";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':key', $key);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? $result['setting_value'] : null;
    }

    // Get all settings as key-value array
    public function getAllAsArray() {
        $sql = "SELECT setting_key, setting_value FROM {$this->table}";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $settings = [];
        foreach ($results as $result) {
            $settings[$result['setting_key']] = $result['setting_value'];
        }
        return $settings;
    }

    // Update setting by key
    public function updateByKey($key, $value) {
        $sql = "UPDATE {$this->table} SET setting_value = :value, updated_at = NOW() WHERE setting_key = :key";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':key', $key);
        $stmt->bindParam(':value', $value);
        return $stmt->execute();
    }

    // Create or update setting
    public function setSetting($key, $value, $type = 'text', $description = '') {
        $existing = $this->getByKey($key);
        
        if ($existing !== null) {
            return $this->updateByKey($key, $value);
        } else {
            return $this->create([
                'setting_key' => $key,
                'setting_value' => $value,
                'setting_type' => $type,
                'description' => $description
            ]);
        }
    }
}
?>
