<?php
session_start();
if (!isset($_SESSION["user_id"])) {
    header("Location: index.php");
    exit;
}
require_once __DIR__ . "/db/config.php";

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

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

// Messages will be loaded via AJAX
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>客服中心 - 全球接码</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #3b82f6;
            --primary-gradient: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
            --bg-body: #f1f5f9;
            --surface: #ffffff;
            --text-main: #1e293b;
            --text-muted: #64748b;
            --border-color: #e2e8f0;
            --sidebar-width: 280px;
            --radius-xl: 24px;
        }
        body {
            font-family: "Plus Jakarta Sans", sans-serif;
            background-color: var(--bg-body);
            color: var(--text-main);
            overflow: hidden;
            letter-spacing: -0.01em;
        }
        
        .main-content {
            margin-left: var(--sidebar-width);
            padding: 2rem;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .chat-container {
            background: white;
            border: 1px solid var(--border-color);
            border-radius: var(--radius-xl);
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;
            box-shadow: 0 10px 25px -5px rgba(0,0,0,0.05);
            margin-bottom: 1rem;
        }
        
        .chat-header {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid var(--border-color);
            background: #fff;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .chat-body {
            flex: 1;
            padding: 1.5rem;
            overflow-y: auto;
            background-color: #f8fafc;
            scroll-behavior: smooth;
        }
        
        .chat-footer {
            padding: 1.25rem 1.5rem;
            border-top: 1px solid var(--border-color);
            background: #fff;
        }

        .message-row {
            display: flex;
            margin-bottom: 1.25rem;
            width: 100%;
        }
        .message-row.me {
            justify-content: flex-end;
        }
        .message-row.them {
            justify-content: flex-start;
        }

        .message-bubble {
            max-width: 75%;
            padding: 0.85rem 1.15rem;
            border-radius: 20px;
            font-size: 0.95rem;
            font-weight: 500;
            line-height: 1.5;
            position: relative;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
        }

        .me .message-bubble {
            background: var(--primary-gradient);
            color: white;
            border-bottom-right-radius: 4px;
        }
        .them .message-bubble {
            background: white;
            color: var(--text-main);
            border-bottom-left-radius: 4px;
            border: 1px solid var(--border-color);
        }

        .message-time {
            font-size: 0.7rem;
            margin-top: 0.4rem;
            opacity: 0.7;
            font-weight: 600;
        }
        .me .message-time { text-align: right; color: rgba(255,255,255,0.8); }
        .them .message-time { text-align: left; color: var(--text-muted); }

        .btn-send { 
            background: var(--primary-gradient); 
            border: none; 
            border-radius: 12px; 
            width: 48px; 
            height: 48px; 
            color: white; 
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .btn-send:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3); }
        .form-control { border: 1.5px solid var(--border-color); border-radius: 12px; padding: 12px 16px; background: #f8fafc; font-weight: 500; font-size: 0.95rem; }
        .form-control:focus { background: white; border-color: var(--primary); box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1); }

        .status-dot {
            width: 10px;
            height: 10px;
            background: #22c55e;
            border-radius: 50%;
            display: inline-block;
            border: 2px solid white;
            box-shadow: 0 0 0 2px #dcfce7;
        }

        @media (max-width: 992px) {
            .main-content { margin-left: 0; padding: 1rem; }
            .sidebar { display: none; }
        }

        /* Scrollbar styling */
        .chat-body::-webkit-scrollbar { width: 6px; }
        .chat-body::-webkit-scrollbar-track { background: transparent; }
        .chat-body::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
    </style>
</head>
<body>

<?php include "includes/sidebar.php"; ?>

