<?php
/**
 * Admin Live Chat Management
 */

// Handle AJAX requests BEFORE including header to avoid output buffer conflicts
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // Load required files for AJAX
    require_once __DIR__ . '/../config/config.php';
    require_once __DIR__ . '/../config/database.php';
    require_once __DIR__ . '/../includes/functions.php';
    require_once __DIR__ . '/../includes/Auth.php';
    
    // Require admin login for AJAX too
    if (!auth()->isAdmin()) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit;
    }
    
    header('Content-Type: application/json');
    
    if ($_POST['action'] === 'send_message') {
        $chatId = (int)$_POST['chat_id'];
        $message = trim($_POST['message']);
        
        if ($chatId && $message) {
            $chat = dbFetch("SELECT user_id FROM support_chats WHERE id = ?", [$chatId]);
            if ($chat) {
                dbInsert('support_chat_messages', [
                    'chat_id' => $chatId,
                    'user_id' => $chat['user_id'],
                    'sender_type' => 'admin',
                    'sender_id' => auth()->getAdminId(),
                    'message' => $message,
                    'is_admin' => 1
                ]);
                echo json_encode(['success' => true]);
                exit;
            }
        }
        echo json_encode(['success' => false]);
        exit;
    }
    
    if ($_POST['action'] === 'get_messages') {
        $chatId = (int)$_POST['chat_id'];
        $messages = dbFetchAll("SELECT * FROM support_chat_messages WHERE chat_id = ? ORDER BY created_at ASC", [$chatId]);
        
        // Get user info
        $user = dbFetch("SELECT CONCAT(u.first_name, ' ', u.last_name) as name FROM support_chats sc JOIN users u ON sc.user_id = u.id WHERE sc.id = ?", [$chatId]);
        
        // Mark as read
        dbQuery("UPDATE support_chat_messages SET is_read = 1 WHERE chat_id = ? AND is_admin = 0", [$chatId]);
        
        echo json_encode(['success' => true, 'messages' => $messages, 'user' => $user]);
        exit;
    }
    
    if ($_POST['action'] === 'get_history') {
        $history = dbFetchAll("
            SELECT sc.*, CONCAT(u.first_name, ' ', u.last_name) as user_name,
            (SELECT message FROM support_chat_messages WHERE chat_id = sc.id ORDER BY created_at DESC LIMIT 1) as last_message
            FROM support_chats sc
            LEFT JOIN users u ON sc.user_id = u.id
            WHERE sc.status != 'active'
            ORDER BY sc.updated_at DESC LIMIT 50
        ");
        echo json_encode(['success' => true, 'chats' => $history ?? []]);
        exit;
    }
    
    echo json_encode(['success' => false, 'error' => 'Invalid action']);
    exit;
}

// Normal page load - include header (which starts output buffering & HTML)
require_once 'includes/header.php';

