<?php

namespace Core\App\Models;

use PDO;

class ThemeSettings
{
    protected PDO $db;

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

    public function getAll(): array
    {
        $stmt = $this->db->query("SELECT `key`, `value` FROM theme_settings");
        $settings = [];

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $settings[$row['key']] = json_decode($row['value'], true);
        }

        return $settings;
    }

    public function get(string $key, $default = null)
    {
        $stmt = $this->db->prepare("SELECT `value` FROM theme_settings WHERE `key` = ?");
        $stmt->execute([$key]);

        $val = $stmt->fetchColumn();
        return $val ? json_decode($val, true) : $default;
    }

    public function set(string $key, $value): bool
    {
        $value = json_encode($value);

        $stmt = $this->db->prepare("
            INSERT INTO theme_settings (`key`, `value`) 
            VALUES (?, ?)
            ON DUPLICATE KEY UPDATE value = VALUES(value)
        ");

        return $stmt->execute([$key, $value]);
    }
}
