<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Model;

final class SettingsModel extends Model
{
    public function all(): array
    {
        return $this->db->query("
            SELECT *
            FROM system_settings
            ORDER BY setting_group ASC, setting_key ASC
        ")->fetchAll();
    }

    public function findById(int $id): ?array
    {
        $stmt = $this->db->prepare("SELECT * FROM system_settings WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare("
            INSERT INTO system_settings (setting_key, setting_value, setting_group, is_public)
            VALUES (:setting_key, :setting_value, :setting_group, :is_public)
        ");
        $stmt->execute([
            ':setting_key' => $data['setting_key'],
            ':setting_value' => $data['setting_value'] ?: null,
            ':setting_group' => $data['setting_group'] ?: null,
            ':is_public' => $data['is_public'] ?? 0,
        ]);
        return (int) $this->db->lastInsertId();
    }

    public function update(int $id, array $data): void
    {
        $stmt = $this->db->prepare("
            UPDATE system_settings
            SET setting_key = :setting_key,
                setting_value = :setting_value,
                setting_group = :setting_group,
                is_public = :is_public
            WHERE id = :id
        ");
        $stmt->execute([
            ':id' => $id,
            ':setting_key' => $data['setting_key'],
            ':setting_value' => $data['setting_value'] ?: null,
            ':setting_group' => $data['setting_group'] ?: null,
            ':is_public' => $data['is_public'] ?? 0,
        ]);
    }
}
