<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * Setting Model
 *
 * Handles key-value application settings data retrieval and persistence.
 */
class Setting extends Model
{
    /**
     * The database table associated with the model.
     */
    protected string $table = 'settings';

    /**
     * Get a setting value by its key.
     *
     * @param string $key The setting key to look up
     * @return string|null The setting value, or null if not found
     */
    public function get(string $key): ?string
    {
        $sql = sprintf(
            'SELECT `setting_value` FROM `%s` WHERE `setting_key` = :key LIMIT 1',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->execute([':key' => $key]);

        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        return $result !== false ? $result['setting_value'] : null;
    }

    /**
     * Set (update) a setting value by its key.
     *
     * @param string $key The setting key to update
     * @param string $value The new value to set
     * @return bool True if the update affected at least one row
     */
    public function set(string $key, string $value): bool
    {
        $sql = sprintf(
            'UPDATE `%s` SET `setting_value` = :value WHERE `setting_key` = :key',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->execute([':value' => $value, ':key' => $key]);

        return $stmt->rowCount() > 0;
    }

    /**
     * Get all settings as key-value pairs.
     *
     * @return array<string, string> Associative array of setting_key => setting_value
     */
    public function getAll(): array
    {
        $sql = sprintf(
            'SELECT `setting_key`, `setting_value` FROM `%s`',
            $this->table
        );

        $stmt = $this->db->prepare($sql);
        $stmt->execute();

        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        $settings = [];
        foreach ($rows as $row) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }

        return $settings;
    }
}