// Get all active chats
$chats = [];
try {
    $chats = dbFetchAll("
        SELECT sc.*, CONCAT(u.first_name, ' ', u.last_name) as user_name, u.email,
        (SELECT message FROM support_chat_messages WHERE chat_id = sc.id ORDER BY created_at DESC LIMIT 1) as last_message,
        (SELECT COUNT(*) FROM support_chat_messages WHERE chat_id = sc.id AND is_admin = 0 AND is_read = 0) as unread_count
        FROM support_chats sc
        LEFT JOIN users u ON sc.user_id = u.id
        WHERE sc.status = 'active'
        ORDER BY sc.updated_at DESC
    ");
} catch (Exception $e) {
    // If table doesn't exist, create it
    try {
        dbQuery("CREATE TABLE IF NOT EXISTS support_chats (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            status ENUM('active','closed') DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )");
        dbQuery("CREATE TABLE IF NOT EXISTS support_chat_messages (
            id INT AUTO_INCREMENT PRIMARY KEY,
            chat_id INT NOT NULL,
            user_id INT NOT NULL,
            message TEXT,
            is_admin TINYINT DEFAULT 0,
            is_read TINYINT DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");
    } catch (Exception $e2) {}
}

?>

<style>
.chat-container{display:grid;grid-template-columns:300px 1fr;gap:20px;height:calc(100vh - 200px)}
.chat-list{background:var(--bg-card);border:1px solid var(--border-color);border-radius:12px;overflow:hidden}
.chat-list-header{padding:16px;background:var(--bg-tertiary);border-bottom:1px solid var(--border-color);font-weight:600}
.chat-tabs{display:flex;gap:8px}
.chat-tab{background:transparent;border:1px solid var(--border-color);color:var(--text-muted);padding:6px 14px;border-radius:6px;cursor:pointer;font-size:.85rem;transition:all .2s}
.chat-tab:hover{background:var(--bg-card);color:#fff}
.chat-tab.active{background:var(--primary);color:#fff;border-color:var(--primary)}
.chat-items{overflow-y:auto;max-height:calc(100vh - 300px)}
.chat-item{display:flex;align-items:center;gap:12px;padding:14px 16px;border-bottom:1px solid var(--border-color);cursor:pointer}
.chat-item:hover,.chat-item.active{background:var(--bg-tertiary)}
.chat-avatar{width:40px;height:40px;background:var(--primary);border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:600}
.chat-info{flex:1}
.chat-info h4{font-size:.9rem;margin-bottom:2px}
.chat-info p{font-size:.75rem;color:var(--text-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:180px}
.chat-meta{text-align:right}
.chat-time{font-size:.7rem;color:var(--text-muted)}
.chat-unread{background:var(--danger);color:#fff;font-size:.65rem;padding:2px 6px;border-radius:10px;margin-top:4px;display:inline-block}

.chat-window{background:var(--bg-card);border:1px solid var(--border-color);border-radius:12px;display:flex;flex-direction:column}
.chat-window-header{padding:16px;background:var(--bg-tertiary);border-bottom:1px solid var(--border-color);display:flex;align-items:center;gap:12px}
.chat-window-header h3{flex:1}
.chat-messages{flex:1;padding:16px;overflow-y:auto;display:flex;flex-direction:column;gap:12px}
.message{max-width:70%;padding:10px 14px;border-radius:12px;font-size:.9rem}
.message.user{background:var(--bg-tertiary);align-self:flex-start}
.message.admin{background:var(--primary);color:#fff;align-self:flex-end}
.message .time{font-size:.65rem;opacity:.7;margin-top:4px}
.chat-input-box{display:flex;gap:10px;padding:16px;border-top:1px solid var(--border-color)}
.chat-input{flex:1;background:var(--bg-tertiary);border:1px solid var(--border-color);border-radius:8px;padding:12px;color:#fff;font-size:.9rem}
.chat-send-btn{background:var(--primary);border:none;border-radius:8px;padding:12px 20px;color:#fff;cursor:pointer}
.chat-send-btn:hover{opacity:.85}
.no-chat{display:flex;align-items:center;justify-content:center;height:100%;color:var(--text-muted)}
</style>

<div class="page-header">
    <h1 class="page-title"><i class="fas fa-comments"></i> Live Chat</h1>
</div>

<div class="chat-container">
    <div class="chat-list">
        <div class="chat-list-header">
            <div class="chat-tabs">
                <button class="chat-tab active" data-tab="active" onclick="switchTab('active')">Active (<?= count($chats) ?>)</button>
                <button class="chat-tab" data-tab="closed" onclick="switchTab('closed')">History</button>
            </div>
        </div>
        
        <!-- Active Chats -->
        <div class="chat-items" id="activeChats">
            <?php if (empty($chats)): ?>
            <div style="padding:20px;text-align:center;color:var(--text-muted)">No active chats</div>
            <?php else: ?>
            <?php foreach ($chats as $chat): ?>
            <div class="chat-item" data-id="<?= $chat['id'] ?>">
                <div class="chat-avatar"><?= strtoupper(substr($chat['user_name'] ?? 'U', 0, 2)) ?></div>
                <div class="chat-info">
                    <h4><?= htmlspecialchars($chat['user_name'] ?? 'Unknown User') ?></h4>
                    <p><?= htmlspecialchars($chat['last_message'] ?? 'No messages') ?></p>
                </div>
                <div class="chat-meta">
                    <div class="chat-time"><?= date('H:i', strtotime($chat['updated_at'])) ?></div>
                    <?php if ($chat['unread_count'] > 0): ?>
                    <span class="chat-unread"><?= $chat['unread_count'] ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <!-- Closed Chats (History) -->
        <div class="chat-items" id="historyChats" style="display:none">
            <div style="padding:20px;text-align:center;color:var(--text-muted)">
                <button onclick="loadHistory()" class="btn btn-sm btn-secondary">Load History</button>
            </div>
        </div>
    </div>
    
    <div class="chat-window" id="chatWindow">
        <div class="no-chat" id="noChat">
            <div style="text-align:center">
                <i class="fas fa-comments" style="font-size:3rem;margin-bottom:16px;opacity:.3"></i>
                <p>Select a chat to start responding</p>
            </div>
        </div>
        <div id="chatContent" style="display:none;flex-direction:column;height:100%">
            <div class="chat-window-header">
                <div class="chat-avatar" id="chatAvatar">US</div>
                <h3 id="chatUserName">User Name</h3>
            </div>
            <div class="chat-messages" id="chatMessages"></div>
            <div class="chat-input-box">
                <input type="text" class="chat-input" id="messageInput" placeholder="Type your reply...">
                <button class="chat-send-btn" id="sendBtn"><i class="fas fa-paper-plane"></i></button>
            </div>
        </div>
    </div>
</div>

<script>
let currentChatId = null;

function switchTab(tab) {
    document.querySelectorAll('.chat-tab').forEach(t => t.classList.remove('active'));
    const btn = document.querySelector(`.chat-tab[data-tab="${tab}"]`);
    if (btn) btn.classList.add('active');
    
    const activeDiv = document.getElementById('activeChats');
    const historyDiv = document.getElementById('historyChats');
    
    if (tab === 'active') {
        activeDiv.style.display = 'block';
        historyDiv.style.display = 'none';
    } else {
        activeDiv.style.display = 'none';
        historyDiv.style.display = 'block';
        loadHistory();
    }
}

function loadHistory() {
    const container = document.getElementById('historyChats');
    container.innerHTML = '<div style="padding:20px;text-align:center"><i class="fas fa-spinner fa-spin"></i> Loading...</div>';
    
    fetch('live-chat.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'action=get_history'
    })
    .then(r => {
        if (!r.ok) throw new Error('Network error: ' + r.status);
        return r.json();
    })
    .then(d => {
        if (d.success && d.chats && d.chats.length > 0) {
            container.innerHTML = '';
            d.chats.forEach(chat => {
                const div = document.createElement('div');
                div.className = 'chat-item history';
                div.dataset.id = chat.id;
                div.onclick = () => loadChat(chat.id);
                div.innerHTML = `
                    <div class="chat-avatar">${(chat.user_name || 'U').substring(0, 2).toUpperCase()}</div>
                    <div class="chat-info">
                        <h4>${chat.user_name || 'Unknown'} <span style="font-size:0.7em;color:var(--text-muted)">(${chat.status})</span></h4>
                        <p>${chat.last_message || 'No messages'}</p>
                    </div>
                    <div class="chat-meta">
                        <div class="chat-time">${new Date(chat.updated_at).toLocaleDateString()}</div>
                    </div>
                `;
                container.appendChild(div);
            });
        } else {
            container.innerHTML = '<div style="padding:20px;text-align:center;color:var(--text-muted)">No history found</div>';
        }
    })
    .catch(err => {
        console.error('loadHistory error:', err);
        container.innerHTML = '<div style="padding:20px;text-align:center;color:var(--text-muted)">Error loading history</div>';
    });
}

document.querySelectorAll('.chat-item').forEach(item => {
    item.addEventListener('click', () => {
        document.querySelectorAll('.chat-item').forEach(i => i.classList.remove('active'));
        item.classList.add('active');
        currentChatId = item.dataset.id;
        loadChat(currentChatId);
    });
});

function loadChat(chatId) {
    document.getElementById('noChat').style.display = 'none';
    document.getElementById('chatContent').style.display = 'flex';
    currentChatId = chatId;
    
    // Highlight if in list
    document.querySelectorAll('.chat-item').forEach(i => i.classList.remove('active'));
    const listItem = document.querySelector(`.chat-item[data-id="${chatId}"]`);
    if(listItem) listItem.classList.add('active');
    
    fetch('live-chat.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'action=get_messages&chat_id=' + chatId
    })
    .then(r => {
        if (!r.ok) throw new Error('Network error: ' + r.status);
        return r.json();
    })
    .then(d => {
        if (d.success) {
            // Update header info if available
            if (d.user) {
                document.getElementById('chatUserName').textContent = d.user.name;
                document.getElementById('chatAvatar').textContent = d.user.name.substring(0,2).toUpperCase();
            }

            const container = document.getElementById('chatMessages');
            container.innerHTML = '';
            if (d.messages.length === 0) {
                container.innerHTML = '<div style="text-align:center;color:var(--text-muted);padding:40px"><i class="fas fa-comment-slash" style="font-size:2rem;margin-bottom:10px;display:block;opacity:.3"></i>No messages yet</div>';
            } else {
                d.messages.forEach(msg => {
                    const div = document.createElement('div');
                    div.className = 'message ' + (parseInt(msg.is_admin) ? 'admin' : 'user');
                    div.innerHTML = msg.message + '<div class="time">' + new Date(msg.created_at).toLocaleTimeString() + '</div>';
                    container.appendChild(div);
                });
            }
            container.scrollTop = container.scrollHeight;
        }
    })
    .catch(err => {
        console.error('loadChat error:', err);
    });
}

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

function sendMessage() {
    const input = document.getElementById('messageInput');
    const msg = input.value.trim();
    if (!msg || !currentChatId) return;
    
    fetch('live-chat.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'action=send_message&chat_id=' + currentChatId + '&message=' + encodeURIComponent(msg)
    })
    .then(r => {
        if (!r.ok) throw new Error('Network error: ' + r.status);
        return r.json();
    })
    .then(d => {
        if (d.success) {
            input.value = '';
            loadChat(currentChatId);
        } else {
            console.error('Send failed:', d.error);
        }
    })
    .catch(err => {
        console.error('sendMessage error:', err);
    });
}

// Auto refresh
setInterval(() => { if (currentChatId) loadChat(currentChatId); }, 5000);
</script>


<!-- Debug Helper -->
<div style="padding: 20px; font-size: 0.8rem; color: #666; text-align: center;">
    Debug Info: 
    Chats: <?= dbCount('support_chats') ?> (Active: <?= dbCount('support_chats', "status = 'active'") ?>) | 
    Messages: <?= dbCount('support_chat_messages') ?>
</div>

<?php require_once 'includes/footer.php'; ?>
