<?php
/**
 * Admin — Chat Conversation Detail
 *
 * Shows a full chat conversation with the visitor and allows admin to reply.
 */
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$conv = $conversation;
?>

<div class="admin-section">
    <!-- Back Button & Info -->
    <div style="display:flex; align-items:center; gap:16px; margin-bottom:20px; flex-wrap:wrap;">
        <a href="<?= $bp ?>/admin/chat" class="admin-btn admin-btn-secondary" style="text-decoration:none; padding:8px 16px; border-radius:8px; display:inline-flex; align-items:center; gap:6px; font-size:13px;">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
            Back to Chats
        </a>
        <div style="flex:1;">
            <div style="font-size:18px; font-weight:600;">
                <?= htmlspecialchars($conv['visitor_name'] ?? 'Anonymous Visitor', ENT_QUOTES, 'UTF-8') ?>
            </div>
            <div style="font-size:13px; color:#888; display:flex; gap:16px; flex-wrap:wrap; margin-top:2px;">
                <?php if ($conv['visitor_email']): ?>
                <span>&#9993; <?= htmlspecialchars($conv['visitor_email'], ENT_QUOTES, 'UTF-8') ?></span>
                <?php endif; ?>
                <?php if ($conv['visitor_phone']): ?>
                <span>&#9742; <?= htmlspecialchars($conv['visitor_phone'], ENT_QUOTES, 'UTF-8') ?></span>
                <?php endif; ?>
                <span>Started: <?= date('M j, Y g:i A', strtotime($conv['created_at'])) ?></span>
                <?php
                $statusColors = ['pending' => '#FFA502', 'active' => '#2ED573', 'closed' => '#999'];
                $statusColor = $statusColors[$conv['status']] ?? '#999';
                ?>
                <span style="display:inline-block; padding:2px 10px; border-radius:20px; font-size:11px; font-weight:600; color:#fff; background:<?= $statusColor ?>;">
                    <?= ucfirst($conv['status']) ?>
                </span>
            </div>
        </div>
        <?php if ($conv['status'] !== 'closed'): ?>
        <form method="POST" action="<?= $bp ?>/admin/chat/<?= (int) $conv['id'] ?>/close" style="display:inline;" onsubmit="return confirm('Close this conversation?');">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8') ?>">
            <button type="submit" class="admin-btn admin-btn-sm" style="background:#FFA502; color:#fff; padding:8px 16px; border-radius:8px; font-size:13px; border:none; cursor:pointer;">Close Chat</button>
        </form>
        <?php endif; ?>
    </div>

    <!-- Chat Messages Area -->
    <div class="admin-chat-container" style="display:flex; flex-direction:column; height:calc(100vh - 300px); min-height:400px; max-height:600px; border:1px solid #e0e0e0; border-radius:12px; overflow:hidden; background:#F7F8FC;">
        <!-- Messages -->
        <div class="admin-chat-messages" id="adminChatMessages" style="flex:1; overflow-y:auto; padding:20px; display:flex; flex-direction:column; gap:12px;">
            <?php foreach ($messages as $msg): ?>
            <div class="admin-chat-bubble admin-chat-bubble-<?= $msg['sender_type'] ?>">
                <div class="admin-chat-bubble-sender">
                    <?= $msg['sender_type'] === 'admin' ? '👤 Admin' : '💬 ' . htmlspecialchars($conv['visitor_name'] ?? 'Visitor', ENT_QUOTES, 'UTF-8') ?>
                </div>
                <div class="admin-chat-bubble-text"><?= nl2br(htmlspecialchars($msg['message'], ENT_QUOTES, 'UTF-8')) ?></div>
                <div class="admin-chat-bubble-time"><?= date('h:i A, M j', strtotime($msg['created_at'])) ?></div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- Reply Input (only if conversation is not closed) -->
        <?php if ($conv['status'] !== 'closed'): ?>
        <div style="padding:16px; background:#fff; border-top:1px solid #e0e0e0;">
            <form method="POST" action="<?= $bp ?>/admin/chat/<?= (int) $conv['id'] ?>/reply" id="adminReplyForm" style="display:flex; gap:10px; align-items:flex-end;">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8') ?>">
                <textarea name="message" id="adminReplyInput" placeholder="Type your reply..." rows="1"
                    style="flex:1; border:1px solid #ddd; border-radius:12px; padding:12px 16px; font-size:14px; font-family:'Inter',sans-serif; outline:none; resize:none; max-height:100px; line-height:1.4; transition:border-color 0.2s;"
                    onfocus="this.style.borderColor='#4A6CF7'" onblur="this.style.borderColor='#ddd'"
                    oninput="this.style.height='auto';this.style.height=Math.min(this.scrollHeight,100)+'px';"></textarea>
                <button type="submit" id="adminReplyBtn" style="width:44px; height:44px; border-radius:50%; background:linear-gradient(135deg,#4A6CF7,#6C3FE8); border:none; color:#fff; display:flex; align-items:center; justify-content:center; cursor:pointer; flex-shrink:0; transition:transform 0.2s;">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
                </button>
            </form>
        </div>
        <?php else: ?>
        <div style="padding:16px; background:#fff; border-top:1px solid #e0e0e0; text-align:center; color:#999; font-size:13px;">
            This conversation has been closed. <a href="<?= $bp ?>/admin/chat" style="color:#4A6CF7;">Go back to chats</a>
        </div>
        <?php endif; ?>
    </div>
