<?php

/**
 * Guest Wishes Moderation View
 *
 * Displays a list of wishes received from guests with search filter,
 * sorting toggles, and pagination.
 *
 * Variables:
 *   $title         — string — Page title.
 *   $wishes        — array — List of guest wishes.
 *   $search        — string — Active search filter query.
 *   $sort          — string — Sort direction ('newest' | 'oldest').
 *   $page          — int — Current page index.
 *   $totalPages    — int — Total pages.
 *   $totalFiltered — int — Matching wishes count.
 *
 * @package Inveetaire
 * @ref     RC-014
 */

?>

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

    <div id="wishes-wrapper" class="space-y-6">
    <!-- Header -->
    <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>Guest Wishes</span>
            </div>
            <h1 class="page-h1">
                <span class="page-header-icon">
                    <i class="fa-solid fa-heart-pulse"></i>
                </span>
                <?= escape_html($title) ?>
            </h1>
            <p class="page-subtitle">Read, search, and moderate warm congratulations wishes from your guest list.</p>
        </div>
    </div>

    <!-- Search & Moderation Filter Bar -->
    <div class="bg-white border border-slate-100 rounded-2xl p-5 shadow-sm space-y-4">
        <!-- Moderation Status Tabs -->
        <?php 
            $statusCounts = $stats ?? ['all' => 0, 'pending' => 0, 'approved' => 0, 'rejected' => 0];
            $currentStatus = $status ?? 'all';
        ?>
        <div class="flex flex-wrap gap-2 border-b border-slate-100 pb-3">
            <a 
                href="<?= url('/app/couple/engagement/wishes?status=all&sort=' . $sort . '&search=' . urlencode($search)) ?>" 
                @click.prevent="status = 'all'; updateFromInputs()" 
                class="px-3 py-1.5 rounded-lg text-xs font-bold transition-colors <?= $currentStatus === 'all' ? 'bg-slate-800 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200' ?>"
            >
                All Wishes (<?= (int)$statusCounts['all'] ?>)
            </a>
            <a 
                href="<?= url('/app/couple/engagement/wishes?status=pending&sort=' . $sort . '&search=' . urlencode($search)) ?>" 
                @click.prevent="status = 'pending'; updateFromInputs()" 
                class="px-3 py-1.5 rounded-lg text-xs font-bold transition-colors flex items-center gap-1.5 <?= $currentStatus === 'pending' ? 'bg-amber-500 text-white' : 'bg-amber-50 text-amber-700 hover:bg-amber-100' ?>"
            >
                <span>⏳ Pending</span>
                <span class="bg-amber-200/60 text-amber-900 px-1.5 py-0.2 rounded-full text-[10px]"><?= (int)$statusCounts['pending'] ?></span>
            </a>
            <a 
                href="<?= url('/app/couple/engagement/wishes?status=approved&sort=' . $sort . '&search=' . urlencode($search)) ?>" 
                @click.prevent="status = 'approved'; updateFromInputs()" 
                class="px-3 py-1.5 rounded-lg text-xs font-bold transition-colors flex items-center gap-1.5 <?= $currentStatus === 'approved' ? 'bg-emerald-600 text-white' : 'bg-emerald-50 text-emerald-700 hover:bg-emerald-100' ?>"
            >
                <span>✓ Approved</span>
                <span class="bg-emerald-200/60 text-emerald-900 px-1.5 py-0.2 rounded-full text-[10px]"><?= (int)$statusCounts['approved'] ?></span>
            </a>
            <a 
                href="<?= url('/app/couple/engagement/wishes?status=rejected&sort=' . $sort . '&search=' . urlencode($search)) ?>" 
                @click.prevent="status = 'rejected'; updateFromInputs()" 
                class="px-3 py-1.5 rounded-lg text-xs font-bold transition-colors flex items-center gap-1.5 <?= $currentStatus === 'rejected' ? 'bg-rose-600 text-white' : 'bg-rose-50 text-rose-700 hover:bg-rose-100' ?>"
            >
                <span>✕ Rejected</span>
                <span class="bg-rose-200/60 text-rose-900 px-1.5 py-0.2 rounded-full text-[10px]"><?= (int)$statusCounts['rejected'] ?></span>
            </a>
        </div>

        <form method="GET" action="<?= url('/app/couple/engagement/wishes') ?>" @submit.prevent="updateFromInputs()" class="flex flex-col md:flex-row gap-3">
            <input type="hidden" name="status" x-model="status">
            <div class="flex-1">
                <input 
                    type="text" 
                    name="search" 
                    x-model.debounce.300ms="search"
                    @input="updateFromInputs()"
                    value="<?= escape_html($search) ?>" 
                    placeholder="Search wishes by guest name or message keywords..." 
                    class="form-input w-full"
                >
            </div>
            <div class="w-full md:w-48">
                <select name="sort" x-model="sort" @change="updateFromInputs()" class="form-input w-full">
                    <option value="newest" <?= $sort === 'newest' ? 'selected' : '' ?>>Newest First</option>
                    <option value="oldest" <?= $sort === 'oldest' ? 'selected' : '' ?>>Oldest First</option>
                </select>
            </div>
            <div class="flex gap-2">
                <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/wishes') ?>" @click.prevent="search = ''; sort = 'newest'; status = 'all'; updateFromInputs()" class="btn btn-secondary px-5 py-2.5">Reset</a>
            </div>
        </form>
    </div>

    <!-- Wishes Cards Grid (RC-015 / G011) -->
    <!-- Loading skeletons visual overlay -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4" x-show="wishesLoading" style="display: none;">
        <div class="skeleton-pulse skeleton-card bg-slate-50 border border-slate-100 rounded-2xl" style="height: 120px;"></div>
        <div class="skeleton-pulse skeleton-card bg-slate-50 border border-slate-100 rounded-2xl" style="height: 120px;"></div>
        <div class="skeleton-pulse skeleton-card bg-slate-50 border border-slate-100 rounded-2xl" style="height: 120px;"></div>
        <div class="skeleton-pulse skeleton-card bg-slate-50 border border-slate-100 rounded-2xl" style="height: 120px;"></div>
    </div>

    <div x-show="!wishesLoading" class="space-y-4">
        <?php if (empty($wishes)): ?>
            <div class="empty-state-elegant">
                <div class="empty-state-icon">💭</div>
                <h3 class="empty-state-title">No guest wishes found</h3>
                <p class="empty-state-text">Once guests submit wishes, their messages will be listed here for your moderation.</p>
                <a href="<?= url('/app/couple/engagement/rsvp') ?>" class="btn btn-primary text-xs font-semibold px-4 py-2.5">
                    📬 Check RSVPs
                </a>
            </div>
        <?php else: ?>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <?php foreach ($wishes as $w): 
                $initial = !empty($w['sender_name']) ? mb_strtoupper(mb_substr($w['sender_name'], 0, 1)) : 'G';
                $wStatus = $w['status'] ?? ($w['is_visible'] ? 'approved' : 'rejected');
            ?>
                <div class="bg-white border border-slate-100 rounded-2xl p-5 shadow-sm hover:shadow-md transition duration-200 flex flex-col justify-between space-y-4">
                    <div class="flex items-start gap-4">
                        <!-- Elegant initial avatar -->
                        <div class="w-12 h-12 rounded-full bg-amber-50 text-amber-700 flex items-center justify-center font-bold text-lg flex-shrink-0 border border-amber-200/50">
                            <?= escape_html($initial) ?>
                        </div>
                        <div class="flex-1 space-y-1.5 min-w-0">
                            <div class="flex justify-between items-start gap-2">
                                <h4 class="font-bold text-slate-800 truncate"><?= escape_html($w['sender_name']) ?></h4>
                                <?php if ($wStatus === 'approved'): ?>
                                    <span class="inline-block bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded-full text-[10px] font-bold">Approved</span>
                                <?php elseif ($wStatus === 'pending'): ?>
                                    <span class="inline-block bg-amber-100 text-amber-800 px-2 py-0.5 rounded-full text-[10px] font-bold">Pending Approval</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; ?>
                            </div>
                            <p class="text-xs text-slate-400 font-mono">
                                <?= date('d M Y, H:i', strtotime($w['submitted_at'])) ?>
                            </p>
                            <p class="text-sm text-slate-700 leading-relaxed italic bg-slate-50 p-3 rounded-xl border border-slate-100">
                                "<?= escape_html($w['message']) ?>"
                            </p>
                        </div>
                    </div>

                    <!-- Moderation Actions -->
                    <div class="flex items-center justify-end gap-2 pt-2 border-t border-slate-100">
                        <?php if ($wStatus !== 'approved'): ?>
                            <form action="<?= url('/app/couple/engagement/wishes/approve/' . $w['id']) ?>" method="POST" class="inline">
                                <?= csrf_field() ?>
                                <button type="submit" class="px-3 py-1 bg-emerald-600 hover:bg-emerald-700 text-white rounded text-xs font-bold transition">
                                    ✓ Approve
                                </button>
                            </form>
                        <?php endif; ?>

                        <?php if ($wStatus !== 'rejected'): ?>
                            <form action="<?= url('/app/couple/engagement/wishes/reject/' . $w['id']) ?>" method="POST" class="inline">
                                <?= csrf_field() ?>
                                <button type="submit" class="px-3 py-1 bg-amber-500 hover:bg-amber-600 text-white rounded text-xs font-bold transition">
                                    ✕ Reject
                                </button>
                            </form>
                        <?php endif; ?>

                        <form action="<?= url('/app/couple/engagement/wishes/delete/' . $w['id']) ?>" method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this wish?')">
                            <?= csrf_field() ?>
                            <button type="submit" class="px-3 py-1 bg-slate-100 hover:bg-rose-50 text-slate-500 hover:text-rose-600 rounded text-xs font-bold transition">
                                Delete
                            </button>
                        </form>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Pagination Section -->
        <?php if ($totalPages > 1): ?>
            <div class="bg-white border border-slate-100 rounded-2xl p-5 shadow-sm flex items-center justify-between">
                <div class="text-xs text-slate-500">
                    Showing page <?= $page ?> of <?= $totalPages ?> (<?= $totalFiltered ?> matching wishes)
                </div>
                <div class="flex gap-1.5">
                    <a 
                        href="<?= $page > 1 ? url('/app/couple/engagement/wishes?page=' . ($page - 1) . '&search=' . urlencode($search) . '&sort=' . $sort) : '#' ?>" 
                        @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/wishes?page=' . ($page + 1) . '&search=' . urlencode($search) . '&sort=' . $sort) : '#' ?>" 
                        @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>
