<?php
include 'header.php';
if (!isset($_SESSION['user_id'])) {
    echo "<script>location.href='login.php';</script>";
    exit;
}

$user_id = $_SESSION['user_id'];
$pdo = db();

// Fetch user info
$stmt = $pdo->prepare("SELECT uid, username FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Get user IP
$user_ip = $_SERVER['REMOTE_ADDR'];
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $user_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}

// Fetch greeting message
$stmt = $pdo->prepare("SELECT value FROM settings WHERE name = 'chat_greeting'");
$stmt->execute();
$greeting = $stmt->fetchColumn() ?: 'Hello! Welcome to NovaEx official support. How can we help you today?';

// Handle POST request via AJAX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    $msg = trim($_POST['message']);
    if ($msg !== '') {
        $stmt = $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'user', ?)");
        $stmt->execute([$user_id, $msg]);
        echo json_encode(['success' => true]);
    }
    exit;
}
?>

<style>
    #chat-box::-webkit-scrollbar { width: 6px; }
    #chat-box::-webkit-scrollbar-track { background: transparent; }
    #chat-box::-webkit-scrollbar-thumb { background: #2b3139; border-radius: 10px; }
    #chat-box { flex: 1; overflow-y: auto; padding: 25px; display: flex; flex-direction: column; gap: 20px; background: #161a1e; scroll-behavior: smooth; }
    
    .msg-container { display: flex; flex-direction: column; transition: all 0.3s ease; }
    .msg-content { max-width: 75%; padding: 12px 18px; border-radius: 18px; font-size: 14px; line-height: 1.6; }
</style>

<div id="chat-container" class="container" style="max-width: 850px; margin: 30px auto; padding: 0; height: 75vh;">
    <div id="chat-card" class="card" style="background: #1e2329; border: 1px solid #2b3139; border-radius: 20px; display: flex; flex-direction: column; height: 100%; box-shadow: 0 10px 30px rgba(0,0,0,0.3);">
        <!-- Header -->
        <div style="padding: 20px 25px; border-bottom: 1px solid #2b3139; display: flex; align-items: center; justify-content: space-between;">
            <div style="display: flex; align-items: center; gap: 15px;">
                <div style="width: 45px; height: 45px; background: #f0b90b; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: black;">
                    <i class="fas fa-headset fa-lg"></i>
                </div>
                <div>
                    <h3 style="margin: 0; font-size: 18px; color: white;">NovaEx Support</h3>
                    <div style="display: flex; align-items: center; gap: 5px; font-size: 12px; color: #00c087;">
                        <span style="width: 8px; height: 8px; background: #00c087; border-radius: 50%; display: inline-block;"></span> Online
                    </div>
                </div>
            </div>
            <div style="text-align: right; font-size: 12px; color: #848e9c;">
                <div>UID: <?php echo $user['uid']; ?></div>
                <div>IP: <?php echo $user_ip; ?></div>
            </div>
        </div>
        
        <!-- Chat Body -->
        <div id="chat-box">
            <!-- Messages loaded via JS -->
            <div style="text-align: center; color: #848e9c; padding: 20px;">Connecting to support...</div>
        </div>
        
        <!-- Input Area -->
        <div style="padding: 20px; background: #1e2329; border-top: 1px solid #2b3139;">
            <form id="chat-form" style="display: flex; gap: 12px; align-items: center;">
                <button type="button" onclick="document.getElementById('image-input').click()" style="background: #2b3139; border: 1px solid #3b424d; color: #f0b90b; width: 45px; height: 45px; border-radius: 12px; cursor: pointer;">
                    <i class="fas fa-plus"></i>
                </button>
                <input type="file" id="image-input" accept="image/*" style="display: none;" onchange="uploadImage(this)">
                
                <input type="text" id="chat-input" placeholder="Type a message..." 
                    style="flex: 1; background: #161a1e; border: 1px solid #2b3139; border-radius: 12px; padding: 14px 20px; color: white; outline: none; font-size: 14px;" autocomplete="off">
                
                <button type="submit" style="background: #f0b90b; border: none; color: black; width: 50px; height: 50px; border-radius: 12px; cursor: pointer; display: flex; align-items: center; justify-content: center;">
                    <i class="fas fa-paper-plane fa-lg"></i>
                </button>
            </form>
        </div>
    </div>
</div>

<script>
    const chatBox = document.getElementById('chat-box');
    const chatForm = document.getElementById('chat-form');
    const chatInput = document.getElementById('chat-input');
    let lastMsgId = 0;
    const greeting = `<?php echo addslashes($greeting); ?>`;

    async function loadMessages() {
        try {
            const resp = await fetch('api/get_messages.php');
            const res = await resp.json();
            if (res.success) {
                const newMessages = res.data;
                if (newMessages.length === 0) {
                    chatBox.innerHTML = `
                        <div style="display: flex; flex-direction: column; align-items: flex-start;">
                            <div class="msg-content" style="background: #2b3139; color: white; border-bottom-left-radius: 4px; border: 1px solid #3b424d;">
                                ${greeting.replace(/\n/g, '<br>')}
                            </div>
                            <span style="font-size: 10px; color: #5e6673; margin-top: 6px;">Support Bot</span>
                        </div>
                    `;
                } else {
                    let html = '';
                    newMessages.forEach(m => {
                        const isUser = m.sender === 'user';
                        html += `
                            <div class="msg-container" style="align-items: ${isUser ? 'flex-end' : 'flex-start'};
">
                                <div class="msg-content" style="${isUser ? 'background: #f0b90b; color: black; border-bottom-right-radius: 4px;' : 'background: #2b3139; color: white; border-bottom-left-radius: 4px; border: 1px solid #3b424d;'}">
                                    ${m.type === 'image' ? `<img src="${m.message}" style="max-width:100%; border-radius:8px; cursor:pointer;" onclick="window.open(this.src)">` : m.message.replace(/\n/g, '<br>')}
                                </div>
                                <span style="font-size: 10px; color: #5e6673; margin-top: 6px;">${new Date(m.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
                            </div>
                        `;
                    });
                    
                    const isAtBottom = chatBox.scrollHeight - chatBox.scrollTop <= chatBox.clientHeight + 100;
                    chatBox.innerHTML = html;
                    if (isAtBottom) chatBox.scrollTop = chatBox.scrollHeight;
                }
            }
        } catch (e) {}
    }

    chatForm.onsubmit = async (e) => {
        e.preventDefault();
        const msg = chatInput.value.trim();
        if (!msg) return;

        chatInput.value = '';
        const formData = new FormData();
        formData.append('message', msg);
        
        await fetch('chat.php', { method: 'POST', body: formData });
        loadMessages();
    };

    function uploadImage(input) {
        if (!input.files || !input.files[0]) return;
        const formData = new FormData();
        formData.append('image', input.files[0]);
        fetch('api/upload_chat_image.php', { method: 'POST', body: formData }).then(() => loadMessages());
    }

    loadMessages();
    setInterval(loadMessages, 2000);
</script>

<?php include 'footer.php'; ?>