<?php

/**
 * Message Preview and Distribution View
 *
 * Displays the list of guests alongside actions to copy URL link,
 * copy personalized compiled message text, and open WhatsApp deep links.
 *
 * Variables expected:
 *   $title  — string — Page title.
 *   $guests — array — List of compiled guest objects.
 *
 * @package Inveetaire
 * @ref     PILOT-006
 */

/** @var string $title */
/** @var array $guests */

?>

<div class="space-y-6">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
            <h1 class="text-2xl font-bold text-slate-800 tracking-tight"><?= escape_html($title) ?></h1>
            <p class="text-sm text-slate-500 mt-1">Review guest invitations, copy links/messages, and trigger WhatsApp delivery.</p>
        </div>
        <div class="flex items-center gap-2">
            <a href="<?= url('/app/couple/messaging/template') ?>" class="btn btn-secondary btn-sm flex items-center gap-1.5">
                <i class="fa-solid fa-pen"></i> Edit Message Template
            </a>
        </div>
    </div>

    <!-- Guests Invitation Distribution Table -->
    <div class="card p-0 overflow-hidden">
        <div class="p-6 border-b border-slate-100 bg-slate-50/50 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">
            <h3 class="text-sm font-bold text-slate-800">Guest Invitation Status (<?= count($guests) ?> Total)</h3>
        </div>

        <?php if (empty($guests)): ?>
            <div class="p-12 text-center text-slate-400 text-sm">
                No guests found. Please <a href="<?= url('/app/couple/guests/import') ?>" class="link-elegant font-bold">import your guests</a> first to generate invitation messages.
            </div>
        <?php else: ?>
            <div class="overflow-x-auto">
                <table class="table-elegant text-xs">
                    <thead>
                        <tr>
                            <th class="py-4 px-6">Guest Name</th>
                            <th class="py-4 px-6">Category</th>
                            <th class="py-4 px-6">Phone Number</th>
                            <th class="py-4 px-6 text-center">Pax</th>
                            <th class="py-4 px-6 text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 text-slate-700">
                        <?php foreach ($guests as $g): ?>
                            <tr>
                                <td class="py-4 px-6">
                                    <div class="font-bold text-slate-850"><?= escape_html($g['full_name']) ?></div>
                                </td>
                                <td class="py-4 px-6">
                                    <span class="badge badge-neutral">
                                        <?= escape_html($g['guest_group'] ?? 'default') ?>
                                    </span>
                                </td>
                                <td class="py-4 px-6 font-mono text-slate-500">
                                    <?= escape_html($g['phone_number'] ?? '-') ?>
                                </td>
                                <td class="py-4 px-6 text-center font-semibold">
                                    <?= (int) $g['invited_pax'] ?>
                                </td>
                                <td class="py-4 px-6 text-right space-x-1.5 whitespace-nowrap">
                                    
                                    <button 
                                        type="button" 
                                        onclick='openPreviewModal("<?= escape_javascript($g['full_name']) ?>", <?= json_encode($g['message'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>, "<?= escape_javascript($g['whatsapp_url'] ?? '') ?>")'
                                        class="btn btn-secondary btn-sm"
                                        title="Preview personalized invitation message"
                                    >
                                        👁️ Preview
                                    </button>

                                    <!-- Action: Copy Message -->
                                    <button 
                                        type="button" 
                                        onclick='copyText(<?= json_encode($g['message'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'
                                        class="btn btn-secondary btn-sm"
                                        title="Copy message to clipboard"
                                    >
                                        📋 Copy Message
                                    </button>

                                    <!-- Action: Copy Link -->
                                    <button 
                                        type="button" 
                                        onclick='copyText("<?= escape_javascript($g['personal_url']) ?>")'
                                        class="btn btn-secondary btn-sm"
                                        title="Copy invitation link to clipboard"
                                    >
                                        🔗 Copy Link
                                    </button>

                                    <!-- Action: WhatsApp Direct Deep Link -->
                                    <?php if (!empty($g['whatsapp_url'])): ?>
                                        <a 
                                            href="<?= escape_html($g['whatsapp_url']) ?>" 
                                            target="_blank"
                                            class="btn btn-sm bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg px-3 inline-flex items-center"
                                            title="Open WhatsApp chat with invitation pre-filled"
                                        >
                                            💬 WhatsApp
                                        </a>
                                    <?php else: ?>
                                        <button 
                                            type="button"
                                            disabled
                                            class="btn btn-secondary btn-sm opacity-50 cursor-not-allowed"
                                            title="No phone number provided"
                                        >
                                            💬 WhatsApp
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Dynamic Preview Modal Popup -->
<div id="preview-modal" class="hidden fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
    <div class="card max-w-md w-full overflow-hidden shadow-2xl p-0">
        <div class="p-6 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
            <div>
                <h3 class="text-sm font-bold text-slate-800" id="modal-guest-name">Personalized Message</h3>
                <p class="text-[10px] text-slate-400 mt-0.5">Preview of the wording that will be sent</p>
            </div>
            <button type="button" onclick="closePreviewModal()" class="text-slate-400 hover:text-slate-650 text-sm font-bold">✕</button>
        </div>
        <div class="p-6 space-y-4">
            <textarea id="modal-message-body" readonly class="form-textarea w-full font-mono h-64"></textarea>
            
            <div class="flex gap-2 justify-end pt-2 border-t border-slate-100">
                <button type="button" onclick="closePreviewModal()" class="btn btn-secondary btn-sm">
                    Close
                </button>
                <button type="button" id="modal-copy-btn" class="btn btn-secondary btn-sm">
                    Copy Message
                </button>
                <a id="modal-wa-link" target="_blank" class="btn btn-sm bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg inline-flex items-center">
                    Send WhatsApp
                </a>
            </div>
        </div>
    </div>
</div>

<script>
    // Copy content Helper
    function copyText(text) {
        if (!navigator.clipboard) {
            // Fallback for local HTTP/dev testing
            const textarea = document.createElement('textarea');
            textarea.value = text;
            textarea.style.position = 'fixed'; // Avoid scrolling to bottom
            document.body.appendChild(textarea);
            textarea.select();
            try {
                document.execCommand('copy');
                alert('Copied to clipboard successfully!');
            } catch (err) {
                console.error('Fallback copy failed', err);
            }
            document.body.removeChild(textarea);
            return;
        }

        navigator.clipboard.writeText(text).then(() => {
            alert('Copied to clipboard successfully!');
        }).catch(err => {
            console.error('Clipboard write failed', err);
        });
    }

    // Modal Control Helpers
    function openPreviewModal(guestName, messageContent, waUrl) {
        document.getElementById('modal-guest-name').innerText = "Personalized Invitation: " + guestName;
        document.getElementById('modal-message-body').value = messageContent;
        
        // Wire copy action
        const copyBtn = document.getElementById('modal-copy-btn');
        copyBtn.onclick = function() {
            copyText(messageContent);
        };

        // Wire WhatsApp anchor href
        const waLink = document.getElementById('modal-wa-link');
        if (waUrl && waUrl !== '') {
            waLink.href = waUrl;
            waLink.classList.remove('hidden');
        } else {
            waLink.href = '#';
            waLink.classList.add('hidden');
        }

        // Show modal
        const modal = document.getElementById('preview-modal');
        modal.classList.remove('hidden');
    }

    function closePreviewModal() {
        const modal = document.getElementById('preview-modal');
        modal.classList.add('hidden');
    }

    // Close on click outside content card
    window.addEventListener('click', (e) => {
        const modal = document.getElementById('preview-modal');
        if (e.target === modal) {
            closePreviewModal();
        }
    });
</script>
