<?php
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Auth.php';

$db = Database::getInstance();
$auth = new Auth($db);

// Get all chats
$allChats = $db->fetchAll("
    SELECT 
        c.id,
        c.user_id,
        u.name AS username,
        c.status,
        c.created_at,
        COUNT(m.id) as message_count,
        MAX(m.created_at) as last_message_time
    FROM chatbot_chats c
    JOIN users u ON u.id = c.user_id
    LEFT JOIN chatbot_messages m ON m.chat_id = c.id
    GROUP BY c.id
    ORDER BY last_message_time DESC, c.created_at DESC
") ?: [];

// Get selected chat
$selectedChat = intval($_GET['chat'] ?? 0);
if (!$selectedChat && count($allChats) > 0) {
    $selectedChat = $allChats[0]['id'];
}

// Load messages for opened chat
$messages = [];
if ($selectedChat) {
    $messages = $db->fetchAll(
        "SELECT m.*, u.name as sender_name
         FROM chatbot_messages m
         LEFT JOIN users u ON u.id = m.sender_id
         WHERE m.chat_id = ?
         ORDER BY m.created_at ASC",
        [$selectedChat]
    ) ?: [];
}

// Handle sending message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    header('Content-Type: application/json');
    
    $message = trim($_POST['message'] ?? '');
    $chatId = intval($_POST['chat_id'] ?? 0);
    
    if (empty($message) || $chatId <= 0) {
        echo json_encode(['success' => false]);
        exit();
    }
    
    try {
        $adminId = 1;
        $db->insert('chatbot_messages', [
            'chat_id' => $chatId,
            'sender_id' => $adminId,
            'message' => $message,
            'created_at' => date('Y-m-d H:i:s')
        ]);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit();
}

// Handle fetching messages
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['get_messages'])) {
    header('Content-Type: application/json');
    
    $chatId = intval($_POST['chat_id'] ?? 0);
    
    if ($chatId <= 0) {
        echo json_encode([]);
        exit();
    }
    
    $messages = $db->fetchAll(
        "SELECT m.*, u.name as sender_name
         FROM chatbot_messages m
         LEFT JOIN users u ON u.id = m.sender_id
         WHERE m.chat_id = ?
         ORDER BY m.created_at ASC",
        [$chatId]
    ) ?: [];
    
    echo json_encode($messages);
    exit();
}

