<?php

use App\Database\Migration;

class CreateCmsUpdateSettings extends Migration
{
    private array $settings = [
        ['cms_update_check_enabled',       '1',    'system_update'],
        ['cms_update_check_ttl',           '21600','system_update'],
        ['cms_update_registry_url',        'https://itsweber.de', 'system_update'],
        ['cms_update_last_check_at',       '',     'system_update'],
        ['cms_update_last_install_at',     '',     'system_update'],
        ['cms_update_last_install_log',    '',     'system_update'],
        ['cms_update_auto_install_enabled','0',    'system_update'],
    ];

    public function up(): void
    {
        foreach ($this->settings as [$key, $value, $group]) {
            $exists = $this->db->fetch(
                "SELECT id FROM iw_settings WHERE setting_key = ? LIMIT 1",
                [$key]
            );
            if (!$exists) {
                $this->db->insert('iw_settings', [
                    'setting_key'   => $key,
                    'setting_value' => $value,
                    'setting_group' => $group,
                ]);
            }
        }
    }

    public function down(): void
    {
        $keys = array_column($this->settings, 0);
        $placeholders = implode(',', array_fill(0, count($keys), '?'));
        $this->db->query(
            "DELETE FROM iw_settings WHERE setting_key IN ({$placeholders})",
            $keys
        );
    }
}
