<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_admin();

// Send message handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'send_message') {
    ensure_csrf();
    $threadId = (int)($_POST['thread_id'] ?? 0);
    $message = trim($_POST['message'] ?? '');
    
    if ($threadId > 0 && !empty($message)) {
        try {
            // Get thread info to find user_id
            $threadInfo = $pdo->prepare("SELECT user_id, guest_id FROM chat_threads WHERE id=?");
            $threadInfo->execute([$threadId]);
            $thread = $threadInfo->fetch();
            
            if ($thread) {
                // Insert admin message
                $stmt = $pdo->prepare("
                    INSERT INTO chat_messages (thread_id, sender_id, guest_id, is_admin, body, status, created_at) 
                    VALUES (?, ?, ?, 1, ?, 'sent', ?)
                ");
                $stmt->execute([$threadId, $_SESSION['user']['id'], $thread['guest_id'], $message, date('c')]);
                
                // Update thread activity
                $pdo->prepare("UPDATE chat_threads SET last_message_at=?, last_active_at=? WHERE id=?")
                     ->execute([date('c'), date('c'), $threadId]);
                
                set_flash('success', 'Message sent');
            } else {
                set_flash('error', 'Thread not found');
            }
        } catch (Exception $e) {
            set_flash('error', 'Failed to send message: ' . $e->getMessage());
        }
    } else {
        set_flash('error', 'Message cannot be empty');
    }
    redirect('/admin/messages.php?thread=' . $threadId);
}

// Mark messages as read
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'mark_read') {
    ensure_csrf();
    $messageIds = $_POST['message_ids'] ?? [];
    if (!empty($messageIds)) {
        $placeholders = implode(',', array_fill(0, count($messageIds), '?'));
        $stmt = $pdo->prepare("UPDATE chat_messages SET status='read', read_at=? WHERE id IN ($placeholders)");
        $params = array_merge([date('c')], $messageIds);
        $stmt->execute($params);
        set_flash('success', 'Messages marked as read');
    }
    redirect('/admin/messages.php');
}