// Handle fetching chat list for auto-refresh
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['get_chats'])) {
    header('Content-Type: application/json');
    
    $allChats = $db->fetchAll("
        SELECT 
            c.id,
            c.user_id,
            u.name AS username,
            c.status,
            c.created_at,
            COUNT(m.id) as message_count,
            MAX(m.created_at) as last_message_time
        FROM chatbot_chats c
        JOIN users u ON u.id = c.user_id
        LEFT JOIN chatbot_messages m ON m.chat_id = c.id
        GROUP BY c.id
        ORDER BY last_message_time DESC, c.created_at DESC
    ") ?: [];
    
    echo json_encode($allChats);
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Chatbot</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        .chatbot-container { display: flex; height: calc(100vh - 100px); background: #f5f5f5; }
        .users-list { width: 300px; background: white; border-right: 1px solid #e5e5e5; overflow-y: auto; padding: 15px; }
        .user-search input { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; margin-bottom: 15px; }
        .user-item { padding: 10px; margin-bottom: 8px; background: #f8f9fa; border-radius: 8px; cursor: pointer; transition: all 0.2s; border-left: 3px solid transparent; }
        .user-item:hover { background: #e9ecef; }
        .user-item.active { background: #e3f2fd; border-left-color: #667eea; }
        .user-name { font-weight: 600; font-size: 14px; margin-bottom: 4px; }
        .user-preview { font-size: 12px; color: #666; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .chat-area { flex: 1; display: flex; flex-direction: column; background: white; }
        .chat-header { background: #667eea; color: white; padding: 15px 20px; font-weight: 600; }
        .chat-messages { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 12px; }
        .message { display: flex; margin-bottom: 12px; animation: slideIn 0.3s ease; }
        .message.admin { justify-content: flex-end; }
        .message-bubble { max-width: 60%; padding: 10px 14px; border-radius: 12px; word-wrap: break-word; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        .message.admin .message-bubble { background: #667eea; color: white; border-bottom-right-radius: 4px; }
        .message.user .message-bubble { background: #e9ecef; color: #000; border-bottom-left-radius: 4px; }
        .message-time { font-size: 11px; color: #999; margin-top: 4px; text-align: right; }
        .message.user .message-time { text-align: left; }
        .empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: #999; text-align: center; }
        .chat-footer { padding: 15px 20px; border-top: 1px solid #e5e5e5; background: white; display: flex; flex-direction: column; gap: 10px; }
        .templates { display: flex; gap: 6px; flex-wrap: wrap; }
        .template-btn { background: #f0f0f0; border: 1px solid #ddd; padding: 6px 10px; border-radius: 4px; font-size: 11px; cursor: pointer; transition: all 0.2s; }
        .template-btn:hover { background: #e0e0e0; }
        .ai-suggestions { display: none; padding: 10px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e9ecef; }
        .ai-suggestions.show { display: block; }
        .suggestions-label { font-size: 11px; color: #666; margin-bottom: 6px; font-weight: 600; }
        .suggestions-list { display: flex; flex-wrap: wrap; gap: 6px; }
        .suggestion-btn { background: #e3f2fd; color: #1976d2; border: 1px solid #90caf9; padding: 6px 10px; border-radius: 12px; font-size: 12px; cursor: pointer; }
        .suggestion-btn:hover { background: #bbdefb; }
        .input-area { display: flex; gap: 10px; }
        .input-area input { flex: 1; padding: 10px 14px; border: 1px solid #ddd; border-radius: 20px; font-size: 14px; outline: none; }
        .input-area input:focus { border-color: #667eea; }
        .input-area button { background: #667eea; color: white; border: none; border-radius: 50%; width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 18px; }
        .input-area button:hover { background: #5568d3; transform: scale(1.05); }
        .no-chats { text-align: center; padding: 30px; color: #999; }
        @keyframes slideIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
    </style>
</head>
<body>
    <div class="chatbot-container">
        <div class="users-list">
            <?php if (empty($allChats)): ?>
                <div class="no-chats">No chats yet</div>
            <?php else: ?>
                <div class="user-search">
                    <input type="text" id="searchUsers" placeholder="Search users...">
                </div>
                <div id="usersList">
                    <?php foreach ($allChats as $chat): ?>
                        <div class="user-item <?= ($chat['id'] == $selectedChat) ? 'active' : '' ?>" onclick="selectChat(<?= $chat['id'] ?>)">
                            <div class="user-name"><?= htmlspecialchars($chat['username']) ?></div>
                            <div class="user-preview"><?= $chat['message_count'] ?> messages</div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <div class="chat-area">
            <?php if ($selectedChat): ?>
                <div class="chat-header">
                    <?php 
                    foreach ($allChats as $chat) {
                        if ($chat['id'] == $selectedChat) {
                            echo '💬 ' . htmlspecialchars($chat['username']);
                            break;
                        }
                    }
                    ?>
                </div>

                <div class="chat-messages" id="messagesContainer">
                    <?php if (empty($messages)): ?>
                        <div class="empty-state">
                            <p style="font-size: 14px; color: #bbb;">No messages yet</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($messages as $msg): ?>
                            <div class="message <?= ($msg['sender_id'] == 1) ? 'admin' : 'user' ?>">
                                <div>
                                    <div class="message-bubble">
                                        <?= nl2br(htmlspecialchars($msg['message'])) ?>
                                    </div>
                                    <div class="message-time">
                                        <?= date('M d, H:i', strtotime($msg['created_at'])) ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <div class="chat-footer">
                    <div class="templates">
                        <button class="template-btn" onclick="useTemplate('Hello! 👋 Thank you for contacting us.')">👋 Welcome</button>
                        <button class="template-btn" onclick="useTemplate('I understand your issue. Let me help!')">💙 Understand</button>
                        <button class="template-btn" onclick="useTemplate('✅ Your issue has been resolved!')">✅ Resolved</button>
                        <button class="template-btn" onclick="useTemplate('⏳ Your request is being processed...')">⏳ Processing</button>
                    </div>

                    <div class="ai-suggestions" id="aiSuggestions">
                        <div class="suggestions-label">🤖 AI Suggestions:</div>
                        <div class="suggestions-list" id="suggestionsList"></div>
                    </div>

                    <div class="input-area">
                        <input type="text" id="messageInput" placeholder="Type a reply..." autocomplete="off" onkeyup="showAISuggestions()">
                        <button onclick="sendMessage()">➤</button>
                    </div>
                </div>
            <?php else: ?>
                <div class="empty-state">
                    <p>👋 Select a chat to start messaging</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        const selectedChatId = <?= $selectedChat ?>;

        function selectChat(chatId) {
            window.location.href = '?page=chatbot&chat=' + chatId;
        }

        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            if (!message || !selectedChatId) return;

            fetch(window.location.href, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'message=' + encodeURIComponent(message) + '&chat_id=' + selectedChatId
            })
            .then(res => res.json())
            .then(result => {
                if (result.success) {
                    input.value = '';
                    document.getElementById('aiSuggestions').classList.remove('show');
                    loadMessages();
                }
            })
            .catch(err => console.error('Error:', err));
        }

        function loadMessages() {
            fetch(window.location.href, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'get_messages=1&chat_id=' + selectedChatId
            })
            .then(res => res.json())
            .then(messages => {
                const container = document.getElementById('messagesContainer');
                container.innerHTML = '';
                if (messages.length === 0) {
                    container.innerHTML = '<div class="empty-state"><p style="font-size: 14px; color: #bbb;">No messages yet</p></div>';
                    return;
                }
                messages.forEach(msg => {
                    const isAdmin = msg.sender_id == 1;
                    // Convert MySQL datetime format to ISO format
                    const dateStr = msg.created_at.replace(' ', 'T');
                    const time = new Date(dateStr).toLocaleString('en-US', {
                        month: 'short',
                        day: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: true
                    });
                    const msgHtml = `<div class="message ${isAdmin ? 'admin' : 'user'}"><div><div class="message-bubble">${msg.message.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')}</div><div class="message-time">${time}</div></div></div>`;
                    container.innerHTML += msgHtml;
                });
                container.scrollTop = container.scrollHeight;
            })
            .catch(err => console.error('Error:', err));
        }

        function useTemplate(text) {
            document.getElementById('messageInput').value = text;
            showAISuggestions();
        }

        function showAISuggestions() {
            const input = document.getElementById('messageInput').value.trim();
            if (!input || input.length < 3) {
                document.getElementById('aiSuggestions').classList.remove('show');
                return;
            }

            fetch('/extract/api/chatbot_ai.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'action=get_suggestions&message=' + encodeURIComponent(input)
            })
            .then(r => r.json())
            .then(data => {
                if (data.suggestions && data.suggestions.length > 0) {
                    const suggestionsList = document.getElementById('suggestionsList');
                    suggestionsList.innerHTML = data.suggestions.map(s => `<button class="suggestion-btn" onclick="addSuggestion('${s.replace(/'/g, "\\'")}')">${s}</button>`).join('');
                    document.getElementById('aiSuggestions').classList.add('show');
                }
            })
            .catch(err => console.error('AI Error:', err));
        }

        function addSuggestion(text) {
            const input = document.getElementById('messageInput');
            input.value = text;
            input.focus();
        }

        // Save selected chat to session storage
        if (selectedChatId) {
            sessionStorage.setItem('selectedChatbotId', selectedChatId);
        }
        
        // Restore selected chat from session storage after refresh
        const savedChatId = sessionStorage.getItem('selectedChatbotId');
        if (savedChatId && !selectedChatId) {
            window.location.href = '?page=chatbot&chat=' + savedChatId;
        }
        
        if (selectedChatId) {
            // Auto-refresh messages every 500ms (4x faster!)
            setInterval(loadMessages, 500);
            
            // Load messages immediately on page load
            window.addEventListener('load', () => {
                loadMessages();
                setTimeout(() => {
                    const container = document.getElementById('messagesContainer');
                    if (container) container.scrollTop = container.scrollHeight;
                }, 100);
            });
        }
        
        // Auto-refresh chat list every 3 seconds
        setInterval(() => {
            fetch(window.location.href, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'get_chats=1'
            })
            .then(res => res.json())
            .then(data => {
                if (data && data.length > 0) {
                    console.log('Chat list refreshed: ' + data.length + ' chats');
                }
            })
            .catch(err => console.error('Error fetching chats:', err));
        }, 3000);

        const msgInput = document.getElementById('messageInput');
        if (msgInput) {
            msgInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    sendMessage();
                }
            });
        }

        const searchUsers = document.getElementById('searchUsers');
        if (searchUsers) {
            searchUsers.addEventListener('keyup', (e) => {
                const search = e.target.value.toLowerCase();
                const items = document.querySelectorAll('.user-item');
                items.forEach(item => {
                    const name = item.querySelector('.user-name').textContent.toLowerCase();
                    item.style.display = name.includes(search) ? 'block' : 'none';
                });
            });
        }
    </script>
</body>
</html>
