<?php

/**
 * Migration 037 – Add custom CSS/JS fields to pages and blog posts
 *
 * Allows admins to add per-page/post custom CSS and JavaScript.
 * Also adds the custom_css_js_enabled setting.
 */

use App\Database\Migration;

class AddCustomCssJsFields extends Migration
{
    public function up(): void
    {
        // ── iw_pages ──────────────────────────────────────────────────────
        $cols = array_column(
            $this->db->fetchAll("SHOW COLUMNS FROM iw_pages"),
            'Field'
        );

        if (!in_array('custom_css', $cols, true)) {
            $this->db->query("ALTER TABLE iw_pages ADD COLUMN custom_css TEXT NULL");
        }
        if (!in_array('custom_js', $cols, true)) {
            $this->db->query("ALTER TABLE iw_pages ADD COLUMN custom_js TEXT NULL");
        }

        // ── iw_blog_posts ─────────────────────────────────────────────────
        $blogCols = array_column(
            $this->db->fetchAll("SHOW COLUMNS FROM iw_blog_posts"),
            'Field'
        );

        if (!in_array('custom_css', $blogCols, true)) {
            $this->db->query("ALTER TABLE iw_blog_posts ADD COLUMN custom_css TEXT NULL");
        }
        if (!in_array('custom_js', $blogCols, true)) {
            $this->db->query("ALTER TABLE iw_blog_posts ADD COLUMN custom_js TEXT NULL");
        }

        // ── Setting ───────────────────────────────────────────────────────
        $existing = $this->db->fetch(
            "SELECT id FROM iw_settings WHERE setting_key = 'custom_css_js_enabled' LIMIT 1"
        );
        if (!$existing) {
            $this->db->insert('iw_settings', [
                'setting_key'   => 'custom_css_js_enabled',
                'setting_value' => '1',
                'setting_group' => 'general',
            ]);
        }
    }

    public function down(): void
    {
        $this->db->query("ALTER TABLE iw_pages DROP COLUMN IF EXISTS custom_css");
        $this->db->query("ALTER TABLE iw_pages DROP COLUMN IF EXISTS custom_js");

        $this->db->query("ALTER TABLE iw_blog_posts DROP COLUMN IF EXISTS custom_css");
        $this->db->query("ALTER TABLE iw_blog_posts DROP COLUMN IF EXISTS custom_js");

        $this->db->query("DELETE FROM iw_settings WHERE setting_key = 'custom_css_js_enabled'");
    }
}