// Get chat threads with latest messages
$threads = $pdo->query("
    SELECT 
        ct.id as thread_id,
        ct.user_id,
        ct.guest_id,
        ct.status as thread_status,
        ct.created_at as thread_created,
        u.full_name as user_name,
        u.email as user_email,
        (SELECT COUNT(*) FROM chat_messages cm WHERE cm.thread_id=ct.id AND cm.status='sent' AND cm.is_admin=0) as unread_count,
        (SELECT body FROM chat_messages cm WHERE cm.thread_id=ct.id ORDER BY cm.created_at DESC LIMIT 1) as last_message,
        (SELECT created_at FROM chat_messages cm WHERE cm.thread_id=ct.id ORDER BY cm.created_at DESC LIMIT 1) as last_message_at
    FROM chat_threads ct
    LEFT JOIN users u ON ct.user_id=u.id
    ORDER BY last_message_at DESC
")->fetchAll();

// Get all messages for selected thread
$selectedThread = (int)($_GET['thread'] ?? 0);
$messages = [];
if ($selectedThread > 0) {
    $stmt = $pdo->prepare("
        SELECT cm.*, u.full_name as sender_name
        FROM chat_messages cm
        LEFT JOIN users u ON cm.sender_id=u.id
        WHERE cm.thread_id=?
        ORDER BY cm.created_at ASC
    ");
    $stmt->execute([$selectedThread]);
    $messages = $stmt->fetchAll();
    
    // Mark messages as read
    $pdo->prepare("UPDATE chat_messages SET status='read', read_at=? WHERE thread_id=? AND is_admin=0")->execute([date('c'), $selectedThread]);
}

include __DIR__ . '/../includes/header.php';
?>
<style>
.messages-layout { display: grid; grid-template-columns: 380px 1fr; gap: 20px; height: calc(100vh - 180px); min-height: 600px; }

/* Thread List */
.thread-list { background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; overflow: hidden; display: flex; flex-direction: column; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.thread-list-header { padding: 20px; border-bottom: 1px solid #e5e7eb; background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); }
.thread-list-header h2 { margin: 0; font-size: 20px; font-weight: 700; color: #1e293b; }
.thread-stats { display: flex; gap: 16px; margin-top: 8px; }
.stat-item { display: flex; align-items: center; gap: 6px; font-size: 13px; color: #64748b; }
.stat-value { font-weight: 600; color: #1e293b; }

.threads { overflow-y: auto; flex: 1; }
.thread-item { display: flex; align-items: center; gap: 12px; padding: 16px 20px; border-bottom: 1px solid #f1f5f9; cursor: pointer; transition: all 0.2s; text-decoration: none; color: inherit; position: relative; }
.thread-item:hover { background: #f8fafc; transform: translateX(2px); }
.thread-item.active { background: linear-gradient(135deg, #ecfdf5 0%, #f0fdf4 100%); border-left: 3px solid #10b981; }
.thread-item.unread::before { content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; background: #10b981; }

.thread-avatar { width: 48px; height: 48px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 18px; flex-shrink: 0; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.thread-avatar.user { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: #fff; }
.thread-avatar.guest { background: linear-gradient(135deg, #64748b 0%, #475569 100%); color: #fff; }

.thread-info { flex: 1; min-width: 0; }
.thread-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px; }
.thread-name { font-weight: 600; font-size: 15px; color: #1e293b; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.thread-time { font-size: 11px; color: #94a3b8; font-weight: 500; }
.thread-preview { font-size: 13px; color: #64748b; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; line-height: 1.4; }
.thread-meta { display: flex; align-items: center; gap: 8px; margin-top: 6px; }
.thread-status { font-size: 11px; padding: 2px 8px; border-radius: 99px; font-weight: 500; }
.status-open { background: #dcfce7; color: #166534; }
.status-closed { background: #f1f5f9; color: #475569; }
.unread-badge { background: #dc2626; color: #fff; font-size: 10px; font-weight: 700; padding: 2px 6px; border-radius: 99px; min-width: 18px; text-align: center; }

/* Chat Area */
.chat-area { background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; overflow: hidden; display: flex; flex-direction: column; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.chat-header { padding: 20px; border-bottom: 1px solid #e5e7eb; background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); display: flex; justify-content: space-between; align-items: center; }
.chat-header h3 { margin: 0; font-size: 18px; font-weight: 700; color: #1e293b; }
.chat-actions { display: flex; gap: 8px; }
.btn-icon { width: 36px; height: 36px; border-radius: 50%; border: 1px solid #e5e7eb; background: #fff; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s; }
.btn-icon:hover { background: #f8fafc; border-color: #10b981; }

.chat-messages { flex: 1; overflow-y: auto; padding: 24px; background: linear-gradient(180deg, #f8fafc 0%, #ffffff 100%); }
.message { display: flex; margin-bottom: 20px; animation: fadeIn 0.3s ease-in; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

.message.sent { justify-content: flex-end; }
.message.received { justify-content: flex-start; }
.message-bubble { max-width: 70%; padding: 14px 18px; border-radius: 18px; font-size: 14px; line-height: 1.5; position: relative; }
.message.sent .message-bubble { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: #fff; border-bottom-right-radius: 4px; box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2); }
.message.received .message-bubble { background: #fff; color: #1e293b; border-bottom-left-radius: 4px; border: 1px solid #e5e7eb; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); }
.message-meta { font-size: 11px; margin-top: 6px; opacity: 0.7; display: flex; align-items: center; gap: 4px; }
.message.sent .message-meta { justify-content: flex-end; }
.message.received .message-meta { justify-content: flex-start; }

/* Chat Input Area */
.chat-input-area { padding: 20px; border-top: 1px solid #e5e7eb; background: #fff; }
.chat-input-form { display: flex; gap: 12px; align-items: center; }
.chat-input { flex: 1; padding: 14px 18px; border: 1px solid #e5e7eb; border-radius: 24px; font-size: 14px; background: #f8fafc; transition: all 0.2s; }
.chat-input:focus { outline: none; border-color: #10b981; background: #fff; box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1); }

/* Empty States */
.empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: #64748b; text-align: center; padding: 60px 40px; }
.empty-state svg { margin-bottom: 20px; opacity: 0.3; }
.empty-state h3 { margin: 0 0 8px; font-size: 18px; font-weight: 600; color: #1e293b; }
.empty-state p { margin: 0; font-size: 14px; }

/* Mobile */
@media (max-width: 768px) {
    .messages-layout { grid-template-columns: 1fr; gap: 0; }
    .thread-list { display: <?= $selectedThread ? 'none' : 'flex' ?>; height: 100vh; border-radius: 0; }
    .chat-area { display: <?= $selectedThread ? 'flex' : 'none' ?>; height: 100vh; border-radius: 0; }
    .thread-list-header, .chat-header { padding: 16px; }
    .chat-messages { padding: 16px; }
    .message-bubble { max-width: 85%; }
}

/* Scrollbar Styling */
.threads::-webkit-scrollbar, .chat-messages::-webkit-scrollbar { width: 6px; }
.threads::-webkit-scrollbar-track, .chat-messages::-webkit-scrollbar-track { background: #f1f5f9; }
.threads::-webkit-scrollbar-thumb, .chat-messages::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 3px; }
.threads::-webkit-scrollbar-thumb:hover, .chat-messages::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
</style>

<div class="admin-header">
    <h2 class="admin-title">Chat Messages</h2>
    <a href="/admin/dashboard.php" class="btn"><?=ui_icon('dashboard', 16)?> Dashboard</a>
</div>

<div class="messages-layout">
    <!-- Thread List -->
    <div class="thread-list">
        <div class="thread-list-header">
            <h2>Conversations</h2>
            <div class="thread-stats">
                <div class="stat-item">
                    <span class="stat-value"><?=count($threads)?></span>
                    <span>Total</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value"><?=array_sum(array_column($threads, 'unread_count'))?></span>
                    <span>Unread</span>
                </div>
            </div>
        </div>
        <div class="threads">
            <?php if (empty($threads)): ?>
                <div class="empty-state">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
                    <p>No conversations yet</p>
                </div>
            <?php endif; ?>
            
            <?php foreach ($threads as $t): 
                $isActive = $selectedThread === (int)$t['thread_id'];
                $name = $t['user_name'] ?? 'Guest ' . substr($t['guest_id'] ?? 'Unknown', 0, 8);
                $initial = strtoupper(substr($name, 0, 1));
                $isGuest = empty($t['user_name']);
                $hasUnread = $t['unread_count'] > 0;
            ?>
                <a href="/admin/messages.php?thread=<?=e((string)$t['thread_id'])?>" class="thread-item <?= $isActive ? 'active' : '' ?> <?= $hasUnread ? 'unread' : '' ?>">
                    <div class="thread-avatar <?= $isGuest ? 'guest' : 'user' ?>"><?=e($initial)?></div>
                    <div class="thread-info">
                        <div class="thread-header">
                            <div class="thread-name"><?=e($name)?></div>
                            <div class="thread-time"><?= $t['last_message_at'] ? date('g:i A', strtotime($t['last_message_at'])) : '' ?></div>
                        </div>
                        <div class="thread-preview"><?=e($t['last_message'] ?? 'No messages')?></div>
                        <div class="thread-meta">
                            <span class="thread-status status-<?=e($t['thread_status'] ?? 'open') ?>"><?=ucfirst($t['thread_status'] ?? 'open')?></span>
                            <?php if ($hasUnread): ?>
                                <span class="unread-badge"><?=e((string)$t['unread_count'])?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Chat Area -->
    <div class="chat-area">
        <?php if ($selectedThread > 0 && !empty($messages)): 
            $currentThread = array_filter($threads, fn($t) => (int)$t['thread_id'] === $selectedThread);
            $currentThread = $currentThread ? array_values($currentThread)[0] : null;
            $threadName = $currentThread ? ($currentThread['user_name'] ?? 'Guest ' . substr($currentThread['guest_id'] ?? 'Unknown', 0, 8)) : 'Unknown';
        ?>
            <div class="chat-header">
                <h3><?=e($threadName)?></h3>
                <div class="chat-actions">
                    <button class="btn-icon" title="Mark all as read">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>
                    </button>
                    <button class="btn-icon" title="Archive conversation">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5" rx="1"/></svg>
                    </button>
                </div>
            </div>
            <div class="chat-messages">
                <?php foreach ($messages as $msg): 
                    $isAdmin = (bool)$msg['is_admin'];
                    $type = $isAdmin ? 'sent' : 'received';
                ?>
                    <div class="message <?=e($type)?>">
                        <div class="message-bubble">
                            <?= nl2br(e($msg['body'])) ?>
                            <div class="message-meta">
                                <?= date('g:i A', strtotime($msg['created_at'])) ?> 
                                <?php if ($msg['status'] === 'read'): ?>• Read<?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <!-- Chat Input Area -->
            <div class="chat-input-area">
                <form method="post" class="chat-input-form" id="admin-chat-form">
                    <?=csrf_field()?>
                    <input type="hidden" name="action" value="send_message">
                    <input type="hidden" name="thread_id" value="<?=e((string)$selectedThread)?>">
                    <input type="text" name="message" class="chat-input" placeholder="Type your message..." autocomplete="off" required>
                    <button type="submit" class="btn primary" style="border-radius: 50%; width: 48px; height: 48px; padding: 0; display: flex; align-items: center; justify-content: center;">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
                    </button>
                </form>
            </div>
        <?php else: ?>
            <div class="empty-state">
                <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
                <h3>Select a conversation</h3>
                <p>Choose a chat from the list to view messages</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
