<?php
/**
 * ITSWEBER CMS – Migration 034: Add logo to mail templates
 * Replaces text-only or broken logo header with {{logo_header}} variable.
 * {{logo_header}} is auto-injected by MailTemplate::render() — outputs
 * <img> if a logo is configured, or <span> with site name as fallback.
 */

use App\Database\Migration;

class UpdateMailTemplatesLogo extends Migration
{
    public function up(): void
    {
        // Pattern 1: original text-only header from migration 033
        $oldText = '<h1 style="color:#ffffff;font-size:20px;margin:0;font-weight:700;">{{site_name}}</h1>';

        // Pattern 2: broken onerror-based logo (if 033 was already updated)
        $oldLogo = '<img src="{{logo_url}}" alt="{{site_name}}" style="max-height:40px;max-width:200px;" onerror="this.style.display=\'none\';this.nextElementSibling.style.display=\'inline\';"><span style="display:none;color:#ffffff;font-size:20px;font-weight:700;">{{site_name}}</span>';

        // New: single variable that renders correctly server-side
        $newHeader = '{{logo_header}}';

        $templates = $this->db->fetchAll("SELECT id, html_body FROM iw_mail_templates");
        foreach ($templates as $tpl) {
            $body    = $tpl['html_body'];
            $changed = false;

            if (str_contains($body, $oldLogo)) {
                $body    = str_replace($oldLogo, $newHeader, $body);
                $changed = true;
            } elseif (str_contains($body, $oldText)) {
                $body    = str_replace($oldText, $newHeader, $body);
                $changed = true;
            }

            if ($changed) {
                $this->db->query(
                    "UPDATE iw_mail_templates SET html_body = ? WHERE id = ?",
                    [$body, $tpl['id']]
                );
            }
        }
    }

    public function down(): void
    {
        // No rollback needed – users can edit templates manually
    }
}
