<?php
/**
 * Couple Portal — Wedding Planning Command Center Dashboard 2.0 (RC-021C)
 * Location: app/views/invitation/dashboard.php
 */

if (!function_exists('format_money')) {
    function format_money(float $amount, string $currency = 'IDR'): string
    {
        if ($currency === 'IDR') {
            return 'Rp ' . number_format($amount, 0, ',', '.');
        }
        return $currency . ' ' . number_format($amount, 2, '.', ',');
    }
}

$groom = $workspace['groom_name'] ?: 'Groom';
$bride = $workspace['bride_name'] ?: 'Bride';
$weddingDate = new \DateTime($workspace['wedding_date']);

$isOverBudget = $budget_difference < 0.00;
$diffBadgeColor = $isOverBudget ? 'bg-rose-50 border-rose-100 text-rose-700' : 'bg-emerald-50 border-emerald-100 text-emerald-700';
$diffLabel = $isOverBudget ? 'Over Budget' : 'Remaining Budget';
?>

<div class="max-w-6xl mx-auto space-y-6">

    <!-- ── SECTION 2: HERO SECTION ──────────────────────────────────────── -->
    <div class="relative rounded-3xl p-6 text-white overflow-hidden shadow-sm" style="background-color:#232323;">
        <div class="absolute -right-16 -bottom-16 w-60 h-60 rounded-full" style="background:rgba(212,162,140,0.06); filter:blur(40px);"></div>
        
        <div class="relative flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
            <div class="space-y-2">
                <div class="flex flex-wrap items-center gap-2">
                    <span class="inline-block text-[10px] tracking-widest uppercase px-3 py-0.5 rounded-full font-bold" style="background:rgba(255,255,255,0.10); color:#FAF8F3;">
                        Command Center
                    </span>
                    <span class="inline-block text-[9px] font-bold px-2 py-0.5 rounded-full uppercase" style="background:rgba(212,162,140,0.15); color:#D4A28C; border:1px solid rgba(212,162,140,0.25);">
                        Plan: <?= escape_html($workspace['plan_name']) ?>
                    </span>
                </div>
                <h1 class="text-2xl md:text-3xl font-black tracking-tight text-white leading-tight">
                    <?= escape_html($groom) ?> &amp; <?= escape_html($bride) ?>
                </h1>
                <div class="flex items-center gap-2 text-xs" style="color:#FAF8F3; opacity:0.8;">
                    <i class="fa-solid fa-calendar-days" style="color:#D4A28C;"></i>
                    <span><?= escape_html($weddingDate->format('d F Y')) ?></span>
                    <span>·</span>
                    <span class="font-bold text-white"><?= $countdown_days ?> Days Remaining</span>
                </div>
            </div>

            <!-- Hero Action Buttons -->
            <div class="flex flex-wrap items-center gap-2 w-full md:w-auto pt-2 md:pt-0">
                <a href="<?= url('/app/couple/invitation/edit') ?>" class="px-4 py-2 transition-all font-bold text-xs text-white rounded-xl flex items-center gap-1.5 w-full sm:w-auto justify-center" style="background:rgba(255,255,255,0.10); border:1px solid rgba(255,255,255,0.15);" onmouseover="this.style.background='rgba(255,255,255,0.16)'" onmouseout="this.style.background='rgba(255,255,255,0.10)'">
                    <i class="fa-solid fa-eye" style="color:#D4A28C;"></i> Preview Invitation
                </a>
                <a href="<?= url('/app/couple/budget') ?>" class="px-4 py-2 transition-all font-bold text-xs rounded-xl flex items-center gap-1.5 w-full sm:w-auto justify-center" style="background:#D4A28C; color:#232323;" onmouseover="this.style.background='#C48B72'" onmouseout="this.style.background='#D4A28C'">
                    <i class="fa-solid fa-wallet"></i> Budget Planner
                </a>
                <a href="<?= url('/app/couple/timeline') ?>" class="px-4 py-2 transition-all font-bold text-xs text-white rounded-xl flex items-center gap-1.5 w-full sm:w-auto justify-center" style="background:rgba(255,255,255,0.06); border:1px solid rgba(255,255,255,0.10);" onmouseover="this.style.background='rgba(255,255,255,0.12)'" onmouseout="this.style.background='rgba(255,255,255,0.06)'">
                    <i class="fa-solid fa-clock-rotate-left" style="color:#FAF8F3; opacity:0.6;"></i> Timeline Planner
                </a>
            </div>
        </div>
    </div>

    <!-- ── SECTION 3: TODAY'S FOCUS ────────────────────────────────────── -->
    <div class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm flex flex-col justify-between">
        <div>
            <h3 class="font-black text-slate-800 text-sm flex items-center gap-2 mb-3">
                <i class="fa-solid fa-bullseye" style="color:#D4A28C;"></i> Today's Focus
            </h3>
            
            <?php if (empty($focus_items)): ?>
                <div class="flex flex-col items-center justify-center py-6 text-slate-400 text-center">
                    <span class="text-2xl mb-1.5">🎉</span>
                    <p class="text-xs font-semibold">No important task today.</p>
                </div>
            <?php else: ?>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-48 overflow-y-auto pr-1">
                    <?php foreach ($focus_items as $item): ?>
                        <a href="<?= $item['link'] ?>" class="p-3 rounded-xl border border-slate-100 bg-slate-50 hover:bg-slate-100 flex items-center justify-between text-xs transition-all hover:border-indigo-200 group">
                            <div class="flex items-center gap-2.5 min-w-0">
                                <span class="w-7 h-7 rounded-lg bg-white border border-slate-100 flex items-center justify-center text-xs flex-shrink-0 group-hover:bg-indigo-50">
                                    <i class="<?= $item['icon'] ?>"></i>
                                </span>
                                <div class="truncate">
                                    <span class="font-bold text-slate-700 block truncate"><?= escape_html($item['title']) ?></span>
                                    <span class="text-[9px] text-slate-400 uppercase font-extrabold tracking-wider mt-0.5 block"><?= $item['type'] ?></span>
                                </div>
                            </div>
                            <i class="fa-solid fa-chevron-right text-slate-350 text-[10px] group-hover:translate-x-0.5 transition-transform ml-2"></i>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- ── SECTION: YOUR INVITATION (G014.2 — Dashboard URL Card) ──────── -->
    <?php
        $wSlug           = $workspace['slug'] ?? '';
        $invStatus       = $workspace['invitation_status'] ?? 'draft';
        $isPublished     = $invStatus === 'published';
        $isArchived      = $invStatus === 'archived';

        // Derive full URLs — APP_URL is the canonical base (no trailing slash)
        $appBase         = defined('APP_URL') ? rtrim((string) APP_URL, '/') : '';
        $livePreviewUrl  = $appBase . '/' . $wSlug . '/livepreview';
        $publicUrl       = $appBase . '/' . $wSlug;
        $guestPatternUrl = $appBase . '/' . $wSlug . '/{guest_token}';

        if ($invStatus === 'published') {
            $statusBadge = ['label' => 'Published', 'class' => 'bg-emerald-100 text-emerald-700 border-emerald-200'];
        } elseif ($invStatus === 'archived') {
            $statusBadge = ['label' => 'Archived',  'class' => 'bg-slate-100 text-slate-500 border-slate-200'];
        } else {
            $statusBadge = ['label' => 'Draft',     'class' => 'bg-amber-100 text-amber-700 border-amber-200'];
        }
    ?>
    <div class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm space-y-5" id="dashboard-url-card">

        <!-- Card header -->
        <div class="flex items-center justify-between border-b border-slate-100 pb-3">
            <h3 class="font-black text-slate-800 text-sm flex items-center gap-2">
                <i class="fa-solid fa-globe" style="color:#D4A28C;"></i> Your Invitation
            </h3>
            <span class="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-bold border <?= $statusBadge['class'] ?>">
                <?php if ($isPublished): ?>
                    <span class="w-1.5 h-1.5 rounded-full bg-emerald-500 inline-block"></span>
                <?php elseif ($isArchived): ?>
                    <span class="w-1.5 h-1.5 rounded-full bg-slate-400 inline-block"></span>
                <?php else: ?>
                    <span class="w-1.5 h-1.5 rounded-full bg-amber-500 inline-block animate-pulse"></span>
                <?php endif; ?>
                <?= $statusBadge['label'] ?>
            </span>
        </div>

        <!-- Slug -->
        <div class="space-y-1">
            <p class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Slug</p>
            <code class="text-xs font-mono font-bold text-slate-700 bg-slate-50 border border-slate-200 px-3 py-1.5 rounded-lg inline-block"><?= escape_html($wSlug) ?></code>
        </div>

        <!-- Live Preview URL — always available -->
        <div class="space-y-2">
            <p class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Live Preview</p>
            <div class="flex items-center gap-2 bg-slate-50 border border-slate-200 rounded-xl px-3 py-2">
                <code class="text-[11px] font-mono text-slate-600 flex-1 truncate" title="<?= escape_html($livePreviewUrl) ?>"><?= escape_html($livePreviewUrl) ?></code>
                <div class="flex items-center gap-1.5 flex-shrink-0">
                    <a href="<?= escape_html($livePreviewUrl) ?>" target="_blank" rel="noopener noreferrer"
                       class="inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-bold rounded-lg border border-slate-300 text-slate-700 bg-white hover:bg-slate-100 transition"
                       title="Open Live Preview">
                        <i class="fa-solid fa-arrow-up-right-from-square text-[9px]"></i> Open
                    </a>
                    <button type="button"
                            onclick="invCopyUrl('<?= escape_html($livePreviewUrl) ?>', this)"
                            class="inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-bold rounded-lg border border-slate-300 text-slate-700 bg-white hover:bg-slate-100 transition"
                            title="Copy Live Preview URL">
                        <i class="fa-solid fa-copy text-[9px]"></i> Copy
                    </button>
                </div>
            </div>
        </div>

        <!-- Public Invitation URL — gated on publish status -->
        <div class="space-y-2">
            <p class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Public Invitation</p>
            <?php if ($isPublished): ?>
                <div class="flex items-center gap-2 bg-emerald-50 border border-emerald-200 rounded-xl px-3 py-2">
                    <code class="text-[11px] font-mono text-emerald-700 flex-1 truncate" title="<?= escape_html($publicUrl) ?>"><?= escape_html($publicUrl) ?></code>
                    <div class="flex items-center gap-1.5 flex-shrink-0">
                        <a href="<?= escape_html($publicUrl) ?>" target="_blank" rel="noopener noreferrer"
                           class="inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-bold rounded-lg border border-emerald-300 text-emerald-700 bg-white hover:bg-emerald-100 transition"
                           title="Open Public Invitation">
                            <i class="fa-solid fa-arrow-up-right-from-square text-[9px]"></i> Open
                        </a>
                        <button type="button"
                                onclick="invCopyUrl('<?= escape_html($publicUrl) ?>', this)"
                                class="inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-bold rounded-lg border border-emerald-300 text-emerald-700 bg-white hover:bg-emerald-100 transition"
                                title="Copy Public Invitation URL">
                            <i class="fa-solid fa-copy text-[9px]"></i> Copy
                        </button>
                    </div>
                </div>
            <?php else: ?>
                <div class="flex items-center gap-2 bg-slate-50 border border-slate-200 border-dashed rounded-xl px-3 py-2">
                    <code class="text-[11px] font-mono text-slate-400 flex-1 truncate"><?= escape_html($publicUrl) ?></code>
                    <span class="text-[10px] font-bold text-slate-400 italic flex-shrink-0">Available after Publish</span>
                </div>
            <?php endif; ?>
        </div>

        <!-- Guest URL Pattern — informational only, no real token exposed -->
        <div class="space-y-1.5">
            <p class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Guest URL Pattern</p>
            <div class="flex items-center gap-2 bg-slate-50 border border-slate-200 rounded-xl px-3 py-2">
                <code class="text-[11px] font-mono text-slate-500 flex-1 truncate" title="<?= escape_html($guestPatternUrl) ?>"><?= escape_html($guestPatternUrl) ?></code>
                <span class="text-[9px] font-bold text-slate-300 uppercase tracking-wider flex-shrink-0">Pattern</span>
            </div>
            <p class="text-[9px] text-slate-400 font-medium">Each guest receives a unique personalised URL. The token is generated when you send the invitation.</p>
        </div>

    </div>

    <!-- Copy-to-clipboard helper (scoped, no global namespace pollution) -->
    <script>
    function invCopyUrl(url, btn) {
        navigator.clipboard.writeText(url).then(function () {
            const original = btn.innerHTML;
            btn.innerHTML = '<i class="fa-solid fa-check text-[9px]"></i> Copied!';
            btn.classList.add('border-emerald-400', 'text-emerald-700');
            setTimeout(function () {
                btn.innerHTML = original;
                btn.classList.remove('border-emerald-400', 'text-emerald-700');
            }, 2000);
        }).catch(function () {
            // Fallback for non-HTTPS contexts (local dev)
            const ta = document.createElement('textarea');
            ta.value = url;
            ta.style.position = 'fixed';
            ta.style.opacity = '0';
            document.body.appendChild(ta);
            ta.select();
            document.execCommand('copy');
            document.body.removeChild(ta);
        });
    }
    </script>

    <!-- ── SECTION 4: BUDGET COMMAND CENTER ──────────────────────────────── -->

    <div class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm space-y-6">
        
        <div class="flex items-center justify-between border-b border-slate-100 pb-3">
            <h3 class="font-black text-slate-800 text-sm flex items-center gap-2">
                <i class="fa-solid fa-wallet" style="color:#D4A28C;"></i> Budget Command Center
            </h3>
            <a href="<?= url('/app/couple/budget') ?>" class="text-xs font-extrabold flex items-center gap-0.5" style="color:#232323;" onmouseover="this.style.color='#D4A28C'" onmouseout="this.style.color='#232323'">
                Open Budget Planner <i class="fa-solid fa-arrow-right"></i>
            </a>
        </div>

        <!-- Budget Stats summaries -->
        <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
            <div class="p-4 rounded-2xl bg-slate-50 border border-slate-100">
                <span class="text-[9px] font-bold text-slate-400 block uppercase tracking-wider">Total Target Budget</span>
                <span class="text-base font-black text-slate-800 block mt-1"><?= format_money($total_budget, $currency) ?></span>
            </div>

            <div class="p-4 rounded-2xl bg-slate-50 border border-slate-100">
                <span class="text-[9px] font-bold text-slate-400 block uppercase tracking-wider">Negotiated Total (Deals)</span>
                <span class="text-base font-black text-[#A8735C] block mt-1"><?= format_money($actual_deal_value, $currency) ?></span>
            </div>

            <div class="p-4 rounded-2xl bg-slate-50 border border-slate-100">
                <span class="text-[9px] font-bold text-slate-400 block uppercase tracking-wider">Paid Amount</span>
                <span class="text-base font-black text-emerald-600 block mt-1"><?= format_money($paid, $currency) ?></span>
            </div>

            <div class="p-4 rounded-2xl bg-slate-50 border border-slate-100">
                <span class="text-[9px] font-bold text-slate-400 block uppercase tracking-wider">Remaining Balance</span>
                <span class="text-base font-black text-slate-800 block mt-1"><?= format_money($remaining_cash, $currency) ?></span>
            </div>

            <div class="p-4 rounded-2xl border <?= $diffBadgeColor ?>">
                <span class="text-[9px] font-bold text-slate-400 block uppercase tracking-wider"><?= $diffLabel ?></span>
                <span class="text-base font-black block mt-1"><?= format_money(abs($budget_difference), $currency) ?></span>
            </div>
        </div>

        <!-- Budget breakdown Categories visual rows progress bars -->
        <div class="space-y-4">
            <h4 class="font-extrabold text-slate-700 text-xs uppercase tracking-wider border-b border-slate-50 pb-2">Category Allocations and Settlement Progress</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
                <?php foreach ($budget_breakdown as $cat): 
                    $targetCost = $cat['actual'] > 0 ? $cat['actual'] : $cat['planned'];
                    $settlementPct = $targetCost > 0 ? ($cat['paid'] / $targetCost) * 100 : 0.0;
                    $diffVal = $cat['difference'];
                    $diffClass = $diffVal > 0.00 ? 'text-green-600 font-semibold' : ($diffVal < 0.00 ? 'text-rose-600 font-semibold' : 'text-slate-400');
                    $diffSign = $diffVal > 0.00 ? '+' : '';
                ?>
                    <div class="p-3 rounded-2xl border border-slate-100 bg-slate-50/50 flex flex-col justify-between space-y-2">
                        <div class="flex justify-between items-start">
                            <div>
                                <span class="font-bold text-slate-850 text-xs block"><?= escape_html($cat['name']) ?></span>
                                <span class="text-[9px] text-slate-400 block mt-0.5">
                                    Budget: <?= format_money($cat['planned'], $currency) ?> 
                                    · Deal: <?= $cat['actual'] > 0 ? format_money($cat['actual'], $currency) : '<span class="italic text-[8px]">Unnegotiated</span>' ?>
                                </span>
                            </div>
                            <div class="text-right">
                                <span class="font-bold text-slate-700 text-xs block">Remaining: <?= format_money($cat['remaining'], $currency) ?></span>
                                <?php if ($cat['actual'] > 0.00): ?>
                                    <span class="text-[8px] <?= $diffClass ?> block mt-0.5">Variance: <?= $diffSign . format_money($diffVal, $currency) ?></span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Progress visual indicator -->
                        <div class="space-y-1">
                            <div class="flex justify-between items-center text-[9px] font-bold text-slate-450 uppercase">
                                <span>Paid Settlement</span>
                                <span class="font-mono"><?= number_format($settlementPct, 0) ?>%</span>
                            </div>
                            <div class="w-full bg-slate-200/70 h-2 rounded-full overflow-hidden">
                                <div class="bg-[#D4A28C] h-full rounded-full transition-all duration-300" style="width: <?= $settlementPct ?>%"></div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

    </div>

    <!-- ── Row 3: Upcoming Payments & Timeline ───────────────────────────── -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        
        <!-- SECTION 5: UPCOMING PAYMENTS -->
        <div class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm flex flex-col justify-between">
            <div>
                <h3 class="font-black text-slate-800 text-sm flex items-center gap-2 border-b border-slate-50 pb-3">
                    <i class="fa-solid fa-money-bill-wave text-[#D4A28C]"></i> Upcoming Payments
                </h3>

                <?php if (empty($upcoming_payments)): ?>
                    <div class="text-center py-8 text-slate-400 text-xs">
                        No upcoming due payments.
                    </div>
                <?php else: ?>
                    <div class="space-y-2 mt-3 max-h-60 overflow-y-auto pr-1">
                        <?php foreach ($upcoming_payments as $p): ?>
                            <a href="<?= url('/app/couple/budget') ?>" class="p-3 rounded-xl border border-slate-100 bg-slate-50 hover:bg-slate-100 transition-all flex justify-between items-center text-xs">
                                <div>
                                    <span class="font-bold text-slate-700 block"><?= escape_html($p['expense_name']) ?></span>
                                    <span class="text-[9px] text-slate-450 block mt-0.5">
                                        Category: <?= escape_html($p['category_name']) ?> 
                                        <?php if ($p['vendor_id']): ?>
                                            · Vendor: <strong class="text-[#A8735C]"><?= escape_html($p['vendor_name']) ?></strong>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                <div class="text-right whitespace-nowrap">
                                    <span class="font-black text-amber-600 block"><?= format_money($p['remaining_balance'], $currency) ?></span>
                                    <span class="text-[8px] text-slate-400 font-bold block mt-0.5">Due: <?= date('d M Y', strtotime($p['due_date'])) ?></span>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- SECTION 6: TIMELINE SUMMARY -->
        <div class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm flex flex-col justify-between">
            <div>
                <div class="flex items-center justify-between border-b border-slate-50 pb-3">
                    <h3 class="font-black text-slate-800 text-sm flex items-center gap-2">
                        <i class="fa-solid fa-clock-rotate-left text-[#D4A28C]"></i> Timeline Summary
                    </h3>
                    <a href="<?= url('/app/couple/timeline') ?>" class="px-2.5 py-1 bg-slate-100 hover:bg-slate-200 transition-all text-[10px] font-bold text-slate-700 rounded-lg">
                        Open Timeline Planner
                    </a>
                </div>

                <div class="grid grid-cols-2 md:grid-cols-5 gap-3 mt-3">
                    <div class="p-3.5 rounded-2xl bg-slate-50 border border-slate-100 text-center">
                        <span class="text-[8px] font-bold text-slate-400 block uppercase">Completed</span>
                        <span class="text-xl font-black text-emerald-600 block mt-1"><?= $timeline_summary['completed'] ?></span>
                    </div>

                    <div class="p-3.5 rounded-2xl bg-slate-50 border border-slate-100 text-center">
                        <span class="text-[8px] font-bold text-slate-400 block uppercase">Remaining</span>
                        <span class="text-xl font-black text-slate-800 block mt-1"><?= $timeline_summary['remaining'] ?></span>
                    </div>

                    <div class="p-3.5 rounded-2xl bg-slate-50 border border-slate-100 text-center">
                        <span class="text-[8px] font-bold text-slate-450 block uppercase">Due Today</span>
                        <span class="text-xl font-black text-[#A8735C] block mt-1"><?= $timeline_summary['due_this_week'] > 0 ? 1 : 0 ?></span>
                    </div>

                    <div class="p-3.5 rounded-2xl bg-slate-50 border border-slate-100 text-center">
                        <span class="text-[8px] font-bold text-slate-450 block uppercase">This Week</span>
                        <span class="text-xl font-black text-slate-700 block mt-1"><?= $timeline_summary['due_this_week'] ?></span>
                    </div>

                    <div class="p-3.5 rounded-2xl bg-rose-50/50 border border-rose-100 text-center">
                        <span class="text-[8px] font-bold text-rose-500 block uppercase">Overdue</span>
                        <span class="text-xl font-black text-rose-600 block mt-1"><?= $timeline_summary['overdue'] ?></span>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <!-- ── Row 4: Guest List Progress & Recent Activities ────────────────── -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        
    <!-- ── SECTION 7: G012 ENGAGEMENT & DELIVERY ANALYTICS ──────────────── -->
    <div class="space-y-6" x-data="{
        progressLoading: false,
        filter: '<?= escape_html($progress_filters['filter'] ?? 'all') ?>',
        search: '<?= escape_html($progress_filters['search'] ?? '') ?>',
        navigateProgress(targetUrl) {
            this.progressLoading = true;
            let url = new URL(targetUrl, window.location.origin);
            url.searchParams.set('ajax', '1');
            fetch(url.toString())
                .then(res => res.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    const wrapper = doc.getElementById('progress-table-wrapper');
                    if (wrapper) {
                        document.getElementById('progress-table-wrapper').innerHTML = wrapper.innerHTML;
                    }
                    window.history.pushState({}, '', targetUrl);
                    this.progressLoading = false;
                })
                .catch(err => {
                    console.error(err);
                    this.progressLoading = false;
                });
        },
        updateProgress() {
            let url = new URL(window.location.href);
            url.searchParams.set('filter', this.filter);
            url.searchParams.set('search', this.search);
            url.searchParams.set('page', '1');
            this.navigateProgress(url.toString());
        }
    }">

        <!-- Analytics Overview Cards Grid (3 Columns) -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            
            <!-- 1. Invitation Delivery Analytics -->
            <div class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm flex flex-col justify-between space-y-4">
                <div class="flex items-center justify-between border-b border-slate-50 pb-3">
                    <h3 class="font-black text-slate-800 text-sm flex items-center gap-2">
                        <i class="fa-solid fa-paper-plane text-[#D4A28C]"></i> Invitation Delivery
                    </h3>
                    <span class="text-xs font-black text-emerald-600 bg-emerald-50 px-2.5 py-0.5 rounded-full border border-emerald-100">
                        <?= number_format((float)($delivery_stats['opening_rate'] ?? 0), 1) ?>% Opened
                    </span>
                </div>

                <div class="grid grid-cols-3 gap-2">
                    <div class="p-3 rounded-2xl bg-slate-50 border border-slate-100 text-center">
                        <span class="text-[8px] font-bold text-slate-400 block uppercase tracking-wider">Total</span>
                        <span class="text-base font-black text-slate-800 block mt-1"><?= (int)($delivery_stats['total'] ?? 0) ?></span>
                    </div>

                    <div class="p-3 rounded-2xl bg-emerald-50/50 border border-emerald-100 text-center">
                        <span class="text-[8px] font-bold text-emerald-700 block uppercase tracking-wider">Opened</span>
                        <span class="text-base font-black text-emerald-600 block mt-1"><?= (int)($delivery_stats['opened'] ?? 0) ?></span>
                    </div>

                    <div class="p-3 rounded-2xl bg-rose-50/40 border border-rose-100 text-center">
                        <span class="text-[8px] font-bold text-rose-500 block uppercase tracking-wider">Not Opened</span>
                        <span class="text-base font-black text-rose-600 block mt-1"><?= (int)($delivery_stats['not_opened'] ?? 0) ?></span>
                    </div>
                </div>

                <!-- Progress Bar -->
                <div class="space-y-1">
                    <div class="flex justify-between text-[9px] font-bold text-slate-400 uppercase">
                        <span>Opening Progress</span>
                        <span><?= (int)($delivery_stats['opened'] ?? 0) ?> / <?= (int)($delivery_stats['total'] ?? 0) ?> Guests</span>
                    </div>
                    <div class="w-full bg-slate-100 h-2 rounded-full overflow-hidden">
                        <div class="bg-[#D4A28C] h-full rounded-full transition-all duration-300" style="width: <?= (float)($delivery_stats['opening_rate'] ?? 0) ?>%"></div>
                    </div>
                </div>
            </div>

            <!-- 2. RSVP Progress & Expected Attendance Analytics -->
            <div class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm flex flex-col justify-between space-y-4">
                <div class="flex items-center justify-between border-b border-slate-50 pb-3">
                    <h3 class="font-black text-slate-800 text-sm flex items-center gap-2">
                        <i class="fa-solid fa-users text-[#D4A28C]"></i> RSVP Progress
                    </h3>
                    <a href="<?= url('/app/couple/engagement/rsvp') ?>" class="text-[10px] font-extrabold text-[#D4A28C] hover:underline">
                        RSVP Center <i class="fa-solid fa-arrow-right"></i>
                    </a>
                </div>

                <div class="grid grid-cols-3 gap-2">
                    <div class="p-3 rounded-2xl bg-amber-50/45 border border-amber-100 text-center">
                        <span class="text-[8px] font-bold text-amber-600 block uppercase tracking-wider">Pending</span>
                        <span class="text-base font-black text-amber-650 block mt-1"><?= (int)($guest_summary['pending'] ?? 0) ?></span>
                    </div>

                    <div class="p-3 rounded-2xl bg-emerald-50/50 border border-emerald-100 text-center">
                        <span class="text-[8px] font-bold text-emerald-700 block uppercase tracking-wider">Attending</span>
                        <span class="text-base font-black text-emerald-600 block mt-1"><?= (int)($guest_summary['confirmed'] ?? 0) ?></span>
                    </div>

                    <div class="p-3 rounded-2xl bg-rose-50/40 border border-rose-100 text-center">
                        <span class="text-[8px] font-bold text-rose-500 block uppercase tracking-wider">Declined</span>
                        <span class="text-base font-black text-rose-600 block mt-1"><?= (int)($guest_summary['declined'] ?? 0) ?></span>
                    </div>
                </div>

                <div class="flex justify-between items-center bg-slate-50 border border-slate-100 rounded-2xl p-3 text-xs">
                    <div>
                        <span class="text-[9px] font-bold text-slate-400 block uppercase tracking-wider">Expected Attendance</span>
                        <span class="font-black text-slate-800 text-sm block mt-0.5"><?= (int)($guest_summary['confirmed_pax'] ?? 0) ?> Pax</span>
                    </div>
                    <a href="<?= url('/app/couple/guests') ?>" class="px-2.5 py-1 bg-white hover:bg-slate-100 border border-slate-200 text-[10px] font-bold text-slate-700 rounded-lg shadow-sm">
                        Guest List
                    </a>
                </div>
            </div>

            <!-- 3. Guest Book Analytics -->
            <div class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm flex flex-col justify-between space-y-4">
                <div class="flex items-center justify-between border-b border-slate-50 pb-3">
                    <h3 class="font-black text-slate-800 text-sm flex items-center gap-2">
                        <i class="fa-solid fa-heart-pulse text-[#D4A28C]"></i> Guest Book Wishes
                    </h3>
                    <a href="<?= url('/app/couple/engagement/wishes') ?>" class="text-[10px] font-extrabold text-[#D4A28C] hover:underline">
                        Moderate <i class="fa-solid fa-arrow-right"></i>
                    </a>
                </div>

                <div class="grid grid-cols-3 gap-2">
                    <div class="p-3 rounded-2xl bg-emerald-50/50 border border-emerald-100 text-center">
                        <span class="text-[8px] font-bold text-emerald-700 block uppercase tracking-wider">Approved</span>
                        <span class="text-base font-black text-emerald-600 block mt-1"><?= (int)($stats['approved_wishes'] ?? 0) ?></span>
                    </div>

                    <div class="p-3 rounded-2xl bg-amber-50/45 border border-amber-100 text-center">
                        <span class="text-[8px] font-bold text-amber-600 block uppercase tracking-wider">Pending</span>
                        <span class="text-base font-black text-amber-650 block mt-1"><?= (int)($stats['pending_wishes'] ?? 0) ?></span>
                    </div>

                    <div class="p-3 rounded-2xl bg-rose-50/40 border border-rose-100 text-center">
                        <span class="text-[8px] font-bold text-rose-500 block uppercase tracking-wider">Rejected</span>
                        <span class="text-base font-black text-rose-600 block mt-1"><?= (int)($stats['rejected_wishes'] ?? 0) ?></span>
                    </div>
                </div>

                <div class="bg-slate-50 border border-slate-100 rounded-2xl p-3 text-xs text-center text-slate-500 italic">
                    "Guest wishes are linked directly to invitation tokens."
                </div>
            </div>

        </div>

        <!-- Per-Ceremony Attendance Summary -->
        <?php if (!empty($per_ceremony_stats)): ?>
            <div class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm space-y-4">
                <div class="flex items-center justify-between border-b border-slate-100 pb-3">
                    <h3 class="font-black text-slate-800 text-sm flex items-center gap-2">
                        <i class="fa-solid fa-clipboard-user text-[#D4A28C]"></i> Ceremony Attendance Breakdown
                    </h3>
                    <a href="<?= url('/app/couple/guests') ?>" class="text-xs font-extrabold text-[#D4A28C] hover:underline">
                        View Guest List <i class="fa-solid fa-arrow-right"></i>
                    </a>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                    <?php foreach ($per_ceremony_stats as $cStat): ?>
                        <div class="p-4 rounded-2xl bg-slate-50 border border-slate-100 space-y-3">
                            <div class="flex items-center justify-between">
                                <h4 class="font-extrabold text-xs text-slate-800 flex items-center gap-1.5">
                                    <span>📍</span> <?= escape_html($cStat['event_name']) ?>
                                </h4>
                                <?php if (!empty($cStat['is_primary'])): ?>
                                    <span class="text-[9px] font-bold text-amber-800 bg-amber-100 px-2 py-0.5 rounded-full border border-amber-200">Primary</span>
                                <?php endif; ?>
                            </div>

                            <div class="grid grid-cols-3 gap-2 text-center">
                                <div class="bg-white p-2 rounded-xl border border-slate-100 shadow-2xs">
                                    <span class="text-[8px] font-bold text-slate-400 block uppercase">Invited</span>
                                    <span class="text-sm font-black text-slate-800 block mt-0.5"><?= (int)$cStat['invited'] ?></span>
                                </div>
                                <div class="bg-emerald-50 p-2 rounded-xl border border-emerald-100 shadow-2xs">
                                    <span class="text-[8px] font-bold text-emerald-700 block uppercase">Arrived</span>
                                    <span class="text-sm font-black text-emerald-600 block mt-0.5"><?= (int)$cStat['arrived'] ?></span>
                                </div>
                                <div class="bg-slate-100 p-2 rounded-xl border border-slate-200 shadow-2xs">
                                    <span class="text-[8px] font-bold text-slate-500 block uppercase">Remaining</span>
                                    <span class="text-sm font-black text-slate-600 block mt-0.5"><?= (int)$cStat['remaining'] ?></span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- Row 2: Recent Activities Feed & Guest Progress Table -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

            <!-- RECENT ACTIVITIES FEED (1 Column) -->
            <div class="lg:col-span-1 bg-white p-6 rounded-3xl border border-slate-100 shadow-sm space-y-4">
                <h3 class="font-black text-slate-800 text-sm border-b border-slate-50 pb-3 flex items-center justify-between">
                    <span><i class="fa-solid fa-list-timeline text-[#D4A28C] mr-1.5"></i> Recent Activities</span>
                    <span class="text-[10px] text-slate-400 font-normal">Real-time</span>
                </h3>

                <?php if (empty($activities)): ?>
                    <div class="text-center py-8 text-slate-400 text-xs">
                        No recent guest activities logged.
                    </div>
                <?php else: ?>
                    <div class="space-y-3.5 max-h-[420px] overflow-y-auto pr-1">
                        <?php foreach ($activities as $act): ?>
                            <div class="flex items-start gap-3 text-xs leading-relaxed border-b border-slate-50 pb-2.5 last:border-0">
                                <span class="w-7 h-7 rounded-full bg-slate-50 border border-slate-100 flex items-center justify-center text-xs flex-shrink-0 mt-0.5 shadow-sm">
                                    <i class="<?= $act['icon'] ?>"></i>
                                </span>
                                <div>
                                    <span class="font-semibold text-slate-700 block"><?= $act['text'] ?></span>
                                    <span class="text-[9px] text-slate-400 block mt-0.5"><?= date('d M Y, H:i', strtotime((string)($act['date'] ?? 'now'))) ?></span>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- GUEST PROGRESS TABLE (2 Columns) -->
            <div class="lg:col-span-2 bg-white p-6 rounded-3xl border border-slate-100 shadow-sm space-y-4">
                <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-50 pb-3">
                    <h3 class="font-black text-slate-800 text-sm flex items-center gap-2">
                        <i class="fa-solid fa-user-check text-[#D4A28C]"></i> Guest Progress Command Table
                    </h3>
                    <div class="text-xs text-slate-400 font-semibold">
                        Matching Guests: <strong class="text-slate-700"><?= (int)($progress_total ?? 0) ?></strong>
                    </div>
                </div>

                <!-- Search & Quick Filters -->
                <div class="space-y-3">
                    <div class="flex flex-col sm:flex-row gap-2">
                        <div class="flex-1">
                            <input 
                                type="text" 
                                x-model.debounce.300ms="search" 
                                @input="updateProgress()" 
                                placeholder="Search by guest name or phone number..." 
                                class="form-input w-full text-xs"
                            >
                        </div>
                        <button 
                            type="button" 
                            @click="search = ''; filter = 'all'; updateProgress()" 
                            class="px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-xl text-xs font-bold transition"
                        >
                            Reset
                        </button>
                    </div>

                    <!-- Filter Tabs Buttons -->
                    <div class="flex flex-wrap gap-1.5">
                        <?php 
                            $currFilter = $progress_filters['filter'] ?? 'all';
                            $filterOptions = [
                                'all'          => 'All Guests',
                                'opened'       => '✓ Opened',
                                'not_opened'   => '✕ Not Opened',
                                'attending'    => 'Attending',
                                'declined'     => 'Declined',
                                'rsvp_pending' => 'Pending RSVP',
                                'has_wish'     => 'Has Wish'
                            ];
                            foreach ($filterOptions as $key => $lbl):
                        ?>
                            <button 
                                type="button" 
                                @click="filter = '<?= $key ?>'; updateProgress()" 
                                class="px-2.5 py-1 rounded-lg text-[10px] font-bold transition-all <?= $currFilter === $key ? 'bg-slate-800 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200' ?>"
                            >
                                <?= $lbl ?>
                            </button>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Progress Table Content -->
                <div id="progress-table-wrapper" class="relative">
                    <div x-show="progressLoading" class="py-8 text-center text-slate-400 text-xs" style="display: none;">
                        Loading progress data...
                    </div>

                    <div x-show="!progressLoading" class="overflow-x-auto border border-slate-100 rounded-2xl">
                        <table class="w-full text-left text-xs">
                            <thead>
                                <tr class="bg-slate-50 border-b border-slate-100 font-bold text-slate-600 uppercase tracking-wider text-[10px]">
                                    <th class="px-4 py-3">Guest Name</th>
                                    <th class="px-4 py-3 text-center">Opened</th>
                                    <th class="px-4 py-3 text-center">RSVP</th>
                                    <th class="px-4 py-3 text-center">Wish</th>
                                    <th class="px-4 py-3 text-center">First Opened</th>
                                    <th class="px-4 py-3 text-center">Last Opened</th>
                                    <th class="px-4 py-3 text-center">Views</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 text-slate-700">
                                <?php if (empty($guest_progress)): ?>
                                    <tr>
                                        <td colspan="7" class="px-4 py-8 text-center text-slate-400 italic">
                                            No guests found matching the selected filter criteria.
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($guest_progress as $gp): 
                                        $isOpened = !empty($gp['first_opened_at']) || (int)$gp['view_count'] > 0 || $gp['invitation_status'] === 'opened';
                                    ?>
                                        <tr class="hover:bg-slate-50/60 transition-colors">
                                            <td class="px-4 py-3 font-semibold text-slate-800">
                                                <?php if (!empty($gp['honorific'])): ?>
                                                    <span class="text-slate-400 font-normal text-[10px] block"><?= escape_html($gp['honorific']) ?></span>
                                                <?php endif; ?>
                                                <?= escape_html($gp['full_name']) ?>
                                            </td>
                                            <td class="px-4 py-3 text-center">
                                                <?php if ($isOpened): ?>
                                                    <span class="inline-block bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded-full text-[10px] font-bold">✓ Opened</span>
                                                <?php else: ?>
                                                    <span class="inline-block bg-slate-100 text-slate-400 px-2 py-0.5 rounded-full text-[10px] font-semibold">Not Opened</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="px-4 py-3 text-center">
                                                <?php if ($gp['rsvp_status'] === 'attending'): ?>
                                                    <span class="inline-block bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded-full text-[10px] font-bold">
                                                        Attending (<?= (int)($gp['confirmed_pax'] ?? $gp['invited_pax']) ?>)
                                                    </span>
                                                <?php elseif ($gp['rsvp_status'] === 'declined'): ?>
                                                    <span class="inline-block bg-rose-100 text-rose-800 px-2 py-0.5 rounded-full text-[10px] font-bold">Declined</span>
                                                <?php else: ?>
                                                    <span class="inline-block bg-amber-100 text-amber-800 px-2 py-0.5 rounded-full text-[10px] font-bold">Pending</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="px-4 py-3 text-center">
                                                <?php if (!empty($gp['wish_message'])): ?>
                                                    <?php if ($gp['wish_status'] === 'approved' || (empty($gp['wish_status']) && $gp['wish_is_visible'])): ?>
                                                        <span class="inline-block bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded-full text-[10px] font-bold" title="<?= escape_html($gp['wish_message']) ?>">✓ Wish</span>
                                                    <?php elseif ($gp['wish_status'] === 'pending'): ?>
                                                        <span class="inline-block bg-amber-100 text-amber-800 px-2 py-0.5 rounded-full text-[10px] font-bold" title="<?= escape_html($gp['wish_message']) ?>">⏳ Pending</span>
                                                    <?php else: ?>
                                                        <span class="inline-block bg-rose-100 text-rose-800 px-2 py-0.5 rounded-full text-[10px] font-bold">✕ Rejected</span>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <span class="text-slate-300 font-mono">—</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="px-4 py-3 text-center font-mono text-[10px] text-slate-500">
                                                <?= !empty($gp['first_opened_at']) ? date('d M H:i', strtotime($gp['first_opened_at'])) : '—' ?>
                                            </td>
                                            <td class="px-4 py-3 text-center font-mono text-[10px] text-slate-500">
                                                <?= !empty($gp['last_opened_at']) ? date('d M H:i', strtotime($gp['last_opened_at'])) : '—' ?>
                                            </td>
                                            <td class="px-4 py-3 text-center font-bold font-mono">
                                                <?= (int)$gp['view_count'] ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Progress Pagination -->
                    <?php if (($progress_pages ?? 1) > 1): ?>
                        <div class="flex justify-between items-center pt-3 text-xs text-slate-500">
                            <span>Page <?= (int)$progress_page ?> of <?= (int)$progress_pages ?></span>
                            <div class="flex gap-1.5">
                                <a 
                                    href="<?= $progress_page > 1 ? url('/app/couple/dashboard?page=' . ($progress_page - 1) . '&filter=' . urlencode($currFilter) . '&search=' . urlencode($progress_filters['search'])) : '#' ?>" 
                                    @click.prevent="navigateProgress($event.target.closest('a').href)"
                                    class="px-3 py-1 bg-slate-100 rounded-lg font-bold text-slate-700 hover:bg-slate-200 <?= $progress_page <= 1 ? 'opacity-50 pointer-events-none' : '' ?>"
                                >
                                    Previous
                                </a>
                                <a 
                                    href="<?= $progress_page < $progress_pages ? url('/app/couple/dashboard?page=' . ($progress_page + 1) . '&filter=' . urlencode($currFilter) . '&search=' . urlencode($progress_filters['search'])) : '#' ?>" 
                                    @click.prevent="navigateProgress($event.target.closest('a').href)"
                                    class="px-3 py-1 bg-slate-100 rounded-lg font-bold text-slate-700 hover:bg-slate-200 <?= $progress_page >= $progress_pages ? 'opacity-50 pointer-events-none' : '' ?>"
                                >
                                    Next
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

        </div>

    </div>

    </div>

    <!-- ── SECTION 9: QUICK ACCESS ──────────────────────────────────────── -->
    <div class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm">
        <h3 class="font-black text-slate-800 text-sm flex items-center gap-2 mb-3">
            <i class="fa-solid fa-bolt text-[#D4A28C]"></i> Quick Access
        </h3>
        <div class="grid grid-cols-2 sm:grid-cols-6 gap-3 text-xs">
            <a href="<?= url('/app/couple/invitation/edit') ?>" class="p-3.5 rounded-2xl bg-slate-50 hover:bg-slate-100 border border-slate-100 hover:border-[#D4A28C] transition-all font-bold text-slate-700 flex flex-col items-center justify-center text-center gap-2">
                <i class="fa-solid fa-envelope text-rose-500 text-lg"></i>
                <span>Invitation</span>
            </a>
            <a href="<?= url('/app/couple/guests') ?>" class="p-3.5 rounded-2xl bg-slate-50 hover:bg-slate-100 border border-slate-100 hover:border-[#D4A28C] transition-all font-bold text-slate-700 flex flex-col items-center justify-center text-center gap-2">
                <i class="fa-solid fa-users text-purple-500 text-lg"></i>
                <span>Guests</span>
            </a>
            <a href="<?= url('/app/couple/budget') ?>" class="p-3.5 rounded-2xl bg-slate-50 hover:bg-slate-100 border border-slate-100 hover:border-[#D4A28C] transition-all font-bold text-slate-700 flex flex-col items-center justify-center text-center gap-2">
                <i class="fa-solid fa-wallet text-amber-500 text-lg"></i>
                <span>Budget</span>
            </a>
            <a href="<?= url('/app/couple/timeline') ?>" class="p-3.5 rounded-2xl bg-slate-50 hover:bg-slate-100 border border-slate-100 hover:border-[#D4A28C] transition-all font-bold text-slate-700 flex flex-col items-center justify-center text-center gap-2">
                <i class="fa-solid fa-clock-rotate-left text-[#D4A28C] text-lg"></i>
                <span>Timeline</span>
            </a>
            <a href="<?= url('/app/couple/checkin') ?>" class="p-3.5 rounded-2xl bg-slate-50 hover:bg-slate-100 border border-slate-100 hover:border-[#D4A28C] transition-all font-bold text-slate-700 flex flex-col items-center justify-center text-center gap-2">
                <i class="fa-solid fa-calendar-check text-emerald-500 text-lg"></i>
                <span>Wedding Day</span>
            </a>
            <a href="<?= url('/app/couple/users') ?>" class="p-3.5 rounded-2xl bg-slate-50 hover:bg-slate-100 border border-slate-100 hover:border-[#D4A28C] transition-all font-bold text-slate-700 flex flex-col items-center justify-center text-center gap-2">
                <i class="fa-solid fa-gear text-slate-500 text-lg"></i>
                <span>Settings</span>
            </a>
        </div>
    </div>

</div>
