<?php
declare(strict_types=1);
require_once __DIR__ . '/../../app/Config/database.php';

class Setting
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::getConnection();
    }

    /** 🔍 Fetch all settings as key–value array */
    public function getAll(): array
    {
        $stmt = $this->db->query("SELECT setting_key, setting_value FROM settings");
        $rows = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        return $rows ?: [];
    }

    /** 💾 Update or insert a setting */
    public function update(string $key, string $value): bool
    {
        $stmt = $this->db->prepare("
            INSERT INTO settings (setting_key, setting_value)
            VALUES (?, ?)
            ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
        ");
        return $stmt->execute([$key, $value]);
    }

    /** ♻️ Reset all settings to defaults */
    public function resetToDefault(): bool
    {
        return $this->db->exec("
            UPDATE settings SET
            setting_value = CASE setting_key
                WHEN 'company_name' THEN 'SGAccount'
                WHEN 'default_currency' THEN 'SGD'
                WHEN 'financial_year_start' THEN '2025-01-01'
                WHEN 'gst_rate' THEN '8.00'
                WHEN 'theme' THEN 'light'
                ELSE setting_value
            END
        ") !== false;
    }
}
