<?php
/**
 * ITSWEBER CMS – Migration 026: Migrate Homepage Data
 *
 * Copies existing rows from iw_homepage_sections into the new
 * iw_page_sections table. Only runs when iw_page_sections is empty
 * (idempotent). The old table is preserved for rollback safety.
 *
 * @author    Benny Weber (ITSWEBER)
 * @copyright © ITSWEBER – www.itsweber.de
 * @contact   kontakt@itsweber.de
 */

use App\Database\Migration;

class MigrateHomepageData extends Migration
{
    public function up(): void
    {
        // Only migrate if both tables exist and target is empty
        $sourceExists = (int) $this->db->fetchColumn(
            "SELECT COUNT(*)
             FROM   information_schema.TABLES
             WHERE  TABLE_SCHEMA = DATABASE()
               AND  TABLE_NAME   = 'iw_homepage_sections'"
        );

        $targetExists = (int) $this->db->fetchColumn(
            "SELECT COUNT(*)
             FROM   information_schema.TABLES
             WHERE  TABLE_SCHEMA = DATABASE()
               AND  TABLE_NAME   = 'iw_page_sections'"
        );

        if ($sourceExists === 0 || $targetExists === 0) {
            return;
        }

        $targetCount = (int) $this->db->fetchColumn(
            "SELECT COUNT(*) FROM iw_page_sections WHERE page_context = 'homepage'"
        );

        if ($targetCount > 0) {
            return; // Already migrated
        }

        $this->db->query("
            INSERT INTO iw_page_sections
                (page_context, section_type, instance_label, content, is_active, sort_order, updated_at)
            SELECT
                'homepage', section_key, title, content, is_active, sort_order, updated_at
            FROM iw_homepage_sections
            ORDER BY sort_order ASC
        ");
    }

    public function down(): void
    {
        // Remove only the migrated homepage rows, leave any manually created ones
        // This is a best-effort rollback
        $this->db->query("
            DELETE FROM iw_page_sections WHERE page_context = 'homepage'
        ");
    }
}
