<?php

namespace App\Models;

use App\Utils\Database;
use PDO;

/**
 * SystemSetting - 系统设置模型
 *
 * 数据库表: system_settings
 * 主要字段:
 * - setting_key (String) - 设置键（主键）
 * - setting_value (String) - 设置值
 * - description (String) - 设置描述
 */
class SystemSetting
{
    private $db;

    // 系统设置属性
    public $settingKey;
    public $settingValue;
    public $description;

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

    public function getSetting($key)
    {
        $stmt = $this->db->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        return $result ? $result['setting_value'] : null;
    }

    public function setSetting($key, $value)
    {
        $stmt = $this->db->prepare(
            "INSERT INTO system_settings (setting_key, setting_value) VALUES (?, ?)
             ON DUPLICATE KEY UPDATE setting_value = ?"
        );
        return $stmt->execute([$key, $value, $value]);
    }

    public function getSettingWithDescription($key)
    {
        $stmt = $this->db->prepare("SELECT setting_value, description FROM system_settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function setSettingWithDescription($key, $value, $description = null)
    {
        $stmt = $this->db->prepare(
            "INSERT INTO system_settings (setting_key, setting_value, description) VALUES (?, ?, ?)
             ON DUPLICATE KEY UPDATE setting_value = ?, description = ?"
        );
        return $stmt->execute([$key, $value, $description, $value, $description]);
    }

    public function isRegistrationEnabled()
    {
        $value = $this->getSetting('registration_enabled');
        return $value === '1' || $value === 'true';
    }

    public function setRegistrationEnabled($enabled)
    {
        return $this->setSetting('registration_enabled', $enabled ? '1' : '0');
    }
}
