<?php
/**
 * ITSWEBER CMS – Migration 033: Mail Templates + Settings
 * Phase 4 (v3.3.0): Mail Settings & Template Editor
 */

use App\Database\Migration;

class CreateMailTemplates extends Migration
{
    public function up(): void
    {
        // ── Create mail templates table ─────────────────────────────────
        $this->db->query("
            CREATE TABLE IF NOT EXISTS iw_mail_templates (
                id              INT AUTO_INCREMENT PRIMARY KEY,
                slug            VARCHAR(50)  NOT NULL UNIQUE,
                name            VARCHAR(100) NOT NULL,
                subject         VARCHAR(255) NOT NULL,
                html_body       TEXT         NOT NULL,
                created_at      DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at      DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // ── Seed default templates ──────────────────────────────────────
        $this->seedTemplate('password_reset', 'Passwort zurücksetzen',
            'Passwort-Reset – {{site_name}}',
            $this->passwordResetHtml()
        );

        $this->seedTemplate('contact_form', 'Kontaktformular',
            '[{{site_name}}] Kontaktanfrage: {{subject}}',
            $this->contactFormHtml()
        );

        // ── Seed mail settings ──────────────────────────────────────────
        $defaults = [
            'mail_transport'       => 'mail',
            'mail_from_address'    => '',
            'mail_from_name'       => '',
            'mail_reply_to'        => '',
            'mail_smtp_host'       => '',
            'mail_smtp_port'       => '587',
            'mail_smtp_username'   => '',
            'mail_smtp_password'   => '',
            'mail_smtp_encryption' => 'tls',
        ];

        foreach ($defaults as $key => $value) {
            $existing = $this->db->fetch(
                "SELECT id FROM iw_settings WHERE setting_key = ?",
                [$key]
            );
            if (!$existing) {
                $this->db->query(
                    "INSERT INTO iw_settings (setting_key, setting_value, setting_group) VALUES (?, ?, 'mail')",
                    [$key, $value]
                );
            }
        }
    }

    public function down(): void
    {
        $this->db->query("DROP TABLE IF EXISTS iw_mail_templates");
        $this->db->query("DELETE FROM iw_settings WHERE setting_group = 'mail'");
    }

    private function seedTemplate(string $slug, string $name, string $subject, string $html): void
    {
        $existing = $this->db->fetch(
            "SELECT id FROM iw_mail_templates WHERE slug = ?",
            [$slug]
        );
        if (!$existing) {
            $this->db->query(
                "INSERT INTO iw_mail_templates (slug, name, subject, html_body) VALUES (?, ?, ?, ?)",
                [$slug, $name, $subject, $html]
            );
        }
    }

    private function mailHeader(): string
    {
        return '<div style="background:linear-gradient(135deg,#0d2d3a 0%,#15779b 100%);padding:24px 32px;text-align:center;">'
            . '{{logo_header}}'
            . '</div>';
    }

    private function passwordResetHtml(): string
    {
        return '<div style="font-family:Arial,Helvetica,sans-serif;max-width:600px;margin:0 auto;background:#ffffff;">'
            . $this->mailHeader()
            . '<div style="padding:32px;">'
            . '<p style="color:#334155;font-size:15px;line-height:1.6;margin:0 0 16px;">Hallo {{username}},</p>'
            . '<p style="color:#334155;font-size:15px;line-height:1.6;margin:0 0 24px;">Sie haben eine Passwortzurücksetzung angefordert. Klicken Sie auf den folgenden Button, um ein neues Passwort zu vergeben:</p>'
            . '<div style="text-align:center;margin:32px 0;">'
            . '<a href="{{reset_url}}" style="display:inline-block;background:linear-gradient(135deg,#0e7490,#0a7c8f);color:#ffffff;text-decoration:none;padding:14px 32px;border-radius:8px;font-size:15px;font-weight:600;box-shadow:0 2px 8px rgba(14,116,144,0.3);">Passwort zurücksetzen</a>'
            . '</div>'
            . '<p style="color:#64748b;font-size:13px;line-height:1.5;margin:0 0 8px;">Dieser Link ist {{token_ttl_minutes}} Minuten gültig.</p>'
            . '<p style="color:#64748b;font-size:13px;line-height:1.5;margin:0;">Falls Sie diese Anfrage nicht gestellt haben, können Sie diese E-Mail ignorieren.</p>'
            . '</div>'
            . '<div style="border-top:1px solid #e2e8f0;padding:20px 32px;text-align:center;">'
            . '<p style="color:#94a3b8;font-size:12px;margin:0;">{{site_name}} – Automatische Benachrichtigung</p>'
            . '</div></div>';
    }

    private function contactFormHtml(): string
    {
        return '<div style="font-family:Arial,Helvetica,sans-serif;max-width:600px;margin:0 auto;background:#ffffff;">'
            . $this->mailHeader()
            . '<div style="padding:32px;">'
            . '<p style="color:#334155;font-size:15px;line-height:1.6;margin:0 0 20px;">Neue Nachricht über das Kontaktformular:</p>'
            . '<table style="width:100%;border-collapse:collapse;margin:0 0 24px;">'
            . '<tr><td style="padding:10px 12px;border:1px solid #e2e8f0;font-size:13px;font-weight:600;color:#475569;background:#f8fafc;width:120px;">Name</td>'
            . '<td style="padding:10px 12px;border:1px solid #e2e8f0;font-size:14px;color:#334155;">{{contact_name}}</td></tr>'
            . '<tr><td style="padding:10px 12px;border:1px solid #e2e8f0;font-size:13px;font-weight:600;color:#475569;background:#f8fafc;">E-Mail</td>'
            . '<td style="padding:10px 12px;border:1px solid #e2e8f0;font-size:14px;color:#334155;">{{contact_email}}</td></tr>'
            . '<tr><td style="padding:10px 12px;border:1px solid #e2e8f0;font-size:13px;font-weight:600;color:#475569;background:#f8fafc;">Betreff</td>'
            . '<td style="padding:10px 12px;border:1px solid #e2e8f0;font-size:14px;color:#334155;">{{subject}}</td></tr>'
            . '</table>'
            . '<div style="background:#f8fafc;border-left:3px solid #15779b;padding:16px 20px;border-radius:0 8px 8px 0;margin:0 0 16px;">'
            . '<p style="color:#334155;font-size:14px;line-height:1.6;margin:0;white-space:pre-wrap;">{{message}}</p>'
            . '</div>'
            . '<p style="color:#64748b;font-size:13px;line-height:1.5;margin:0;">Sie können direkt auf diese E-Mail antworten, um dem Absender zu schreiben.</p>'
            . '</div>'
            . '<div style="border-top:1px solid #e2e8f0;padding:20px 32px;text-align:center;">'
            . '<p style="color:#94a3b8;font-size:12px;margin:0;">{{site_name}} – Automatische Benachrichtigung</p>'
            . '</div></div>';
    }
}
