<?php

namespace App\Modules\Settings\Repositories;

use Core\Database\DB;
use PDO;

class SettingsRepository
{
    public function all(): array
    {
        $stmt = DB::conn()->query("
            SELECT setting_key, setting_value
            FROM settings
        ");

        $settings = [];

        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {

            $settings[$row['setting_key']] = $row['setting_value'];

        }

        return $settings;
    }

    public function get(string $key, $default = null)
    {
        $stmt = DB::conn()->prepare("
            SELECT setting_value
            FROM settings
            WHERE setting_key = :key
            LIMIT 1
        ");

        $stmt->execute([
            'key' => $key
        ]);

        $value = $stmt->fetchColumn();

        return $value !== false
            ? $value
            : $default;
    }

    public function set(string $key, $value): bool
    {
        $stmt = DB::conn()->prepare("
            INSERT INTO settings (setting_key, setting_value)
            VALUES (:key, :value)

            ON DUPLICATE KEY UPDATE
            setting_value = VALUES(setting_value)
        ");

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