<?php

namespace App;

class Settings
{
    private $grupa;
    private $data = [];

    public function __construct($grupa) 
    {
        $this->grupa = $grupa;
        $this->load();
    }

    private function load() 
    {
        $sql = "SELECT name, value FROM settings WHERE grupa = ?";
        $results = db()->fetchAll($sql, [$this->grupa]);
        
        $this->data = [];
        foreach ($results as $row) {
            $this->data[$row['name']] = $row['value'];
        }
    }

    public function get($name, $default = null) 
    {
        return isset($this->data[$name]) ? $this->data[$name] : $default;
    }

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

    public function set($name, $value) 
    {
        $exists = db()->fetchOne("SELECT id FROM settings WHERE grupa = ? AND name = ?", [$this->grupa, $name]);
        
        if ($exists) {
            db()->execute("UPDATE settings SET value = ? WHERE grupa = ? AND name = ?", [$value, $this->grupa, $name]);
        } else {
            db()->execute("INSERT INTO settings (grupa, name, value) VALUES (?, ?, ?)", [$this->grupa, $name, $value]);
        }
        
        $this->data[$name] = $value;
    }

    public function delete($name) 
    {
        db()->execute("DELETE FROM settings WHERE grupa = ? AND name = ?", [$this->grupa, $name]);
        unset($this->data[$name]);
    }
}