<div class="main-content">
    <div class="mb-3 d-flex justify-content-between align-items-center">
        <div>
            <h4 class="fw-bold mb-0">在线客服</h4>
            <p class="text-muted small mb-0">为您解答任何关于收码与充值的疑问</p>
        </div>
        <div class="d-flex align-items-center gap-2 bg-white px-3 py-2 rounded-pill border shadow-sm">
            <span class="status-dot"></span>
            <span class="small fw-bold text-success">客服在线</span>
        </div>
    </div>

    <div class="chat-container">
        <div class="chat-header">
            <div class="avatar bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                <i class="fas fa-headset"></i>
            </div>
            <div>
                <div class="fw-bold small">官方技术支持</div>
                <div class="text-muted" style="font-size: 11px;">通常在几分钟内回复</div>
            </div>
        </div>
        <div class="chat-body" id="chatBody">
            <div class="message-row them" id="welcomeMsg">
                <div class="message-bubble">
                    您好，" . htmlspecialchars($user["username"]) . "！我是您的专属技术支持。如果您遇到任何关于充值未到账、号码收不到码或其他系统问题，请随时在这里留言，我们会尽快回复您。
                    <div class="message-time">" . date("H:i") . "</div>
                </div>
            </div>
            <!-- Messages loaded via JS -->
        </div>
        <div class="chat-footer">
<input type="file" id="imageInput" style="display:none" accept="image/*">
            <button type="button" class="btn btn-outline-secondary" onclick="document.getElementById("imageInput").click()"><i class="fas fa-image"></i></button> <form id="chatForm" class="d-flex gap-2">
                <input type="text" id="msgInput" class="form-control" placeholder="输入您的问题..." required autocomplete="off">
                <button type="submit" class="btn btn-send"><i class="fas fa-paper-plane"></i></button>
            </form>
        </div>
    </div>
</div>

<audio id="notifSound" src="https://assets.mixkit.co/active_storage/sfx/2354/2354-preview.mp3" preload="auto"></audio>

<script>
    const chatBody = document.getElementById("chatBody");
    const chatForm = document.getElementById("chatForm");
    const msgInput = document.getElementById("msgInput");
    const notifSound = document.getElementById("notifSound");
    let loadedMessageIds = new Set();
    let isInitialLoad = true;

    async function loadMessages() {
        try {
            const res = await fetch("ajax_handler.php?action=get_messages");
            const data = await res.json();
            if (data.code === 0) {
                let hasNew = false;
                data.data.forEach(msg => {
                    if (!loadedMessageIds.has(msg.id)) {
                        appendMessage(msg);
                        loadedMessageIds.add(msg.id);
                        hasNew = true;
                        
                        // Play sound if it"s a new admin message (not during initial load)
                        if (!isInitialLoad && msg.sender === "admin") {
                            try { notifSound.play().catch(e => {}); } catch(e) {}
                        }
                    }
                });
                
                if (hasNew) {
                    chatBody.scrollTop = chatBody.scrollHeight;
                }
                isInitialLoad = false;
            }
        } catch (e) {
            console.error("Failed to load messages");
        }
    }

    function appendMessage(msg) {
        const row = document.createElement("div");
        row.className = `message-row ${msg.sender === "user" ? "me" : "them"}`;
        
        const time = new Date(msg.created_at.replace(" ", "T") + "Z").toLocaleTimeString([], {hour: "2-digit", minute:"2-digit"});
        
        row.innerHTML = `
            <div class="message-bubble">
                ${escapeHtml(msg.message)}
                <div class="message-time">${time}</div>
            </div>
        `;
        chatBody.appendChild(row);
    }

    chatForm.addEventListener("submit", async (e) => {
        e.preventDefault();
        const msg = msgInput.value.trim();
        if (!msg) return;

        msgInput.value = "";

        const formData = new FormData();
        formData.append("message", msg);

        try {
            const res = await fetch("ajax_handler.php?action=send_message", {
                method: "POST",
                body: formData
            });
            const data = await res.json();
            if (data.code === 0) {
                loadMessages();
            } else {
                alert("发送失败: " + data.msg);
            }
        } catch (e) {
            alert("发送失败，请检查网络");
        }
    });
document.getElementById("imageInput").addEventListener("change", async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const formData = new FormData();
    formData.append("image", file);
    const res = await fetch("ajax_handler.php?action=upload_image", { method: "POST", body: formData });
    const data = await res.json();
    if (data.code === 0) {
        const msgData = new FormData();
        msgData.append("message", data.url);
        await fetch("ajax_handler.php?action=send_message", { method: "POST", body: msgData });
        loadMessages();
    }
});

    function escapeHtml(text) {
        const div = document.createElement("div");
        div.textContent = text;
        return div.innerHTML;
    }

    setInterval(loadMessages, 3000);
    loadMessages();
</script>
</body>
</html>
