<?php
declare(strict_types=1);
namespace App\Repositories;
use App\Core\Repository;

final class SettingRepository extends Repository {
    public function get(string $key, string $default=''): string {
        $row = $this->one("SELECT setting_value FROM settings WHERE setting_key=?", [$key]);
        return (string)($row['setting_value'] ?? $default);
    }

    public function set(string $key, string $value): void {
        $this->exec("INSERT INTO settings(setting_key,setting_value,updated_at) VALUES(?,?,NOW()) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value), updated_at=VALUES(updated_at)", [$key, $value]);
    }

    public function allAssoc(): array {
        $rows = $this->all("SELECT setting_key, setting_value FROM settings ORDER BY setting_key");
        $out = [];
        foreach ($rows as $row) {
            $out[$row['setting_key']] = $row['setting_value'];
        }
        return $out;
    }

    public function saveBulk(array $pairs): void {
        foreach ($pairs as $key => $value) {
            $this->set((string)$key, (string)$value);
        }
    }
}
