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

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

// Handle sending message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    ob_clean();
    header('Content-Type: application/json');
    
    $message = trim($_POST['message'] ?? '');
    $ticketId = intval($_POST['ticket_id'] ?? 0);
    
    if (empty($message)) {
        echo json_encode(['success' => false]);
        exit();
    }
    
    if ($ticketId <= 0) {
        echo json_encode(['success' => false]);
        exit();
    }
    
    try {
        $adminId = 1;
        $escaped_msg = addslashes($message);
        $sql = "INSERT INTO support_messages (ticket_id, sender_id, message, created_at)
                VALUES ($ticketId, $adminId, '$escaped_msg', NOW())";
        
        $db->query($sql);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false]);
    }
    exit();
}

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

// Handle fetching ticket list
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['get_ticket_list'])) {
    ob_clean();
    header('Content-Type: application/json');
    
    $aiWidgetChats = $db->fetchAll("
       SELECT 
           s.id,
           s.user_id,
           u.name AS username,
           COALESCE(u.phone, u.phone_number, u.mobile, 'N/A') AS userphone,
           s.title,
           s.status,
           s.created_at,
           COUNT(m.id) as message_count,
           MAX(m.created_at) as last_message_time
       FROM support_tickets s
       JOIN users u ON u.id = s.user_id
       LEFT JOIN support_messages m ON m.ticket_id = s.id
       WHERE s.title = 'Admin Chat (AI Widget)'
       GROUP BY s.id
       ORDER BY last_message_time DESC, s.created_at DESC
    ") ?: [];
    
    $regularChats = $db->fetchAll("
       SELECT 
           s.id,
           s.user_id,
           u.name AS username,
           COALESCE(u.phone, u.phone_number, u.mobile, 'N/A') AS userphone,
           s.title,
           s.status,
           s.created_at,
           COUNT(m.id) as message_count,
           MAX(m.created_at) as last_message_time
       FROM support_tickets s
       JOIN users u ON u.id = s.user_id
       LEFT JOIN support_messages m ON m.ticket_id = s.id
       WHERE s.title != 'Admin Chat (AI Widget)'
       GROUP BY s.id
       ORDER BY last_message_time DESC, s.created_at DESC
    ") ?: [];
    
    echo json_encode([
        'ai_chats' => $aiWidgetChats,
        'regular_chats' => $regularChats
    ]);
    exit();
}

/* Get all tickets with user info - SEPARATE AI WIDGET CHATS */
$aiWidgetChats = $db->fetchAll("
   SELECT 
       s.id,
       s.user_id,
       u.name AS username,
       COALESCE(u.phone, u.phone_number, u.mobile, 'N/A') AS userphone,
       s.title,
       s.status,
       s.created_at,
       COUNT(m.id) as message_count,
       MAX(m.created_at) as last_message_time
   FROM support_tickets s
   JOIN users u ON u.id = s.user_id
   LEFT JOIN support_messages m ON m.ticket_id = s.id
   WHERE s.title = 'Admin Chat (AI Widget)'
   GROUP BY s.id
   ORDER BY last_message_time DESC, s.created_at DESC
") ?: [];

$regularChats = $db->fetchAll("
   SELECT 
       s.id,
       s.user_id,
       u.name AS username,
       COALESCE(u.phone, u.phone_number, u.mobile, 'N/A') AS userphone,
       s.title,
       s.status,
       s.created_at,
       COUNT(m.id) as message_count,
       MAX(m.created_at) as last_message_time
   FROM support_tickets s
   JOIN users u ON u.id = s.user_id
   LEFT JOIN support_messages m ON m.ticket_id = s.id
   WHERE s.title != 'Admin Chat (AI Widget)'
   GROUP BY s.id
   ORDER BY last_message_time DESC, s.created_at DESC
") ?: [];

/* Get all tickets with user info */
$allTickets = array_merge($aiWidgetChats, $regularChats);

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

// Load messages for opened ticket
$messages = [];
$selectedUserInfo = null;

if ($selectedTicket) {
    $sql = "SELECT m.*, u.name as sender_name
            FROM support_messages m
            LEFT JOIN users u ON u.id = m.sender_id
            WHERE m.ticket_id = '$selectedTicket'
            ORDER BY m.created_at ASC";
    $messages = $db->fetchAll($sql) ?: [];
    
    // Get selected user info
    foreach ($allTickets as $t) {
        if ($t['id'] == $selectedTicket) {
            $selectedUserInfo = $t;
            break;
        }
    }
}
ob_end_clean();
?>

<style>
.whatsapp-wrapper {
    display: flex;
    height: calc(100vh - 150px);
    gap: 0;
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.chat-sidebar {
    width: 30%;
    background: #fff;
    border-right: 1px solid #e5e5e5;
    overflow-y: auto;
    min-width: 280px;
}

.chat-main {
    width: 70%;
    display: flex;
    flex-direction: column;
    background: #f0f0f0;
}

.search-box {
    padding: 12px;
    border-bottom: 1px solid #e5e5e5;
}

.search-box input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 20px;
    font-size: 14px;
    outline: none;
}

.search-box input:focus {
    border-color: #007aff;
}

.user-list {
    overflow-y: auto;
    max-height: calc(100vh - 250px);
}

.user-item {
    padding: 12px 15px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background 0.2s;
    text-decoration: none;
    color: #000;
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.user-item:hover {
    background: #f5f5f5;
}

.user-item.active {
    background: #e7f3ff;
    border-left: 4px solid #007aff;
}

.user-name {
    font-weight: 600;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.user-meta {
    font-size: 12px;
    color: #999;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.message-count-badge {
    background: #007aff;
    color: white;
    border-radius: 50%;
    min-width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 11px;
    font-weight: 600;
}

/* Chat Main Area */
.chat-header {
    background: #007aff;
    color: white;
    padding: 15px 20px;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #0051d5;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    background: #fff;
}

.message-group {
    display: flex;
    margin-bottom: 12px;
    align-items: flex-start;
}

.message-group.user {
    justify-content: flex-start;
}

.message-group.admin {
    justify-content: flex-end;
}

.message-bubble {
    max-width: 60%;
    padding: 10px 14px;
    border-radius: 18px;
    word-wrap: break-word;
    position: relative;
    box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.message-group.user .message-bubble {
    background: #e9e9eb;
    color: #000;
    border-bottom-left-radius: 4px;
}

.message-group.admin .message-bubble {
    background: #007aff;
    color: white;
    border-bottom-right-radius: 4px;
}

.message-time {
    font-size: 11px;
    color: #999;
    margin-top: 4px;
}

.message-group.admin .message-time {
    text-align: right;
}

.empty-chat {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #999;
    text-align: center;
}

.chat-footer {
    padding: 12px 20px;
    border-top: 1px solid #ddd;
    background: #fff;
    display: flex;
    gap: 10px;
}

.chat-footer input {
    flex: 1;
    padding: 10px 14px;
    border: 1px solid #ddd;
    border-radius: 20px;
    font-size: 14px;
    outline: none;
}

.chat-footer input:focus {
    border-color: #007aff;
}

.chat-footer button {
    background: #007aff;
    color: white;
    border: none;
    border-radius: 50%;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 18px;
}

.chat-footer button:hover {
    background: #0051d5;
}

.no-chats {
    padding: 20px;
    text-align: center;
    color: #999;
    font-size: 14px;
}

@media (max-width: 1024px) {
    .chat-sidebar {
        width: 35%;
        min-width: 300px;
    }
    .chat-main {
        width: 65%;
    }
    .message-bubble {
        max-width: 75%;
    }
}

@media (max-width: 768px) {
    .whatsapp-wrapper {
        height: calc(100vh - 100px);
    }
    .chat-sidebar {
        display: none;
    }
    .chat-main {
        width: 100%;
    }
}
</style>

<h4 class="mb-3">💬 Support Chat</h4>

<div class="whatsapp-wrapper">
    <!-- LEFT SIDEBAR: USER LIST -->
    <div class="chat-sidebar">
        <div class="search-box">
            <input type="text" id="searchUsers" placeholder="🔍 Search users..." 
                   onkeyup="filterUsers(this.value)">
        </div>

        <div class="user-list">
            <?php if (empty($allTickets)): ?>
                <div class="no-chats">No support chats yet</div>
            <?php else: ?>
                <?php if (count($aiWidgetChats) > 0): ?>
                    <div style="padding: 8px 12px; background: #fff3cd; border-bottom: 2px solid #ffc107;">
                        <strong style="font-size: 12px; color: #856404;">🤖 AI Widget Chats (<?= count($aiWidgetChats) ?>)</strong>
                    </div>
                    <?php foreach ($aiWidgetChats as $t): ?>
                    <a href="?page=support&chat=<?= $t['id'] ?>" 
                       class="user-item <?= ($selectedTicket == $t['id']) ? 'active' : '' ?>"
                       data-user-id="<?= $t['user_id'] ?>"
                       data-ticket-id="<?= $t['id'] ?>"
                       style="background: #fffbf0; border-left: 3px solid #ffc107;">
                        <div class="user-name">
                            🤖 <?= htmlspecialchars($t['username']) ?>
                        </div>
                        <div class="user-meta">
                            <span><?= htmlspecialchars($t['userphone']) ?></span>
                            <?php if ($t['message_count'] > 0): ?>
                                <span class="message-count-badge"><?= $t['message_count'] ?></span>
                            <?php endif; ?>
                        </div>
                    </a>
                    <?php endforeach; ?>
                    <hr style="margin: 0; opacity: 0.3;">
                <?php endif; ?>
                
                <?php foreach ($regularChats as $t): ?>
                <a href="?page=support&chat=<?= $t['id'] ?>" 
                   class="user-item <?= ($selectedTicket == $t['id']) ? 'active' : '' ?>"
                   data-user-id="<?= $t['user_id'] ?>"
                   data-ticket-id="<?= $t['id'] ?>">
                    <div class="user-name">
                        <?= htmlspecialchars($t['username']) ?>
                    </div>
                    <div class="user-meta">
                        <span><?= htmlspecialchars($t['userphone']) ?></span>
                        <?php if ($t['message_count'] > 0): ?>
                            <span class="message-count-badge"><?= $t['message_count'] ?></span>
                        <?php endif; ?>
                    </div>
                </a>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- RIGHT SIDE: CHAT WINDOW -->
    <div class="chat-main">
        <?php if (!$selectedTicket || !$selectedUserInfo): ?>
            <div class="empty-chat">
                <p>Select a chat to start messaging</p>
            </div>
        <?php else: ?>
            <!-- Chat Header -->
            <div class="chat-header">
                <div>
                    <div><?= htmlspecialchars($selectedUserInfo['username']) ?></div>
                    <small><?= htmlspecialchars($selectedUserInfo['userphone']) ?></small>
                </div>
                <span style="font-size: 14px; opacity: 0.9;">Ticket #<?= $selectedTicket ?></span>
            </div>

            <!-- Messages Area -->
            <div class="chat-messages" id="messagesContainer">
                <?php if (empty($messages)): ?>
                    <div class="empty-chat">
                        <p>No messages yet. Start the conversation!</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($messages as $m): ?>
                        <div class="message-group <?= ($m['sender_id'] == 1) ? 'admin' : 'user' ?>">
                            <div>
                                <div class="message-bubble">
                                    <?= nl2br(htmlspecialchars($m['message'])) ?>
                                </div>
                                <div class="message-time">
                                    <?= date('M d, H:i', strtotime($m['created_at'])) ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- Chat Input -->
            <div class="chat-footer">
                <div style="margin-bottom: 8px; display: flex; gap: 4px; flex-wrap: wrap;" id="templatePanel">
                    <button onclick="useTemplate('Hello! 👋 Thank you for reaching out. How can I help you today?')" type="button" style="background: #f0f0f0; border: 1px solid #ddd; padding: 4px 8px; border-radius: 4px; font-size: 11px; cursor: pointer;">👋 Welcome</button>
                    <button onclick="useTemplate('I understand your issue. Let me help you with that.')" type="button" style="background: #f0f0f0; border: 1px solid #ddd; padding: 4px 8px; border-radius: 4px; font-size: 11px; cursor: pointer;">💙 Understand</button>
                    <button onclick="useTemplate('✅ Great! Your issue has been resolved. Please refresh and check.')" type="button" style="background: #f0f0f0; border: 1px solid #ddd; padding: 4px 8px; border-radius: 4px; font-size: 11px; cursor: pointer;">✅ Resolved</button>
                    <button onclick="useTemplate('⏳ Your request is being processed. I'll update you shortly.')" type="button" style="background: #f0f0f0; border: 1px solid #ddd; padding: 4px 8px; border-radius: 4px; font-size: 11px; cursor: pointer;">⏳ Processing</button>
                </div>
                <div style="margin-bottom: 10px; display: none;" id="aiSuggestionsPanel">
                    <small style="color: #666; font-size: 11px;">🤖 AI Suggestions:</small>
                    <div style="display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px;" id="aiSuggestionsContainer"></div>
                </div>
                <input type="text" id="messageInput" placeholder="Type a reply..." autocomplete="off" onkeyup="showAISuggestions()">
                <button onclick="sendAdminMessage(<?= $selectedTicket ?>)" type="button">➤</button>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
const selectedTicketId = <?= $selectedTicket ?: 'null' ?>;

function filterUsers(query) {
    const items = document.querySelectorAll('.user-item');
    items.forEach(item => {
        const name = item.querySelector('.user-name').textContent.toLowerCase();
        item.style.display = name.includes(query.toLowerCase()) ? 'flex' : 'none';
    });
}

function sendAdminMessage(ticketId) {
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    
    if (!message) return;

    const data = new FormData();
    data.append('message', message);
    data.append('ticket_id', ticketId);

    fetch(window.location.href, {
        method: 'POST',
        body: data
    })
    .then(res => res.json())
    .then(result => {
        if (result.success) {
            messageInput.value = '';
            loadAdminMessages(ticketId);
        }
    })
    .catch(err => console.error('Error:', err));
}

function loadAdminMessages(ticketId) {
    if (!ticketId) return;
    
    const data = new FormData();
    data.append('get_messages', '1');
    data.append('ticket_id', ticketId);

    fetch(window.location.href, {
        method: 'POST',
        body: data
    })
    .then(res => res.json())
    .then(messages => {
        const container = document.getElementById('messagesContainer');
        if (!container) return;
        
        container.innerHTML = '';
        
        if (!messages || messages.length === 0) {
            container.innerHTML = '<div class="empty-chat"><p>No messages yet. Start the conversation!</p></div>';
            return;
        }

        messages.forEach(msg => {
            const isAdmin = msg.sender_id == 1;
            const groupClass = isAdmin ? 'admin' : 'user';
            // Convert MySQL datetime format to ISO format
            const dateStr = msg.created_at.replace(' ', 'T');
            const dateObj = new Date(dateStr);
            const timeStr = dateObj.toLocaleString('en-US', {
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                hour12: true
            });

            const msgHtml = `
                <div class="message-group ${groupClass}">
                    <div>
                        <div class="message-bubble">
                            ${msg.message.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')}
                        </div>
                        <div class="message-time">${timeStr}</div>
                    </div>
                </div>
            `;
            container.innerHTML += msgHtml;
        });

        // Auto scroll to bottom
        container.scrollTop = container.scrollHeight;
    })
    .catch(err => console.error('Error:', err));
}

// Store selected ticket in session storage to persist after refresh
const selectedTicketIdStored = sessionStorage.getItem('selectedTicketId');
if (selectedTicketIdStored && !selectedTicketId) {
    // Reload page with correct ticket parameter
    if (parseInt(selectedTicketIdStored) !== selectedTicketId) {
        window.location.href = '?page=support&chat=' + selectedTicketIdStored;
    }
}

// Save selected ticket ID when clicking
document.addEventListener('click', function(e) {
    const userItem = e.target.closest('.user-item');
    if (userItem) {
        const ticketId = userItem.getAttribute('data-ticket-id');
        if (ticketId) {
            sessionStorage.setItem('selectedTicketId', ticketId);
        }
    }
});

// Function to reload chat list via AJAX
function reloadChatListAjax() {
    fetch(window.location.href, {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'get_ticket_list=1'
    })
    .then(res => res.json())
    .then(data => {
        if (data.ai_chats || data.regular_chats) {
            console.log('Chat list refreshed - ' + (data.ai_chats.length + data.regular_chats.length) + ' chats');
            // Could update UI here without page reload if needed
        }
    })
    .catch(err => console.error('Error reloading chat list:', err));
}

// Auto-refresh messages every 500ms if ticket selected
let autoRefreshInterval = null;
if (selectedTicketId) {
    // Load messages immediately
    loadAdminMessages(selectedTicketId);
    
    // Then auto-refresh every 500ms for messages
    autoRefreshInterval = setInterval(() => loadAdminMessages(selectedTicketId), 500);
    
    // Auto-refresh chat list every 3 seconds
    setInterval(() => reloadChatListAjax(), 3000);
    
    // Initial scroll on load
    window.addEventListener('load', () => {
        setTimeout(() => {
            const container = document.getElementById('messagesContainer');
            if (container) container.scrollTop = container.scrollHeight;
        }, 100);
    });
}

// Allow Enter key to send message
document.addEventListener('DOMContentLoaded', () => {
    const input = document.getElementById('messageInput');
    if (input) {
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                if (selectedTicketId) {
                    sendAdminMessage(selectedTicketId);
                }
            }
        });
    }
});

// AI Suggestions for Admin
async function showAISuggestions() {
    const messageInput = document.getElementById('messageInput');
    const userMessage = messageInput.value.trim();
    
    if (!userMessage || userMessage.length < 3) {
        document.getElementById('aiSuggestionsPanel').style.display = 'none';
        return;
    }
    
    try {
        const formData = new FormData();
        formData.append('action', 'suggest_response');
        formData.append('ticket_id', selectedTicketId);
        formData.append('user_message', userMessage);
        
        const res = await fetch('../api/admin_ai.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await res.json();
        
        if (data.success && data.suggestions) {
            const container = document.getElementById('aiSuggestionsContainer');
            container.innerHTML = '';
            
            data.suggestions.slice(0, 3).forEach(suggestion => {
                const btn = document.createElement('button');
                btn.type = 'button';
                btn.style.cssText = 'background: #e8f0ff; color: #667eea; border: 1px solid #667eea; padding: 6px 10px; border-radius: 4px; font-size: 11px; cursor: pointer; transition: all 0.2s;';
                btn.textContent = '💡 ' + suggestion.substring(0, 40) + '...';
                btn.onmouseover = function() { 
                    this.style.background = '#667eea';
                    this.style.color = 'white';
                };
                btn.onmouseout = function() { 
                    this.style.background = '#e8f0ff';
                    this.style.color = '#667eea';
                };
                btn.onclick = () => useSuggestion(suggestion);
                container.appendChild(btn);
            });
            
            document.getElementById('aiSuggestionsPanel').style.display = 'block';
        }
    } catch (error) {
        console.error('AI Suggestions error:', error);
    }
}

function useSuggestion(suggestion) {
    const messageInput = document.getElementById('messageInput');
    messageInput.value = suggestion;
    document.getElementById('aiSuggestionsPanel').style.display = 'none';
    messageInput.focus();
}

function useTemplate(text) {
    const messageInput = document.getElementById('messageInput');
    messageInput.value = text;
    messageInput.focus();
    document.getElementById('aiSuggestionsPanel').style.display = 'none';
}
</script>
