<?php
require_once dirname(__DIR__) . '/config/config.php';
requireLogin();
requireAdmin();

$pdo = getDBConnection();

// Handle reply
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $convId = intval($_POST['conversation_id'] ?? 0);
    $message = trim($_POST['message'] ?? '');
    $action = $_POST['action'] ?? '';
    
    if ($action === 'reply' && $convId && $message) {
        $stmt = $pdo->prepare("INSERT INTO support_messages (conversation_id, sender_id, sender_role, message, created_at) VALUES (?, ?, ?, ?, NOW())");
        $stmt->execute([$convId, $_SESSION['user_id'], $_SESSION['role'], $message]);
        
        $stmt = $pdo->prepare("UPDATE support_conversations SET updated_at = NOW() WHERE id = ?");
        $stmt->execute([$convId]);
    }
    
    if ($action === 'close' && $convId) {
        $stmt = $pdo->prepare("UPDATE support_conversations SET status = 'closed', updated_at = NOW() WHERE id = ?");
        $stmt->execute([$convId]);
    }
    
    header('Location: support.php' . ($convId ? '?chat=' . $convId : ''));
    exit;
}

// Get selected conversation
$selectedConv = null;
$selectedMessages = [];
$selectedUser = null;

if (isset($_GET['chat'])) {
    $chatId = intval($_GET['chat']);
    $stmt = $pdo->prepare("SELECT c.*, u.name as user_name, u.email as user_email FROM support_conversations c JOIN users u ON c.user_id = u.id WHERE c.id = ?");
    $stmt->execute([$chatId]);
    $selectedConv = $stmt->fetch();
    
    if ($selectedConv) {
        $stmt = $pdo->prepare("SELECT m.*, u.name as sender_name FROM support_messages m LEFT JOIN users u ON m.sender_id = u.id WHERE m.conversation_id = ? ORDER BY m.created_at ASC");
        $stmt->execute([$chatId]);
        $selectedMessages = $stmt->fetchAll();
        
        // Mark messages as read
        $stmt = $pdo->prepare("UPDATE support_messages SET is_read = 1 WHERE conversation_id = ? AND sender_role = 'user'");
        $stmt->execute([$chatId]);
    }
}

