<?php
require_once __DIR__ . '/../Core.php';

class Setting extends Model
{
    public function all(): array
    {
        $rows = $this->db->query('SELECT setting_key, setting_value FROM settings')->fetchAll(PDO::FETCH_KEY_PAIR);
        foreach ($rows as $key => $value) {
            if (in_array($key, sensitive_setting_keys(), true)) {
                $rows[$key] = decrypt_value($value);
            }
        }
        return $rows;
    }

    public function get(string $key, $default = null)
    {
        $stmt = $this->db->prepare('SELECT setting_value FROM settings WHERE setting_key = ? LIMIT 1');
        $stmt->execute([$key]);
        $value = $stmt->fetchColumn();
        if ($value === false || $value === null || $value === '') {
            return $default;
        }
        if (in_array($key, sensitive_setting_keys(), true)) {
            $value = decrypt_value((string)$value);
        }
        return $value;
    }

    public function set(string $key, string $value): bool
    {
        if (in_array($key, sensitive_setting_keys(), true)) {
            $value = (string)encrypt_value($value);
        }
        $stmt = $this->db->prepare('INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()');
        return $stmt->execute([$key, $value]);
    }
}
