<?php
class Setting extends Model
{
    public function createTableIfNotExists(): void
    {
        $sql = "CREATE TABLE IF NOT EXISTS site_settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            setting_key VARCHAR(150) NOT NULL UNIQUE,
            setting_value TEXT NULL,
            setting_group VARCHAR(80) NOT NULL DEFAULT 'general',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
        $this->execute($sql);
    }

    public function all(): array
    {
        return $this->fetchAll('SELECT * FROM site_settings ORDER BY id ASC');
    }

    public function get(string $key, $default = null)
    {
        $row = $this->fetch('SELECT setting_value FROM site_settings WHERE setting_key = :key LIMIT 1', ['key' => $key]);
        return $row['setting_value'] ?? $default;
    }

    public function getMultiple(array $keys): array
    {
        if (empty($keys)) return [];
        $placeholders = implode(',', array_fill(0, count($keys), '?'));
        $sql = "SELECT setting_key, setting_value FROM site_settings WHERE setting_key IN ($placeholders)";
        $stmt = $this->db->prepare($sql);
        foreach (array_values($keys) as $i => $k) {
            $stmt->bindValue($i + 1, $k);
        }
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $result = [];
        foreach ($rows as $r) {
            $result[$r['setting_key']] = $r['setting_value'];
        }
        foreach ($keys as $k) {
            if (!array_key_exists($k, $result)) $result[$k] = null;
        }
        return $result;
    }

    public function upsert(string $key, string $value, string $group = 'general'): bool
    {
        $sql = 'INSERT INTO site_settings (setting_key, setting_value, setting_group) VALUES (:key, :value, :group)
                ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), setting_group = VALUES(setting_group)';
        return $this->execute($sql, ['key' => $key, 'value' => $value, 'group' => $group]);
    }

    public function updateMultiple(array $items): bool
    {
        $this->db->beginTransaction();
        try {
            foreach ($items as $key => $value) {
                $this->upsert($key, (string)$value);
            }
            $this->db->commit();
            return true;
        } catch (Throwable $e) {
            $this->db->rollBack();
            return false;
        }
    }
}
