<?php

namespace App\Models;

use App\Core\Model;

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

    public function get($key, $default = null)
    {
        $stmt = $this->conn->prepare("SELECT value FROM {$this->table} WHERE `key` = :key");
        $stmt->execute(['key' => $key]);
        $result = $stmt->fetch();

        return $result ? $result['value'] : $default;
    }

    public function set($key, $value)
    {
        // Check if exists
        if ($this->get($key) !== null) {
            $stmt = $this->conn->prepare("UPDATE {$this->table} SET value = :value WHERE `key` = :key");
        } else {
            $stmt = $this->conn->prepare("INSERT INTO {$this->table} (`key`, value) VALUES (:key, :value)");
        }
        
        return $stmt->execute(['key' => $key, 'value' => $value]);
    }

    public function getAll()
    {
        $stmt = $this->conn->query("SELECT * FROM {$this->table}");
        $results = $stmt->fetchAll();
        
        $settings = [];
        foreach ($results as $row) {
            $settings[$row['key']] = $row['value'];
        }
        
        return $settings;
    }
}
