<?php

declare(strict_types=1);

namespace App\Repositories;

use App\Database;
use PDO;

final class SiteSettingRepository
{
    private PDO $db;

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

    public function all(): array
    {
        $rows = $this->db->query('SELECT setting_key, setting_value FROM site_settings')->fetchAll();
        $settings = [];
        foreach ($rows as $row) $settings[$row['setting_key']] = $row['setting_value'];
        return $settings;
    }

    public function save(array $settings): void
    {
        $statement = $this->db->prepare(
            'INSERT INTO site_settings (setting_key, setting_value) VALUES (:key, :value)
             ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)'
        );
        $this->db->beginTransaction();
        try {
            foreach ($settings as $key => $value) $statement->execute(['key'=>$key, 'value'=>$value]);
            $this->db->commit();
        } catch (\Throwable $exception) {
            $this->db->rollBack();
            throw $exception;
        }
    }
}
