<?php

class Setting {
    private $db;

    public function __construct() {
        $this->db = new Database;
    }

    /**
     * Get a single setting value by its key.
     * @param string $key The key of the setting.
     * @return string|null The value of the setting or null if not found.
     */
    public function get($key) {
        $this->db->query("SELECT setting_value FROM settings WHERE setting_key = :key");
        $this->db->bind(':key', $key);
        $row = $this->db->single();
        return $row ? $row->setting_value : null;
    }

    /**
     * Get all settings from the database.
     * @return array An associative array of settings (key => value).
     */
    public function getAll() {
        $this->db->query("SELECT setting_key, setting_value FROM settings");
        $results = $this->db->resultSet();
        $settings = [];
        foreach ($results as $row) {
            $settings[$row->setting_key] = $row->setting_value;
        }
        return $settings;
    }

    /**
     * Update multiple settings at once.
     * Uses an INSERT ... ON DUPLICATE KEY UPDATE query for efficiency.
     * @param array $data An associative array of settings to update (key => value).
     * @return bool True on success, false on failure.
     */
    public function updateMultiple($data) {
        if (empty($data)) return true;

        foreach ($data as $key => $value) {
            $this->db->query("INSERT INTO settings (setting_key, setting_value) VALUES (:key, :value) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
            $this->db->bind(':key', $key);
            $this->db->bind(':value', $value);
            if (!$this->db->execute()) return false;
        }
        return true;
    }
}

