<?php
/**
 * ITSWEBER CMS – Migration 032: Add pagebuilder_enabled
 *
 * Adds pagebuilder_enabled flag to iw_pages and iw_blog_posts,
 * allowing pages and blog posts to use the page builder instead of WYSIWYG.
 */

use App\Database\Migration;

class AddPagebuilderEnabled extends Migration
{
    public function up(): void
    {
        // MySQL 8 does not support ADD COLUMN IF NOT EXISTS – check first
        if (!$this->columnExists('iw_pages', 'pagebuilder_enabled')) {
            $this->db->query("
                ALTER TABLE iw_pages
                    ADD COLUMN pagebuilder_enabled TINYINT(1) NOT NULL DEFAULT 0 AFTER show_title
            ");
        }

        if (!$this->columnExists('iw_blog_posts', 'pagebuilder_enabled')) {
            $this->db->query("
                ALTER TABLE iw_blog_posts
                    ADD COLUMN pagebuilder_enabled TINYINT(1) NOT NULL DEFAULT 0 AFTER status
            ");
        }
    }

    public function down(): void
    {
        if ($this->columnExists('iw_pages', 'pagebuilder_enabled')) {
            $this->db->query("ALTER TABLE iw_pages DROP COLUMN pagebuilder_enabled");
        }
        if ($this->columnExists('iw_blog_posts', 'pagebuilder_enabled')) {
            $this->db->query("ALTER TABLE iw_blog_posts DROP COLUMN pagebuilder_enabled");
        }
    }

    private function columnExists(string $table, string $column): bool
    {
        $row = $this->db->fetch(
            "SELECT COUNT(*) AS cnt FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?",
            [$table, $column]
        );
        return ((int) ($row['cnt'] ?? 0)) > 0;
    }
}
