<?php

/**
 * Edit Invitation Form View
 *
 * Renders the wedding invitation builder interface for the Couple.
 * Features validation feedback, CSRF protection, and responsive layout.
 *
 * Variables expected:
 *   $invitation — array — Current invitation payload details.
 *   $themes     — array — Array of available active theme versions.
 *   $old        — array — Old form values if validation failed.
 *   $errors     — array — Validation errors map.
 *
 * @package Inveetaire
 * @ref     PILOT-001
 */

/** @var array $invitation */
/** @var array $themes */
/** @var array $old */
/** @var array $errors */

$errors = $errors ?? [];
$old = $old ?? [];

// Helper to resolve field value with fallback
$val = function (string $key) use ($invitation, $old) {
    if (isset($old[$key])) {
        return $old[$key];
    }
    return $invitation[$key] ?? '';
};

// Helper to determine active status state
$status = $val('invitation_status');

?>

<div class="w-full mx-auto px-4 sm:px-6 lg:px-8">
    <!-- Header Summary -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 items-end mb-8">
        <div class="lg:col-span-2">
            <div class="page-breadcrumb">
                <a href="<?= url('/app/couple/dashboard') ?>">Dashboard</a>
                <span class="sep">/</span>
                <span>Configure Invitation</span>
            </div>
            <h1 class="page-h1">
                <span class="page-header-icon">
                    <i class="fa-solid fa-envelope-open-text"></i>
                </span>
                Configure Invitation
            </h1>
            <p class="page-subtitle">Design and publish your wedding invitation page.</p>
        </div>
        <div class="lg:col-span-1 flex items-center justify-start lg:justify-end gap-3">
            <a href="<?= url('/app/couple/invitation/preview') ?>" target="_blank" class="btn btn-secondary btn-md flex items-center gap-1.5" title="Fast layout check using simulated content">
                <span>&#128065;</span> Preview
            </a>

            <a href="<?= url('/' . ($workspace_slug ?? '') . '/livepreview') ?>" target="_blank" class="btn btn-primary btn-md flex items-center gap-1.5" title="Experience the invitation exactly as your guests will see it">
                <span>&#10024;</span> Live Preview
            </a>
            
            <div class="flex items-center">
                <?php if ($status === 'published'): ?>
                    <span class="badge badge-success">
                        Published &amp; Active
                    </span>
                <?php else: ?>
                    <span class="badge badge-neutral">
                        Draft Mode
                    </span>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Main Configuration Form -->
    <form action="<?= url('/app/couple/invitation/edit') ?>" method="POST" class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <?= csrf_field() ?>

        <!-- Hidden input storing status target -->
        <input type="hidden" name="invitation_status" id="invitation-status-input" value="<?= escape_html($status) ?>">

        <!-- Left 2 Columns: Main settings sections -->
        <div class="lg:col-span-2 space-y-6">

            <!-- Card 1: Groom & Bride Details -->
            <div class="card p-6">
                <div class="border-b border-slate-100 pb-4 mb-5">
                    <h2 class="text-lg font-bold text-slate-800">Groom & Bride Display Names</h2>
                    <p class="text-xs text-slate-400 mt-0.5">Customize the names as they should appear on the invitation site.</p>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="form-group">
                        <label for="groom_display_name" class="form-label">Groom Name *</label>
                        <input 
                            type="text" 
                            name="groom_display_name" 
                            id="groom_display_name"
                            value="<?= escape_html((string) $val('groom_display_name')) ?>"
                            placeholder="e.g. John Doe"
                            class="form-input <?= isset($errors['groom_display_name']) ? 'is-invalid' : '' ?>"
                            required
                        >
                        <?php if (isset($errors['groom_display_name'])): ?>
                            <p class="form-error"><?= escape_html($errors['groom_display_name']) ?></p>
                        <?php endif; ?>
                    </div>
                    <div class="form-group">
                        <label for="bride_display_name" class="form-label">Bride Name *</label>
                        <input 
                            type="text" 
                            name="bride_display_name" 
                            id="bride_display_name"
                            value="<?= escape_html((string) $val('bride_display_name')) ?>"
                            placeholder="e.g. Jane Smith"
                            class="form-input <?= isset($errors['bride_display_name']) ? 'is-invalid' : '' ?>"
                            required
                        >
                        <?php if (isset($errors['bride_display_name'])): ?>
                            <p class="form-error"><?= escape_html($errors['bride_display_name']) ?></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Card 2: Event Management & Ceremonies -->
            <?php 
                $eventsList = $invitation['events'] ?? [];
                if (empty($eventsList)) {
                    $eventsList = [
                        [
                            'id' => 0,
                            'event_name' => 'Holy Matrimony',
                            'event_date' => ($val('wedding_date') ?: date('Y-m-d')) . ' ' . ($val('wedding_time') ?: '09:00') . ':00',
                            'venue_name' => $val('venue_name') ?: 'Grand Ballroom',
                            'venue_address' => $val('venue_address') ?: '',
                            'maps_url' => $val('maps_url') ?: '',
                            'is_primary' => 1
                        ],
                        [
                            'id' => 0,
                            'event_name' => 'Reception',
                            'event_date' => ($val('wedding_date') ?: date('Y-m-d')) . ' 18:00:00',
                            'venue_name' => $val('venue_name') ?: 'Grand Ballroom',
                            'venue_address' => $val('venue_address') ?: '',
                            'maps_url' => $val('maps_url') ?: '',
                            'is_primary' => 0
                        ]
                    ];
                }
                $primaryEvtId = 0;
                foreach ($eventsList as $e) {
                    if (!empty($e['is_primary'])) {
                        $primaryEvtId = (int)$e['id'];
                        break;
                    }
                }
                if ($primaryEvtId === 0 && !empty($eventsList[0]['id'])) {
                    $primaryEvtId = (int)$eventsList[0]['id'];
                }
            ?>
            <div class="card p-6 space-y-6">
                <div class="border-b border-slate-100 pb-4 flex items-center justify-between">
                    <div>
                        <h2 class="text-lg font-bold text-slate-800">Event Management &amp; Ceremonies</h2>
                        <p class="text-xs text-slate-400 mt-0.5">Manage schedules, venues, and primary countdown ceremony. Timezone default: <strong>WIB (Asia/Jakarta)</strong>.</p>
                    </div>
                    <span class="badge badge-neutral text-xxs font-mono">24-Hour Format (HH:mm)</span>
                </div>

                <div id="ceremonies-container" class="space-y-6">
                    <?php foreach ($eventsList as $idx => $evt): 
                        $eId = (int) ($evt['id'] ?? 0);
                        $eName = $evt['event_name'] ?? 'Ceremony';
                        $dtObj = !empty($evt['event_date']) ? new \DateTime($evt['event_date']) : new \DateTime();
                        $eDate = $dtObj->format('Y-m-d');
                        $eTime = $dtObj->format('H:i');
                        $isPrimary = ($primaryEvtId > 0 && $eId === $primaryEvtId) || ($primaryEvtId === 0 && $idx === 0);
                    ?>
                        <div class="bg-slate-50 border border-slate-200 rounded-2xl p-5 space-y-4 relative">
                            <input type="hidden" name="events[<?= $idx ?>][id]" value="<?= $eId ?>">

                            <div class="flex items-center justify-between border-b border-slate-200/60 pb-3">
                                <div class="flex items-center gap-2">
                                    <span class="w-6 h-6 rounded-full bg-amber-500 text-white text-xs font-bold flex items-center justify-center"><?= $idx + 1 ?></span>
                                    <input 
                                        type="text" 
                                        name="events[<?= $idx ?>][event_name]" 
                                        value="<?= escape_html($eName) ?>" 
                                        placeholder="e.g. Holy Matrimony, Reception" 
                                        class="form-input text-sm font-bold text-slate-800 bg-white border border-slate-300 rounded-xl px-3 py-1.5 focus:border-amber-500" 
                                        required
                                    >
                                </div>
                                <label class="inline-flex items-center gap-2 text-xs font-semibold text-slate-700 cursor-pointer bg-white border border-slate-200 px-3 py-1.5 rounded-xl hover:bg-slate-50 transition">
                                    <input 
                                        type="radio" 
                                        name="primary_event_id" 
                                        value="<?= $eId ?>" 
                                        <?= $isPrimary ? 'checked' : '' ?> 
                                        class="text-amber-600 focus:ring-amber-500"
                                    >
                                    <span>Primary Ceremony (Countdown)</span>
                                </label>
                            </div>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label class="form-label text-xxs">Date *</label>
                                    <input type="date" name="events[<?= $idx ?>][event_date]" value="<?= escape_html($eDate) ?>" class="form-input text-xs" required>
                                </div>
                                <div>
                                    <label class="form-label text-xxs">Timezone</label>
                                    <input type="text" value="WIB (Asia/Jakarta)" class="form-input text-xs bg-slate-100 text-slate-500" readonly>
                                </div>
                            </div>

                            <!-- Invitation Times Container -->
                            <div class="bg-white border border-slate-200 rounded-xl p-3.5 space-y-2">
                                <div class="flex items-center justify-between">
                                    <label class="form-label text-xxs font-bold text-slate-800 flex items-center gap-1.5">
                                        <i class="fa-regular fa-clock text-amber-500"></i> Invitation Times (24-Hour WIB) *
                                    </label>
                                    <span class="text-[10px] text-slate-400 font-mono">Earliest time = Default</span>
                                </div>
                                <p class="text-[10px] text-slate-400">Specify one or more invitation time slots for this ceremony (e.g. 10:00, 11:00). Guests can be assigned to a specific time slot.</p>

                                <div class="invitation-times-list space-y-2 pt-1" id="times-list-<?= $idx ?>">
                                    <?php 
                                    $invTimes = !empty($evt['invitation_times']) ? $evt['invitation_times'] : [$eTime];
                                    foreach ($invTimes as $tVal): 
                                    ?>
                                        <div class="flex items-center gap-2 time-row">
                                            <input 
                                                type="time" 
                                                name="events[<?= $idx ?>][invitation_times][]" 
                                                value="<?= escape_html($tVal) ?>" 
                                                class="form-input text-xs w-36 bg-slate-50 focus:bg-white" 
                                                required
                                            >
                                            <button 
                                                type="button" 
                                                onclick="removeTimeRow(this)" 
                                                class="btn-remove-time text-slate-400 hover:text-red-500 text-xs p-1.5 rounded-lg transition"
                                                title="Remove Time Slot"
                                            >
                                                <i class="fa-solid fa-trash-can"></i>
                                            </button>
                                        </div>
                                    <?php endforeach; ?>
                                </div>

                                <div class="pt-1">
                                    <button 
                                        type="button" 
                                        onclick="addTimeRow(<?= $idx ?>)" 
                                        class="text-xs font-bold text-amber-600 hover:text-amber-700 inline-flex items-center gap-1.5 bg-amber-50 hover:bg-amber-100 border border-amber-200 px-3 py-1.5 rounded-xl transition cursor-pointer"
                                    >
                                        <i class="fa-solid fa-plus text-[10px]"></i> Add Invitation Time
                                    </button>
                                </div>
                            </div>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label class="form-label text-xxs">Venue Name *</label>
                                    <input type="text" name="events[<?= $idx ?>][venue_name]" value="<?= escape_html($evt['venue_name'] ?? '') ?>" placeholder="e.g. Grand Ballroom" class="form-input text-xs" required>
                                </div>
                                <div class="flex items-end pb-1">
                                    <label class="inline-flex items-center gap-2 text-xs font-semibold text-slate-700 cursor-pointer bg-white border border-slate-200 px-3 py-2 rounded-xl hover:bg-slate-50 transition w-full">
                                        <input 
                                            type="checkbox" 
                                            name="events[<?= $idx ?>][show_map]" 
                                            value="1" 
                                            <?= !isset($evt['show_map']) || !empty($evt['show_map']) ? 'checked' : '' ?> 
                                            class="text-amber-600 rounded focus:ring-amber-500"
                                        >
                                        <span>☑ Show Map on Invitation Page</span>
                                    </label>
                                </div>
                            </div>

                            <div>
                                <label class="form-label text-xxs">Venue Address *</label>
                                <textarea name="events[<?= $idx ?>][venue_address]" rows="2" placeholder="Full location address..." class="form-textarea text-xs" required><?= escape_html($evt['venue_address'] ?? '') ?></textarea>
                            </div>

                            <!-- Dedicated Google Maps Configuration Section (maps_url vs maps_embed_url) -->
                            <div class="bg-white border border-slate-200 rounded-xl p-4 space-y-4">
                                <div class="border-b border-slate-200/80 pb-2 flex items-center justify-between">
                                    <label class="form-label text-xs font-bold text-slate-800 flex items-center gap-1.5">
                                        <i class="fa-solid fa-map-location-dot text-amber-500"></i> Google Maps Configuration
                                    </label>
                                    <span class="text-[10px] bg-amber-50 text-amber-700 font-semibold px-2.5 py-0.5 rounded-full border border-amber-200">Interactive Map &amp; Navigation</span>
                                </div>

                                <!-- Field 1: Open in Google Maps URL (maps_url) -->
                                <div class="space-y-1">
                                    <label class="form-label text-xxs font-semibold text-slate-700">Open in Google Maps URL</label>
                                    <input 
                                        type="url" 
                                        name="events[<?= $idx ?>][maps_url]" 
                                        value="<?= escape_html($evt['maps_url'] ?? '') ?>" 
                                        placeholder="https://maps.app.goo.gl/..." 
                                        class="form-input text-xs <?= isset($errors["event_{$idx}_maps_url"]) ? 'is-invalid' : '' ?>"
                                    >
                                    <p class="text-[10px] text-slate-400 mt-1">
                                        Paste a Google Maps Share URL (e.g. <code>https://maps.app.goo.gl/...</code> or <code>https://www.google.com/maps/place/...</code>). Used for the "Open in Google Maps" button.
                                    </p>
                                    <?php if (isset($errors["event_{$idx}_maps_url"])): ?>
                                        <p class="text-xs text-red-500 font-semibold mt-1"><?= escape_html($errors["event_{$idx}_maps_url"]) ?></p>
                                    <?php endif; ?>
                                </div>

                                <!-- Field 2: Google Maps Embed URL (maps_embed_code) -->
                                <div class="space-y-2">
                                    <label class="form-label text-xxs font-semibold text-slate-700 flex items-center justify-between">
                                        <span>Google Maps Embed URL (Interactive Map)</span>
                                        <span class="text-[10px] text-slate-400 font-mono">maps_embed_url</span>
                                    </label>
                                    <textarea 
                                        name="events[<?= $idx ?>][maps_embed_code]" 
                                        rows="2" 
                                        placeholder="https://www.google.com/maps/embed?pb=..." 
                                        class="form-textarea text-xs font-mono bg-slate-50 focus:bg-white <?= isset($errors["event_{$idx}_maps_embed_code"]) ? 'is-invalid' : '' ?>"
                                    ><?= escape_html($evt['maps_embed_url'] ?? '') ?></textarea>
                                    <p class="text-[10px] text-slate-400 mt-1">
                                        Paste either a Google Maps Embed URL (e.g. <code>https://www.google.com/maps/embed?pb=...</code>) or full <code>&lt;iframe&gt;</code> code. The system will automatically extract and save only the Embed URL. Used for the Interactive Map displayed on the invitation.
                                    </p>
                                    <?php if (isset($errors["event_{$idx}_maps_embed_code"])): ?>
                                        <p class="text-xs text-red-500 font-semibold mt-1"><?= escape_html($errors["event_{$idx}_maps_embed_code"]) ?></p>
                                    <?php endif; ?>

                                    <!-- Quick Helper Box -->
                                    <div class="bg-amber-50/60 border border-amber-200/80 rounded-xl p-3 text-[11px] text-slate-700 space-y-1">
                                        <p class="font-bold text-amber-900 flex items-center gap-1">
                                            <span>💡</span> How to get Google Maps embed code:
                                        </p>
                                        <ol class="list-decimal pl-4 space-y-0.5 text-slate-600 leading-relaxed text-[11px]">
                                            <li>Open <a href="https://maps.google.com" target="_blank" class="underline text-amber-700 font-semibold">Google Maps</a> in your browser.</li>
                                            <li>Search your venue address or location name.</li>
                                            <li>Click <strong>Share</strong>, select <strong>Embed a map</strong>, click <strong>COPY HTML</strong>, and paste the code above.</li>
                                        </ol>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Card 3: Story & Visuals -->
            <div class="card p-6">
                <div class="border-b border-slate-100 pb-4 mb-5">
                    <h2 class="text-lg font-bold text-slate-800">Narrative & Visual Assets</h2>
                    <p class="text-xs text-slate-400 mt-0.5">Tell your love story and configure the landing page backdrop.</p>
                </div>
                <div class="space-y-6">
                    <div class="form-group">
                        <label for="love_story" class="form-label">Love Story Narrative</label>
                        <textarea 
                            name="love_story" 
                            id="love_story"
                            rows="5"
                            placeholder="Share how you first met, fell in love, and decided to marry..."
                            class="form-textarea <?= isset($errors['love_story']) ? 'is-invalid' : '' ?>"
                        ><?= escape_html((string) $val('love_story')) ?></textarea>
                        <?php if (isset($errors['love_story'])): ?>
                            <p class="form-error"><?= escape_html($errors['love_story']) ?></p>
                        <?php endif; ?>
                    </div>

                    <div class="form-group">
                        <label for="cover_image" class="form-label">Cover Image URL</label>
                        <input 
                            type="url" 
                            name="cover_image" 
                            id="cover_image"
                            value="<?= escape_html((string) $val('cover_image')) ?>"
                            placeholder="https://yourimagehost.com/wedding-photo.jpg"
                            class="form-input <?= isset($errors['cover_image']) ? 'is-invalid' : '' ?>"
                        >
                        <?php if (isset($errors['cover_image'])): ?>
                            <p class="form-error"><?= escape_html($errors['cover_image']) ?></p>
                        <?php endif; ?>
                    </div>

                    <div class="form-group">
                        <label for="hero_quote" class="form-label">Hero Quote / Verse</label>
                        <input 
                            type="text" 
                            name="hero_quote" 
                            id="hero_quote"
                            value="<?= escape_html((string) $val('hero_quote')) ?>"
                            placeholder="e.g. 'And the two shall become one' - Mark 10:8"
                            class="form-input <?= isset($errors['hero_quote']) ? 'is-invalid' : '' ?>"
                        >
                        <?php if (isset($errors['hero_quote'])): ?>
                            <p class="form-error"><?= escape_html($errors['hero_quote']) ?></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Card 4: RSVP System Settings (G010) -->
            <div class="card p-6">
                <div class="border-b border-slate-100 pb-4 mb-5">
                    <h2 class="text-lg font-bold text-slate-800">RSVP System &amp; Preferences</h2>
                    <p class="text-xs text-slate-400 mt-0.5">Configure RSVP attendance confirmation rules, deadlines, and guest note settings.</p>
                </div>
                <div class="space-y-5">
                    <div class="flex items-center gap-3">
                        <input 
                            type="checkbox" 
                            name="rsvp_enabled" 
                            id="rsvp_enabled"
                            value="1"
                            <?= $val('rsvp_enabled') ? 'checked' : '' ?>
                            class="w-4 h-4 text-amber-500 rounded border-slate-300 focus:ring-amber-400"
                        >
                        <label for="rsvp_enabled" class="text-xs font-bold text-slate-700 cursor-pointer">
                            Enable Public RSVP Form &amp; Attendance Confirmation
                        </label>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
                        <div class="form-group">
                            <label for="rsvp_closes_at" class="form-label">RSVP Deadline Date</label>
                            <?php
                                $deadlineVal = (string) $val('rsvp_closes_at');
                                if ($deadlineVal !== '') {
                                    $deadlineVal = date('Y-m-d\TH:i', strtotime($deadlineVal));
                                }
                            ?>
                            <input 
                                type="datetime-local" 
                                name="rsvp_closes_at" 
                                id="rsvp_closes_at"
                                value="<?= escape_html($deadlineVal) ?>"
                                class="form-input text-xs <?= isset($errors['rsvp_closes_at']) ? 'is-invalid' : '' ?>"
                            >
                            <p class="text-[10px] text-slate-400 mt-1">Form automatically locks after this timestamp.</p>
                            <?php if (isset($errors['rsvp_closes_at'])): ?>
                                <p class="form-error"><?= escape_html($errors['rsvp_closes_at']) ?></p>
                            <?php endif; ?>
                        </div>

                        <div class="space-y-3 pt-1">
                            <div class="flex items-center gap-2.5">
                                <input 
                                    type="checkbox" 
                                    name="rsvp_allow_edit" 
                                    id="rsvp_allow_edit"
                                    value="1"
                                    <?= $val('rsvp_allow_edit') ? 'checked' : '' ?>
                                    class="w-4 h-4 text-amber-500 rounded border-slate-300 focus:ring-amber-400"
                                >
                                <label for="rsvp_allow_edit" class="text-xs font-semibold text-slate-700 cursor-pointer">
                                    Allow guests to edit response before deadline
                                </label>
                            </div>

                            <div class="flex items-center gap-2.5">
                                <input 
                                    type="checkbox" 
                                    name="rsvp_notes_enabled" 
                                    id="rsvp_notes_enabled"
                                    value="1"
                                    <?= $val('rsvp_notes_enabled') ? 'checked' : '' ?>
                                    class="w-4 h-4 text-amber-500 rounded border-slate-300 focus:ring-amber-400"
                                >
                                <label for="rsvp_notes_enabled" class="text-xs font-semibold text-slate-700 cursor-pointer">
                                    Enable Guest Notes / Special Remarks field (max 500 chars)
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            <!-- Card 5: Guest Book & Wishes Settings (G011) -->
            <div class="card p-6">
                <div class="border-b border-slate-100 pb-4 mb-5">
                    <h2 class="text-lg font-bold text-slate-800">Guest Book &amp; Wishes Settings</h2>
                    <p class="text-xs text-slate-400 mt-0.5">Configure guest congratulatory wishes, moderation requirements, and public wall display rules.</p>
                </div>
                <div class="space-y-5">
                    <div class="flex items-center gap-3">
                        <input 
                            type="checkbox" 
                            name="wishes_enabled" 
                            id="wishes_enabled"
                            value="1"
                            <?= $val('wishes_enabled') ? 'checked' : '' ?>
                            class="w-4 h-4 text-amber-500 rounded border-slate-300 focus:ring-amber-400"
                        >
                        <label for="wishes_enabled" class="text-xs font-bold text-slate-700 cursor-pointer">
                            Enable Guest Book &amp; Wishes Section
                        </label>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
                        <div class="space-y-3">
                            <div class="flex items-center gap-2.5">
                                <input 
                                    type="checkbox" 
                                    name="wishes_display_public" 
                                    id="wishes_display_public"
                                    value="1"
                                    <?= $val('wishes_display_public') ? 'checked' : '' ?>
                                    class="w-4 h-4 text-amber-500 rounded border-slate-300 focus:ring-amber-400"
                                >
                                <label for="wishes_display_public" class="text-xs font-semibold text-slate-700 cursor-pointer">
                                    Display approved wishes publicly on invitation
                                </label>
                            </div>

                            <div class="flex items-center gap-2.5">
                                <input 
                                    type="checkbox" 
                                    name="wishes_require_moderation" 
                                    id="wishes_require_moderation"
                                    value="1"
                                    <?= $val('wishes_require_moderation') ? 'checked' : '' ?>
                                    class="w-4 h-4 text-amber-500 rounded border-slate-300 focus:ring-amber-400"
                                >
                                <label for="wishes_require_moderation" class="text-xs font-semibold text-slate-700 cursor-pointer">
                                    Require couple approval before displaying publicly
                                </label>
                            </div>
                        </div>

                        <div class="space-y-4">
                            <div class="form-group">
                                <label for="wishes_max_char_limit" class="form-label">Maximum Character Limit per Wish</label>
                                <input 
                                    type="number" 
                                    name="wishes_max_char_limit" 
                                    id="wishes_max_char_limit"
                                    min="50"
                                    max="5000"
                                    value="<?= escape_html((string)($val('wishes_max_char_limit') ?: 1000)) ?>"
                                    class="form-input text-xs"
                                >
                            </div>

                            <div class="form-group">
                                <label for="wishes_sort_order" class="form-label">Public Display Sort Order</label>
                                <select name="wishes_sort_order" id="wishes_sort_order" class="form-select text-xs">
                                    <option value="newest" <?= $val('wishes_sort_order') === 'newest' ? 'selected' : '' ?>>Newest First</option>
                                    <option value="oldest" <?= $val('wishes_sort_order') === 'oldest' ? 'selected' : '' ?>>Oldest First</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>

        <!-- Right Column: Sidebar actions -->
        <div class="lg:col-span-1 space-y-6">

            <!-- Card 4: Theme Selection -->
            <div class="card p-6">
                <div class="border-b border-slate-100 pb-4 mb-5">
                    <h2 class="text-sm font-bold text-slate-800 uppercase tracking-wider">Design Theme</h2>
                </div>
                <div class="form-group">
                    <label for="theme_version_id" class="form-label">Theme Version *</label>
                    <select 
                        name="theme_version_id" 
                        id="theme_version_id"
                        class="form-select <?= isset($errors['theme_version_id']) ? 'is-invalid' : '' ?>"
                        required
                    >
                        <?php foreach ($themes as $themeOption): ?>
                            <?php 
                            $optionId = (int) $themeOption['id'];
                            $selected = ($optionId === (int) $val('theme_version_id')) ? 'selected' : '';
                            ?>
                            <option value="<?= $optionId ?>" <?= $selected ?>>
                                <?= escape_html($themeOption['theme_name']) ?> (v<?= escape_html($themeOption['version_number']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (isset($errors['theme_version_id'])): ?>
                        <p class="form-error"><?= escape_html($errors['theme_version_id']) ?></p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Card 5: Publish Controls -->
            <div class="card p-6">
                <div class="border-b border-slate-100 pb-4 mb-5">
                    <h2 class="text-sm font-bold text-slate-800 uppercase tracking-wider">Save & Publish</h2>
                </div>
                <div class="space-y-3">
                    <!-- Save Draft Button -->
                    <button 
                        type="submit" 
                        class="btn btn-secondary btn-md w-full"
                        onclick="document.getElementById('invitation-status-input').value = 'draft';"
                    >
                        Save as Draft
                    </button>

                    <!-- Publish Button -->
                    <button 
                        type="submit" 
                        class="btn btn-primary btn-md w-full"
                        onclick="document.getElementById('invitation-status-input').value = 'published';"
                    >
                        🚀 Save &amp; Publish
                    </button>
                </div>
            </div>

        </div>
    </form>
</div>

<script>
function addTimeRow(evtIdx) {
    const container = document.getElementById('times-list-' + evtIdx);
    if (!container) return;

    const div = document.createElement('div');
    div.className = 'flex items-center gap-2 time-row';
    div.innerHTML = `
        <input 
            type="time" 
            name="events[${evtIdx}][invitation_times][]" 
            value="12:00" 
            class="form-input text-xs w-36 bg-slate-50 focus:bg-white" 
            required
        >
        <button 
            type="button" 
            onclick="removeTimeRow(this)" 
            class="btn-remove-time text-slate-400 hover:text-red-500 text-xs p-1.5 rounded-lg transition"
            title="Remove Time Slot"
        >
            <i class="fa-solid fa-trash-can"></i>
        </button>
    `;
    container.appendChild(div);
    updateTimeRemoveButtons(container);
}

function removeTimeRow(btn) {
    const row = btn.closest('.time-row');
    const container = row ? row.parentElement : null;
    if (container && container.querySelectorAll('.time-row').length > 1) {
        row.remove();
        updateTimeRemoveButtons(container);
    }
}

function updateTimeRemoveButtons(container) {
    const rows = container.querySelectorAll('.time-row');
    rows.forEach(r => {
        const btn = r.querySelector('.btn-remove-time');
        if (btn) {
            btn.disabled = (rows.length <= 1);
            btn.style.opacity = (rows.length <= 1) ? '0.3' : '1';
            btn.style.cursor = (rows.length <= 1) ? 'not-allowed' : 'pointer';
        }
    });
}

document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('[id^="times-list-"]').forEach(container => {
        updateTimeRemoveButtons(container);
    });
});
</script>
