<?php

namespace App\Models;

use App\Core\Model;

class Setting extends Model
{
    protected $table = 'settings';
    protected $primaryKey = 'id';

    public function getByGroup($group)
    {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE `group` = ? ORDER BY id ASC");
        $stmt->execute([$group]);
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function getGroups()
    {
        $stmt = $this->db->query("SELECT DISTINCT `group` FROM {$this->table} ORDER BY `group` ASC");
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function getValue($key, $default = null)
    {
        $stmt = $this->db->prepare("SELECT `value` FROM {$this->table} WHERE `key` = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch(\PDO::FETCH_OBJ);
        return $result ? $result->value : $default;
    }

    public function setValue($key, $value)
    {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET `value` = ? WHERE `key` = ?");
        return $stmt->execute([$value, $key]);
    }
}
