<?php

/**
 * Migration 036 – Add extended SEO fields to pages and blog posts
 *
 * Adds og_image, robots_meta, and canonical_url columns for per-page
 * SEO control. Also adds the extended_seo_enabled setting.
 */

use App\Database\Migration;

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

        if (!in_array('og_image', $cols, true)) {
            $this->db->query("ALTER TABLE iw_pages ADD COLUMN og_image VARCHAR(500) NULL AFTER seo_description");
        }
        if (!in_array('robots_meta', $cols, true)) {
            $this->db->query("ALTER TABLE iw_pages ADD COLUMN robots_meta VARCHAR(100) NULL AFTER og_image");
        }
        if (!in_array('canonical_url', $cols, true)) {
            $this->db->query("ALTER TABLE iw_pages ADD COLUMN canonical_url VARCHAR(500) NULL AFTER robots_meta");
        }

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

        if (!in_array('og_image', $blogCols, true)) {
            $this->db->query("ALTER TABLE iw_blog_posts ADD COLUMN og_image VARCHAR(500) NULL AFTER seo_description");
        }
        if (!in_array('robots_meta', $blogCols, true)) {
            $this->db->query("ALTER TABLE iw_blog_posts ADD COLUMN robots_meta VARCHAR(100) NULL AFTER og_image");
        }
        if (!in_array('canonical_url', $blogCols, true)) {
            $this->db->query("ALTER TABLE iw_blog_posts ADD COLUMN canonical_url VARCHAR(500) NULL AFTER robots_meta");
        }

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

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

        $this->db->query("ALTER TABLE iw_blog_posts DROP COLUMN IF EXISTS og_image");
        $this->db->query("ALTER TABLE iw_blog_posts DROP COLUMN IF EXISTS robots_meta");
        $this->db->query("ALTER TABLE iw_blog_posts DROP COLUMN IF EXISTS canonical_url");

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