</div>

<style>
    .admin-chat-bubble {
        max-width: 75%;
        padding: 12px 16px;
        border-radius: 16px;
        word-wrap: break-word;
        line-height: 1.5;
    }

    .admin-chat-bubble-visitor {
        align-self: flex-start;
        background: #fff;
        color: #333;
        border-bottom-left-radius: 4px;
        box-shadow: 0 1px 4px rgba(0,0,0,0.06);
    }

    .admin-chat-bubble-admin {
        align-self: flex-end;
        background: linear-gradient(135deg, #4A6CF7, #6C3FE8);
        color: #fff;
        border-bottom-right-radius: 4px;
    }

    .admin-chat-bubble-sender {
        font-size: 11px;
        font-weight: 600;
        margin-bottom: 4px;
        opacity: 0.7;
    }

    .admin-chat-bubble-text {
        font-size: 14px;
    }

    .admin-chat-bubble-time {
        font-size: 10px;
        opacity: 0.5;
        margin-top: 4px;
        text-align: right;
    }

    .admin-chat-messages::-webkit-scrollbar {
        width: 5px;
    }
    .admin-chat-messages::-webkit-scrollbar-thumb {
        background: #ccc;
        border-radius: 3px;
    }

    /* New message animation */
    @keyframes chatSlideIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .admin-chat-bubble {
        animation: chatSlideIn 0.3s ease;
    }
</style>

<script>
(function() {
    'use strict';

    const BASE = '<?= $bp ?>';
    const convId = <?= (int) $conv['id'] ?>;
    let lastId = <?= (int) $lastId ?>;
    const messagesEl = document.getElementById('adminChatMessages');

    // Scroll to bottom on load
    if (messagesEl) {
        messagesEl.scrollTop = messagesEl.scrollHeight;
    }

    // Enter key to submit
    const input = document.getElementById('adminReplyInput');
    if (input) {
        input.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                document.getElementById('adminReplyForm').submit();
            }
        });
    }

    // Poll for new messages every 5 seconds
    setInterval(async function() {
        try {
            const res = await fetch(`${BASE}/admin/chat/${convId}/poll?after_id=${lastId}`);
            const data = await res.json();

            if (data.success && data.messages && data.messages.length > 0) {
                data.messages.forEach(msg => {
                    const bubble = document.createElement('div');
                    bubble.className = `admin-chat-bubble admin-chat-bubble-${msg.sender_type}`;

                    const senderName = msg.sender_type === 'admin' ? '👤 Admin' : '💬 Visitor';

                    bubble.innerHTML = `
                        <div class="admin-chat-bubble-sender">${senderName}</div>
                        <div class="admin-chat-bubble-text">${msg.message.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')}</div>
                        <div class="admin-chat-bubble-time">${new Date(msg.created_at).toLocaleTimeString('en-IN', {hour:'2-digit', minute:'2-digit', hour12:true})}, ${new Date(msg.created_at).toLocaleDateString('en-IN', {month:'short', day:'numeric'})}</div>
                    `;

                    messagesEl.appendChild(bubble);
                });

                lastId = data.last_id;
                messagesEl.scrollTop = messagesEl.scrollHeight;
            }
        } catch (err) {
            // Silently ignore
        }
    }, 5000);

})();
</script>
