<?php
/**
 * ITSWEBER CMS – Migration 035: Contact Submissions + Form Builder Settings
 * F5 (v3.3.0): Configurable contact form, DB-stored submissions
 */

use App\Database\Migration;

class CreateContactSubmissions extends Migration
{
    private const DEFAULT_FIELDS = [
        ['id' => 'field_name',    'type' => 'text',     'label' => 'Name',      'placeholder' => '',   'required' => true,  'width' => 'half'],
        ['id' => 'field_email',   'type' => 'email',    'label' => 'E-Mail',    'placeholder' => '',   'required' => true,  'width' => 'half'],
        ['id' => 'field_subject', 'type' => 'text',     'label' => 'Betreff',   'placeholder' => '',   'required' => true,  'width' => 'full'],
        ['id' => 'field_message', 'type' => 'textarea', 'label' => 'Nachricht', 'placeholder' => '…',  'required' => true,  'width' => 'full'],
    ];

    public function up(): void
    {
        // ── Contact submissions table ───────────────────────────────────
        $this->db->query("
            CREATE TABLE IF NOT EXISTS `iw_contact_submissions` (
                `id`          INT          AUTO_INCREMENT PRIMARY KEY,
                `form_data`   TEXT         NOT NULL,
                `ip_address`  VARCHAR(45)  NULL,
                `user_agent`  VARCHAR(500) NULL,
                `is_read`     TINYINT(1)   NOT NULL DEFAULT 0,
                `created_at`  DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        // ── Seed form builder settings ──────────────────────────────────
        $defaults = [
            ['contact_form_enabled',  '1',                                       'contact_form'],
            ['contact_form_save_to_db', '1',                                     'contact_form'],
            ['contact_form_fields',   json_encode(self::DEFAULT_FIELDS, JSON_UNESCAPED_UNICODE), 'contact_form'],
        ];

        foreach ($defaults as [$key, $value, $group]) {
            $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 (?, ?, ?)",
                    [$key, $value, $group]
                );
            }
        }
    }

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