<?php

/**
 * RSVP Center View
 *
 * Displays RSVP statistics cards and a paginated list of guests' RSVP statuses,
 * incorporating search and group filtration.
 *
 * Variables:
 *   $title         — string — Page title.
 *   $guests        — array — Paginated list of guest records.
 *   $groups        — array — Distinct guest categories.
 *   $search        — string — Active search query.
 *   $rsvp          — string — Active RSVP filter state.
 *   $group         — string — Active group filter state.
 *   $page          — int — Current page index.
 *   $totalPages    — int — Total available pages.
 *   $totalFiltered — int — Total guests matching active filters.
 *   $stats         — array — Expected, Confirmed, Declined, Pending metrics.
 *
 * @package Inveetaire
 * @ref     RC-014
 */

?>

<div class="max-w-6xl mx-auto space-y-6" 
     x-data="{ 
        rsvpLoading: false,
        search: '<?= escape_html($search ?? '') ?>',
        rsvp: '<?= escape_html($rsvp ?? '') ?>',
        group: '<?= escape_html($group ?? '') ?>',
        navigate(targetUrl) {
            this.rsvpLoading = 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('rsvp-center-wrapper');
                    if (wrapper) {
                        document.getElementById('rsvp-center-wrapper').innerHTML = wrapper.innerHTML;
                    }
                    window.history.pushState({}, '', targetUrl);
                    this.rsvpLoading = false;
                })
                .catch(err => {
                    console.error(err);
                    this.rsvpLoading = false;
                });
        },
        updateFromInputs() {
            let url = new URL(window.location.href);
            url.searchParams.set('search', this.search);
            url.searchParams.set('rsvp', this.rsvp);
            url.searchParams.set('group', this.group);
            url.searchParams.set('page', '1');
            this.navigate(url.toString());
        }
     }">

    <div id="rsvp-center-wrapper" class="space-y-6">
    <!-- Header Summary Section -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
            <div class="page-breadcrumb">
                <a href="<?= url('/app/couple/dashboard') ?>">Dashboard</a>
                <span class="sep">/</span>
                <span>RSVP Center</span>
            </div>
            <h1 class="page-h1">
                <span class="page-header-icon">
                    <i class="fa-solid fa-clipboard-check"></i>
                </span>
                <?= escape_html($title) ?>
            </h1>
            <p class="page-subtitle">Monitor live guest responses, manage confirmed seats, and track invitation follow-ups.</p>
        </div>
    </div>

    <!-- RSVP KPI Cards Section (White, Lavender, Periwinkle Design System) -->
    <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <!-- Card 1: Expected Guests -->
        <div class="bg-white border border-slate-100 rounded-2xl p-5 shadow-sm hover:shadow-md transition duration-200">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-slate-50 flex items-center justify-center text-lg text-slate-500"><i class="fa-solid fa-users"></i></div>
                <div>
                    <div class="text-xs font-semibold text-slate-400 uppercase tracking-wider">Expected Guests</div>
                    <div class="text-xl font-bold text-slate-800 mt-0.5"><?= (int) $stats['expected'] ?></div>
                </div>
            </div>
        </div>

        <!-- Card 2: Confirmed -->
        <div class="bg-white border border-slate-100 rounded-2xl p-5 shadow-sm hover:shadow-md transition duration-200" style="border-left: 4px solid #3b82f6;">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center text-lg"><i class="fa-solid fa-circle-check"></i></div>
                <div>
                    <div class="text-xs font-semibold text-slate-400 uppercase tracking-wider">Confirmed</div>
                    <div class="text-xl font-bold text-blue-700 mt-0.5"><?= (int) $stats['confirmed'] ?></div>
                </div>
            </div>
        </div>

        <!-- Card 3: Declined -->
        <div class="bg-white border border-slate-100 rounded-2xl p-5 shadow-sm hover:shadow-md transition duration-200" style="border-left: 4px solid #f43f5e;">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-rose-50 text-rose-600 flex items-center justify-center text-lg"><i class="fa-solid fa-ban"></i></div>
                <div>
                    <div class="text-xs font-semibold text-slate-400 uppercase tracking-wider">Declined</div>
                    <div class="text-xl font-bold text-rose-600 mt-0.5"><?= (int) $stats['declined'] ?></div>
                </div>
            </div>
        </div>

        <!-- Card 4: Pending -->
        <div class="bg-white border border-slate-100 rounded-2xl p-5 shadow-sm hover:shadow-md transition duration-200" style="border-left: 4px solid #d97706;">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center text-lg"><i class="fa-solid fa-hourglass-half"></i></div>
                <div>
                    <div class="text-xs font-semibold text-slate-400 uppercase tracking-wider">Pending</div>
                    <div class="text-xl font-bold text-amber-700 mt-0.5"><?= (int) $stats['pending'] ?></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Search & Filter Controls -->
    <div class="bg-white border border-slate-100 rounded-2xl p-5 shadow-sm">
        <form method="GET" action="<?= url('/app/couple/engagement/rsvp') ?>" @submit.prevent="updateFromInputs()" class="flex flex-col md:flex-row gap-3">
            <div class="flex-1">
                <input 
                    type="text" 
                    name="search" 
                    x-model.debounce.300ms="search"
                    @input="updateFromInputs()"
                    value="<?= escape_html($search) ?>" 
                    placeholder="Search by guest name or phone number..." 
                    class="form-input w-full"
                >
            </div>
            <div class="w-full md:w-48">
                <select name="rsvp" x-model="rsvp" @change="updateFromInputs()" class="form-input w-full">
                    <option value="">All RSVPs</option>
                    <option value="attending" <?= $rsvp === 'attending' ? 'selected' : '' ?>>Confirmed (Attending)</option>
                    <option value="declined" <?= $rsvp === 'declined' ? 'selected' : '' ?>>Declined</option>
                    <option value="pending" <?= $rsvp === 'pending' ? 'selected' : '' ?>>Pending</option>
                </select>
            </div>
            <div class="w-full md:w-48">
                <select name="group" x-model="group" @change="updateFromInputs()" class="form-input w-full">
                    <option value="">All Categories</option>
                    <?php foreach ($groups as $g): ?>
                        <option value="<?= escape_html($g) ?>" <?= $group === $g ? 'selected' : '' ?>>
                            <?= escape_html(ucfirst($g)) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
                <button type="submit" class="btn btn-primary px-5 py-2.5 flex items-center gap-1.5">
                    <i class="fa-solid fa-magnifying-glass"></i> Filter
                </button>
                <a href="<?= url('/app/couple/engagement/rsvp') ?>" @click.prevent="search = ''; rsvp = ''; group = ''; updateFromInputs()" class="btn btn-secondary px-5 py-2.5">Reset</a>
            </div>
        </form>
    </div>

    <!-- RSVP Responsive List Table (RC-015) -->
    <!-- Loading skeletons visual overlay -->
    <div class="card p-5 space-y-4" x-show="rsvpLoading" style="display: none;">
        <div class="flex justify-between items-center pb-2">
            <h4 class="text-xs font-black text-slate-400 uppercase tracking-wide">Updating RSVP data...</h4>
        </div>
        <div class="space-y-3">
            <div class="skeleton-pulse skeleton-table-row"></div>
            <div class="skeleton-pulse skeleton-table-row"></div>
            <div class="skeleton-pulse skeleton-table-row"></div>
            <div class="skeleton-pulse skeleton-table-row"></div>
            <div class="skeleton-pulse skeleton-table-row"></div>
        </div>
    </div>

    <div class="bg-white border border-slate-100 rounded-2xl shadow-sm overflow-hidden" x-show="!rsvpLoading">
        <?php if (empty($guests)): ?>
            <div class="empty-state-elegant">
                <div class="empty-state-icon">📬</div>
                <h3 class="empty-state-title">No RSVP responses found</h3>
                <p class="empty-state-text">Adjust your filters or share your pre-filled WhatsApp templates to prompt guest RSVPs.</p>
                <a href="<?= url('/app/couple/engagement/whatsapp-queue') ?>" class="btn btn-primary text-xs font-semibold px-4 py-2.5">
                    💬 View Message Queue
                </a>
            </div>
        <?php else: ?>
            <div class="overflow-x-auto">
                <table class="table-elegant w-full text-slate-700">
                    <thead>
                        <tr class="bg-slate-50/70 border-b border-slate-100">
                            <th class="py-4 px-6 text-left text-xs font-bold text-slate-500 uppercase tracking-wider">Guest Name</th>
                            <th class="py-4 px-6 text-left text-xs font-bold text-slate-500 uppercase tracking-wider">Category</th>
                            <th class="py-4 px-6 text-center text-xs font-bold text-slate-500 uppercase tracking-wider">Seats</th>
                            <th class="py-4 px-6 text-left text-xs font-bold text-slate-500 uppercase tracking-wider">RSVP Status</th>
                            <th class="py-4 px-6 text-left text-xs font-bold text-slate-500 uppercase tracking-wider">Response Details / Message</th>
                            <th class="py-4 px-6 text-right text-xs font-bold text-slate-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 text-sm">
                        <?php foreach ($guests as $g): 
                            $badgeClass = 'badge-neutral';
                            $statusLabel = 'Pending';
                            if ($g['rsvp_status'] === 'attending') {
                                $badgeClass = 'bg-blue-100 text-blue-700';
                                $statusLabel = 'Confirmed';
                            } elseif ($g['rsvp_status'] === 'declined') {
                                $badgeClass = 'bg-rose-100 text-rose-700';
                                $statusLabel = 'Declined';
                            }
                        ?>
                            <tr class="hover:bg-slate-50/50 transition duration-150">
                                <td class="py-4 px-6">
                                    <div class="font-bold text-slate-800"><?= escape_html($g['full_name']) ?></div>
                                    <div class="text-xs text-slate-400 mt-0.5 font-mono"><?= escape_html($g['phone_number'] ?? '-') ?></div>
                                </td>
                                <td class="py-4 px-6">
                                    <span class="badge badge-neutral text-xs">
                                        <?= escape_html(ucfirst($g['guest_group'] ?? 'others')) ?>
                                    </span>
                                </td>
                                <td class="py-4 px-6 text-center font-bold">
                                    <?= (int) $g['invited_pax'] ?> pax
                                </td>
                                <td class="py-4 px-6">
                                    <span class="badge <?= $badgeClass ?> font-semibold px-2.5 py-1 text-xs rounded-full">
                                        <?= $statusLabel ?>
                                    </span>
                                </td>
                                <td class="py-4 px-6 text-xs text-slate-500 max-w-xs truncate" title="<?= escape_html($g['notes'] ?? '') ?>">
                                    <?= !empty($g['notes']) ? escape_html($g['notes']) : '<span class="text-slate-350 italic">No notes provided</span>' ?>
                                </td>
                                <td class="py-4 px-6 text-right space-x-1.5 whitespace-nowrap">
                                    <a href="<?= url('/app/couple/guests?search=' . urlencode($g['full_name'])) ?>" class="btn btn-secondary btn-xs py-1.5 px-3 flex items-center justify-end gap-1 inline-flex">
                                        <i class="fa-solid fa-pen"></i> Edit Guest
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Table Pagination Footer -->
            <?php if ($totalPages > 1): ?>
                <div class="p-6 border-t border-slate-100 flex items-center justify-between">
                    <div class="text-xs text-slate-500">
                        Showing page <?= $page ?> of <?= $totalPages ?> (<?= $totalFiltered ?> matching guests)
                    </div>
                    <div class="flex gap-1.5">
                        <a 
                            href="<?= $page > 1 ? url('/app/couple/engagement/rsvp?page=' . ($page - 1) . '&search=' . urlencode($search) . '&rsvp=' . $rsvp . '&group=' . $group) : '#' ?>" 
                            @click.prevent="navigate($event.target.closest('a').href)"
                            class="btn btn-secondary btn-xs py-1.5 px-3 <?= $page <= 1 ? 'opacity-50 pointer-events-none' : '' ?>"
                        >
                            ◀ Prev
                        </a>
                        <a 
                            href="<?= $page < $totalPages ? url('/app/couple/engagement/rsvp?page=' . ($page + 1) . '&search=' . urlencode($search) . '&rsvp=' . $rsvp . '&group=' . $group) : '#' ?>" 
                            @click.prevent="navigate($event.target.closest('a').href)"
                            class="btn btn-secondary btn-xs py-1.5 px-3 <?= $page >= $totalPages ? 'opacity-50 pointer-events-none' : '' ?>"
                        >
                            Next ▶
                        </a>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
    </div>
</div>
