<?php
session_start();
require_once 'config.php';
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Live Support - <?= defined('APP_NAME') ? APP_NAME : 'GameHub' ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #ff4a4a; --bg: #F7F8FA; }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, sans-serif; background: var(--bg); max-width: 480px; margin: 0 auto; min-height: 100vh; }

        .header { display: flex; align-items: center; padding: 14px 15px; background: #fff; box-shadow: 0 1px 8px rgba(0,0,0,0.06); }
        .back { font-size: 20px; color: #333; text-decoration: none; margin-right: 12px; }
        .title { font-size: 17px; font-weight: 800; }

        .problem-types { padding: 20px 15px; }
        .problem-types h3 { font-size: 14px; color: #666; margin-bottom: 12px; }
        .problem-btn { display: block; width: 100%; text-align: left; padding: 14px 16px; margin-bottom: 10px; background: #fff; border: 1px solid #eee; border-radius: 12px; font-size: 14px; font-weight: 600; color: #333; cursor: pointer; transition: 0.2s; }
        .problem-btn:hover, .problem-btn:active { border-color: var(--primary); background: #fff5f5; }
        .problem-btn i { margin-right: 10px; color: var(--primary); width: 22px; }

        .chat-section { display: none; padding: 15px; }
        .chat-section.show { display: block; }
        .chat-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
        .chat-header h3 { font-size: 15px; }
        .btn-new { padding: 6px 12px; background: #f0f0f0; border: none; border-radius: 8px; font-size: 12px; font-weight: 600; cursor: pointer; }
        .chat-messages { background: #fff; border-radius: 12px; min-height: 280px; max-height: 50vh; overflow-y: auto; padding: 12px; margin-bottom: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); }
        .msg { margin-bottom: 12px; clear: both; }
        .msg.user { text-align: right; }
        .msg .bubble { display: inline-block; max-width: 85%; padding: 10px 14px; border-radius: 14px; font-size: 13px; }
        .msg.user .bubble { background: linear-gradient(135deg, #ff6c6b, var(--primary)); color: #fff; }
        .msg.admin .bubble { background: #f0f0f0; color: #333; }
        .msg .time { font-size: 10px; color: #999; margin-top: 4px; }
        .chat-reply { display: flex; gap: 8px; padding: 10px 0; }
        .chat-reply input { flex: 1; padding: 12px 14px; border: 1px solid #ddd; border-radius: 25px; font-size: 14px; outline: none; }
        .chat-reply input:focus { border-color: var(--primary); }
        .chat-reply button { padding: 12px 20px; background: var(--primary); color: #fff; border: none; border-radius: 25px; font-weight: 700; cursor: pointer; }

        .first-msg-wrap { display: none; padding: 15px; }
        .first-msg-wrap.show { display: block; }
        .first-msg-wrap textarea { width: 100%; padding: 14px; border: 1px solid #ddd; border-radius: 12px; font-size: 14px; min-height: 100px; margin-bottom: 12px; resize: vertical; }
        .first-msg-wrap button { width: 100%; padding: 14px; background: var(--primary); color: #fff; border: none; border-radius: 12px; font-weight: 700; cursor: pointer; }

        .toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background: #333; color: #fff; padding: 10px 20px; border-radius: 8px; font-size: 13px; z-index: 9999; opacity: 0; transition: opacity 0.3s; }
        .toast.show { opacity: 1; }
    </style>
</head>
<body>
    <div class="header">
        <a href="index.php" class="back"><i class="fas fa-chevron-left"></i></a>
        <span class="title">Live Support</span>
    </div>

    <div class="problem-types" id="problemTypes">
        <h3>Choose your issue (Contact to agents)</h3>
        <button type="button" class="problem-btn" data-type="withdraw_problem"><i class="fas fa-money-bill-wave"></i> Withdrawal Problem</button>
        <button type="button" class="problem-btn" data-type="deposit_problem"><i class="fas fa-wallet"></i> Deposit Problem</button>
        <button type="button" class="problem-btn" data-type="bonus_problem"><i class="fas fa-gift"></i> Bonus Problem</button>
        <button type="button" class="problem-btn" data-type="bug_problem"><i class="fas fa-bug"></i> Bug Problem</button>
        <button type="button" class="problem-btn" data-type="advance_option"><i class="fas fa-cog"></i> Advance Option</button>
        <button type="button" class="problem-btn" data-type="contact_agent"><i class="fas fa-headset"></i> Contact to Agents</button>
    </div>

    <div class="first-msg-wrap" id="firstMsgWrap">
        <p class="mb-2" style="margin-bottom:10px; font-weight:600;" id="selectedTypeLabel">Describe your issue</p>
        <textarea id="firstMsg" placeholder="Type your message..."></textarea>
        <button type="button" id="startChatBtn">Start Chat</button>
    </div>

    <div class="chat-section" id="chatSection">
        <div class="chat-header">
            <h3 id="chatTitle">Chat</h3>
            <button type="button" class="btn-new" id="newChatBtn">New Chat</button>
        </div>
        <div class="chat-messages" id="chatMessages"></div>
        <div class="chat-reply">
            <input type="text" id="replyInput" placeholder="Type message...">
            <button type="button" id="sendReplyBtn">Send</button>
        </div>
    </div>

    <div id="toast" class="toast"></div>

    <script>
        const typeLabels = { withdraw_problem: 'Withdrawal Problem', deposit_problem: 'Deposit Problem', bonus_problem: 'Bonus Problem', bug_problem: 'Bug Problem', advance_option: 'Advance Option', contact_agent: 'Contact to Agents' };
        let currentTicketId = null;
        let currentType = '';

        function showToast(msg) {
            const t = document.getElementById('toast');
            t.textContent = msg;
            t.classList.add('show');
            setTimeout(() => t.classList.remove('show'), 2500);
        }

        function showProblems() {
            document.getElementById('problemTypes').style.display = 'block';
            document.getElementById('firstMsgWrap').classList.remove('show');
            document.getElementById('chatSection').classList.remove('show');
            currentTicketId = null;
        }

        function loadMessages(ticketId) {
            fetch('support_api.php?action=messages&ticket_id=' + ticketId)
                .then(r => r.json())
                .then(data => {
                    const box = document.getElementById('chatMessages');
                    box.innerHTML = '';
                    if (data.success && data.messages) {
                        data.messages.forEach(m => {
                            const div = document.createElement('div');
                            div.className = 'msg ' + (m.is_admin == 1 ? 'admin' : 'user');
                            div.innerHTML = '<div class="bubble">' + m.message.replace(/</g, '&lt;') + '</div><div class="time">' + m.created_at + '</div>';
                            box.appendChild(div);
                        });
                        box.scrollTop = box.scrollHeight;
                    }
                });
        }

        document.querySelectorAll('.problem-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                currentType = this.getAttribute('data-type');
                document.getElementById('selectedTypeLabel').textContent = typeLabels[currentType] + ' – Describe your issue';
                document.getElementById('firstMsgWrap').classList.add('show');
                document.getElementById('problemTypes').style.display = 'none';
                document.getElementById('firstMsg').value = '';
            });
        });

        document.getElementById('startChatBtn').addEventListener('click', function() {
            const msg = document.getElementById('firstMsg').value.trim();
            if (!msg) { showToast('Please enter a message'); return; }
            const fd = new FormData();
            fd.append('action', 'create');
            fd.append('problem_type', currentType);
            fd.append('message', msg);
            fetch('support_api.php', { method: 'POST', body: fd })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        currentTicketId = data.ticket_id;
                        document.getElementById('firstMsgWrap').classList.remove('show');
                        document.getElementById('chatSection').classList.add('show');
                        document.getElementById('chatTitle').textContent = typeLabels[currentType];
                        loadMessages(currentTicketId);
                        showToast('Chat started. Agent will reply soon.');
                    } else showToast(data.message || 'Error');
                })
                .catch(() => showToast('Error'));
        });

        document.getElementById('sendReplyBtn').addEventListener('click', sendReply);
        document.getElementById('replyInput').addEventListener('keypress', function(e) { if (e.key === 'Enter') sendReply(); });

        function sendReply() {
            if (!currentTicketId) return;
            const msg = document.getElementById('replyInput').value.trim();
            if (!msg) return;
            const fd = new FormData();
            fd.append('action', 'reply');
            fd.append('ticket_id', currentTicketId);
            fd.append('message', msg);
            fetch('support_api.php', { method: 'POST', body: fd })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('replyInput').value = '';
                        loadMessages(currentTicketId);
                    }
                });
        }

        document.getElementById('newChatBtn').addEventListener('click', function() {
            showProblems();
            document.getElementById('problemTypes').style.display = 'block';
        });

        fetch('support_api.php?action=list')
            .then(r => r.json())
            .then(data => {
                if (data.success && data.tickets && data.tickets.length > 0) {
                    const open = data.tickets.find(t => t.status === 'open');
                    if (open) {
                        currentTicketId = open.id;
                        currentType = open.problem_type;
                        document.getElementById('problemTypes').style.display = 'none';
                        document.getElementById('chatSection').classList.add('show');
                        document.getElementById('chatTitle').textContent = typeLabels[open.problem_type] || open.problem_type;
                        loadMessages(open.id);
                    }
                }
            });
    </script>
</body>
</html>
