<?php

/**
 * Migration 055 – Add marketplace_installed table + marketplace settings.
 *
 * Tracks packages (themes/plugins) installed via the Marketplace.
 * Also seeds marketplace_url and marketplace_cache_ttl settings.
 */

use App\Database\Migration;

class AddMarketplaceInstalledTable extends Migration
{
    public function up(): void
    {
        // 1. Create marketplace_installed table
        $this->db->query("
            CREATE TABLE IF NOT EXISTS iw_marketplace_installed (
                id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                slug            VARCHAR(100) NOT NULL,
                type            ENUM('theme','plugin') NOT NULL DEFAULT 'plugin',
                name            VARCHAR(255) NOT NULL DEFAULT '',
                version         VARCHAR(20) NOT NULL DEFAULT '1.0.0',
                installed_at    DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                license_key     VARCHAR(100) NULL,
                remote_version  VARCHAR(20) NULL,
                UNIQUE INDEX idx_slug (slug)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // 2. Add marketplace settings (idempotent)
        $newSettings = [
            ['marketplace_url',       '', 'marketplace'],
            ['marketplace_cache_ttl', '3600', 'marketplace'],
        ];

        foreach ($newSettings as [$key, $value, $group]) {
            $exists = $this->db->fetch(
                "SELECT id FROM iw_settings WHERE setting_key = :key LIMIT 1",
                ['key' => $key]
            );

            if (!$exists) {
                $this->db->insert('iw_settings', [
                    'setting_key'   => $key,
                    'setting_value' => $value,
                    'setting_group' => $group,
                ]);
            }
        }
    }

    public function down(): void
    {
        $this->db->query("DROP TABLE IF EXISTS iw_marketplace_installed");

        $this->db->query(
            "DELETE FROM iw_settings WHERE setting_key IN ('marketplace_url', 'marketplace_cache_ttl')"
        );
    }
}