// Get all conversations
$conversations = $pdo->query("
    SELECT c.*, u.name as user_name, u.email as user_email,
    (SELECT COUNT(*) FROM support_messages WHERE conversation_id = c.id AND sender_role = 'user' AND is_read = 0) as unread_count,
    (SELECT message FROM support_messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_message
    FROM support_conversations c 
    JOIN users u ON c.user_id = u.id 
    ORDER BY c.updated_at DESC
")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Support - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', sans-serif; background: #0A1628; color: #fff; min-height: 100vh; display: flex; }
        .sidebar { width: 260px; background: #0F2744; height: 100vh; position: fixed; left: 0; top: 0; transition: transform 0.3s; z-index: 100; }
        .sidebar-header { padding: 1.5rem; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid #1E3A5F; }
        .sidebar-header i { font-size: 1.5rem; color: #F5A623; }
        .sidebar-header span { font-weight: 700; color: #F5A623; font-size: 1.25rem; }
        .sidebar-nav { padding: 1rem 0; }
        .nav-link { display: flex; align-items: center; gap: 12px; padding: 0.875rem 1.5rem; color: #E5E7EB; text-decoration: none; border-left: 3px solid transparent; }
        .nav-link:hover, .nav-link.active { background: #1E3A5F; color: #F5A623; border-left-color: #F5A623; }
        .nav-link i { width: 20px; text-align: center; }
        .nav-divider { height: 1px; background: #1E3A5F; margin: 0.75rem 1.5rem; }
        .main { flex: 1; margin-left: 260px; }
        .header { background: #0F2744; padding: 1rem 1.5rem; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #1E3A5F; }
        .header-toggle { background: none; border: none; color: #fff; font-size: 1.25rem; cursor: pointer; display: none; }
        .menu-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 99; display: none; }
        .menu-overlay.active { display: block; }
        
        .support-container { display: flex; height: calc(100vh - 60px); }
        .conv-list { width: 320px; background: #0F2744; border-right: 1px solid #1E3A5F; overflow-y: auto; }
        .conv-header { padding: 1rem; border-bottom: 1px solid #1E3A5F; font-weight: 600; color: #F5A623; }
        .conv-item { padding: 1rem; border-bottom: 1px solid #1E3A5F; cursor: pointer; transition: background 0.2s; display: block; text-decoration: none; color: inherit; }
        .conv-item:hover, .conv-item.active { background: #1E3A5F; }
        .conv-item .name { font-weight: 600; display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.25rem; }
        .conv-item .email { font-size: 0.8rem; color: #9CA3AF; margin-bottom: 0.25rem; }
        .conv-item .preview { font-size: 0.85rem; color: #9CA3AF; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .conv-item .unread { background: #EF4444; color: #fff; font-size: 0.7rem; padding: 0.15rem 0.5rem; border-radius: 10px; }
        .conv-item .status { font-size: 0.7rem; padding: 0.15rem 0.5rem; border-radius: 10px; }
        .conv-item .status-open { background: rgba(16,185,129,0.2); color: #10B981; }
        .conv-item .status-closed { background: rgba(156,163,175,0.2); color: #9CA3AF; }
        
        .chat-area { flex: 1; display: flex; flex-direction: column; background: #0A1628; }
        .chat-header { padding: 1rem; background: #0F2744; border-bottom: 1px solid #1E3A5F; display: flex; justify-content: space-between; align-items: center; }
        .chat-header .user-info h3 { font-size: 1rem; margin-bottom: 0.25rem; }
        .chat-header .user-info p { font-size: 0.8rem; color: #9CA3AF; }
        .chat-actions { display: flex; gap: 0.5rem; }
        .chat-actions button { padding: 0.5rem 1rem; border: none; border-radius: 6px; cursor: pointer; font-size: 0.85rem; }
        .btn-close { background: #EF4444; color: #fff; }
        
        .chat-messages { flex: 1; padding: 1rem; overflow-y: auto; display: flex; flex-direction: column; gap: 1rem; }
        .chat-msg { max-width: 70%; padding: 0.75rem 1rem; border-radius: 12px; }
        .chat-msg.user { background: #1E3A5F; align-self: flex-start; border-bottom-left-radius: 4px; }
        .chat-msg.admin { background: #F5A623; color: #0A1628; align-self: flex-end; border-bottom-right-radius: 4px; }
        .chat-msg .meta { font-size: 0.7rem; opacity: 0.7; margin-top: 0.25rem; }
        
        .chat-input { padding: 1rem; background: #0F2744; border-top: 1px solid #1E3A5F; }
        .chat-input form { display: flex; gap: 0.5rem; }
        .chat-input input { flex: 1; padding: 0.75rem; background: #1E3A5F; border: 1px solid #2D4A6F; border-radius: 8px; color: #fff; font-size: 1rem; }
        .chat-input input:focus { outline: none; border-color: #F5A623; }
        .chat-input button { padding: 0.75rem 1.5rem; background: #F5A623; color: #0A1628; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; }
        
        .no-chat { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; color: #9CA3AF; }
        .no-chat i { font-size: 4rem; color: #1E3A5F; margin-bottom: 1rem; }
        
        .empty-conv { padding: 3rem; text-align: center; color: #9CA3AF; }
        .empty-conv i { font-size: 3rem; color: #1E3A5F; margin-bottom: 1rem; display: block; }
        
        @media (max-width: 992px) {
            .conv-list { width: 280px; }
        }
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-260px); }
            .sidebar.active { transform: translateX(0); }
            .main { margin-left: 0; }
            .header-toggle { display: block; }
            .support-container { flex-direction: column; }
            .conv-list { width: 100%; height: 200px; border-right: none; border-bottom: 1px solid #1E3A5F; }
            .chat-area { height: calc(100vh - 260px); }
        }
    </style>
</head>
<body>
    <div class="menu-overlay" id="menuOverlay" onclick="toggleSidebar()"></div>
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header"><i class="fas fa-feather-alt"></i><span><?php echo SITE_NAME; ?></span></div>
        <nav class="sidebar-nav">
            <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
            <a href="users.php" class="nav-link"><i class="fas fa-users"></i> Users</a>
            <a href="orders.php" class="nav-link"><i class="fas fa-shopping-cart"></i> Orders</a>
            <a href="fund-requests.php" class="nav-link"><i class="fas fa-money-bill"></i> Fund Requests</a>
            <div class="nav-divider"></div>
            <a href="smm-services.php" class="nav-link"><i class="fas fa-rocket"></i> SMM Services</a>
            <a href="sms-services.php" class="nav-link"><i class="fas fa-sms"></i> SMS Services</a>
            <div class="nav-divider"></div>
            <a href="offers.php" class="nav-link"><i class="fas fa-tags"></i> Offers</a>
            <a href="banners.php" class="nav-link"><i class="fas fa-ad"></i> Banners</a>
            <a href="support.php" class="nav-link active"><i class="fas fa-headset"></i> Support</a>
            <div class="nav-divider"></div>
            <a href="<?php echo SITE_URL; ?>/logout.php" class="nav-link"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </nav>
    </aside>
    
    <main class="main">
        <header class="header">
            <button class="header-toggle" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
            <span><i class="fas fa-headset"></i> Support Chat</span>
            <span><?php echo htmlspecialchars($_SESSION['name']); ?></span>
        </header>
        
        <div class="support-container">
            <div class="conv-list">
                <div class="conv-header"><i class="fas fa-comments"></i> Conversations</div>
                <?php if (empty($conversations)): ?>
                <div class="empty-conv">
                    <i class="fas fa-inbox"></i>
                    <p>No conversations yet</p>
                </div>
                <?php else: ?>
                <?php foreach ($conversations as $conv): ?>
                <a href="?chat=<?php echo $conv['id']; ?>" class="conv-item <?php echo ($selectedConv && $selectedConv['id'] == $conv['id']) ? 'active' : ''; ?>">
                    <div class="name">
                        <?php echo htmlspecialchars($conv['user_name']); ?>
                        <?php if ($conv['unread_count'] > 0): ?>
                        <span class="unread"><?php echo $conv['unread_count']; ?></span>
                        <?php else: ?>
                        <span class="status status-<?php echo $conv['status']; ?>"><?php echo ucfirst($conv['status']); ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="email"><?php echo htmlspecialchars($conv['user_email']); ?></div>
                    <div class="preview"><?php echo htmlspecialchars(substr($conv['last_message'] ?? 'No messages', 0, 50)); ?></div>
                </a>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
            
            <div class="chat-area">
                <?php if ($selectedConv): ?>
                <div class="chat-header">
                    <div class="user-info">
                        <h3><?php echo htmlspecialchars($selectedConv['user_name']); ?></h3>
                        <p><?php echo htmlspecialchars($selectedConv['user_email']); ?></p>
                    </div>
                    <div class="chat-actions">
                        <?php if ($selectedConv['status'] === 'open'): ?>
                        <form method="POST" style="display:inline;">
                            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                            <input type="hidden" name="conversation_id" value="<?php echo $selectedConv['id']; ?>">
                            <input type="hidden" name="action" value="close">
                            <button type="submit" class="btn-close"><i class="fas fa-times"></i> Close</button>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="chat-messages" id="chatMessages">
                    <?php foreach ($selectedMessages as $msg): ?>
                    <div class="chat-msg <?php echo $msg['sender_role'] === 'user' ? 'user' : 'admin'; ?>">
                        <?php echo nl2br(htmlspecialchars($msg['message'])); ?>
                        <div class="meta">
                            <?php echo $msg['sender_role'] === 'user' ? 'User' : htmlspecialchars($msg['sender_name'] ?? 'Admin'); ?> • 
                            <?php echo date('M d, g:i A', strtotime($msg['created_at'])); ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <?php if ($selectedConv['status'] === 'open'): ?>
                <div class="chat-input">
                    <form method="POST">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                        <input type="hidden" name="conversation_id" value="<?php echo $selectedConv['id']; ?>">
                        <input type="hidden" name="action" value="reply">
                        <input type="text" name="message" placeholder="Type your reply..." required autocomplete="off">
                        <button type="submit"><i class="fas fa-paper-plane"></i> Send</button>
                    </form>
                </div>
                <?php endif; ?>
                
                <?php else: ?>
                <div class="no-chat">
                    <i class="fas fa-comments"></i>
                    <h3>Select a conversation</h3>
                    <p>Choose a conversation from the list to view messages</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
    
    <script>
        function toggleSidebar() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('menuOverlay').classList.toggle('active'); 
        }
        
        // Scroll to bottom of messages
        const chatMessages = document.getElementById('chatMessages');
        if (chatMessages) {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
    </script>
</body>
</html>