<?php
session_start();
require_once 'config.php'; // Ensure this points to your DB connection file with $pdo

// Determine login state
$is_logged_in = isset($_SESSION['user_id']);
$user_id = $is_logged_in ? $_SESSION['user_id'] : null;
$user_uid = '';
$user_phone = '';

if ($is_logged_in) {
    try {
        $stmt = $pdo->prepare("SELECT id, number FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $u = $stmt->fetch();
        if ($u) {
            $user_uid = $u['id'];
            $user_phone = $u['number'];
        }
    } catch (Exception $e) {
        // Handle error gracefully
    }
}

// ==============================================================================
// AJAX HANDLERS FOR TICKET SYSTEM
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
    header('Content-Type: application/json');
    $action = $_POST['ajax_action'];
    
    try {
        if ($action === 'submit_ticket') {
            $subject = trim($_POST['subject'] ?? '');
            $message = trim($_POST['message'] ?? '');
            
            $phone = $is_logged_in ? $user_phone : trim($_POST['phone'] ?? '');
            $uid = $is_logged_in ? $user_uid : trim($_POST['uid'] ?? '');

            if (!$subject || !$message || !$phone || !$uid) {
                throw new Exception("All fields are required.");
            }

            $stmt = $pdo->prepare("INSERT INTO tickets (user_id, uid, phone, subject, message, status) VALUES (?, ?, ?, ?, ?, 'Open')");
            $stmt->execute([$user_id, $uid, $phone, $subject, $message]);
            
            echo json_encode(['success' => true]);
            exit;
        }
        
        if ($action === 'get_history') {
            $phone = $is_logged_in ? $user_phone : trim($_POST['phone'] ?? '');
            $uid = $is_logged_in ? $user_uid : trim($_POST['uid'] ?? '');

            if (!$phone || !$uid) {
                throw new Exception("Phone and UID are required.");
            }

            $stmt = $pdo->prepare("SELECT * FROM tickets WHERE phone = ? AND uid = ? ORDER BY id DESC");
            $stmt->execute([$phone, $uid]);
            $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode(['success' => true, 'data' => $tickets]);
            exit;
        }

        if ($action === 'get_ticket') {
            $ticket_id = (int)($_POST['ticket_id'] ?? 0);
            $phone = $is_logged_in ? $user_phone : trim($_POST['phone'] ?? '');
            $uid = $is_logged_in ? $user_uid : trim($_POST['uid'] ?? '');

            // Verify Ownership
            $stmt = $pdo->prepare("SELECT * FROM tickets WHERE id = ? AND phone = ? AND uid = ?");
            $stmt->execute([$ticket_id, $phone, $uid]);
            $ticket = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$ticket) {
                throw new Exception("Ticket not found or unauthorized.");
            }

            // Get Replies
            $stmtReplies = $pdo->prepare("SELECT * FROM ticket_replies WHERE ticket_id = ? ORDER BY created_at ASC");
            $stmtReplies->execute([$ticket_id]);
            $replies = $stmtReplies->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode(['success' => true, 'ticket' => $ticket, 'replies' => $replies]);
            exit;
        }

        if ($action === 'reply_ticket') {
            $ticket_id = (int)($_POST['ticket_id'] ?? 0);
            $message = trim($_POST['message'] ?? '');
            $phone = $is_logged_in ? $user_phone : trim($_POST['phone'] ?? '');
            $uid = $is_logged_in ? $user_uid : trim($_POST['uid'] ?? '');

            if (!$message) throw new Exception("Message cannot be empty.");

            // Verify Ownership and Status
            $stmt = $pdo->prepare("SELECT status FROM tickets WHERE id = ? AND phone = ? AND uid = ?");
            $stmt->execute([$ticket_id, $phone, $uid]);
            $ticket = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$ticket) throw new Exception("Unauthorized.");
            if ($ticket['status'] === 'Resolved') throw new Exception("This ticket is resolved and closed.");

            // Insert Reply
            $stmtRep = $pdo->prepare("INSERT INTO ticket_replies (ticket_id, sender_type, message) VALUES (?, 'User', ?)");
            $stmtRep->execute([$ticket_id, $message]);

            echo json_encode(['success' => true]);
            exit;
        }

    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Customer Service - PAKclub</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* Top Header */
        .top-header { background-color: #1a0f0a; padding: 15px 20px; display: flex; align-items: center; justify-content: space-between; position: sticky; top: 0; z-index: 100; border-bottom: 1px solid rgba(255, 255, 255, 0.05); }
        .back-btn { color: #ffffff; font-size: 20px; text-decoration: none; cursor: pointer; }
        .page-title { font-size: 18px; font-weight: 600; }
        .header-placeholder { width: 20px; }

        /* Support Banner Image */
        .support-banner { width: 100%; height: auto; display: block; }

        /* Support Items Container */
        .support-container { padding: 20px 15px; display: flex; flex-direction: column; gap: 15px; }

        /* Individual Support Item */
        .support-item { background-color: #241b16; border-radius: 12px; padding: 18px 20px; display: flex; align-items: center; justify-content: space-between; text-decoration: none; color: #ffffff; border: 1px solid rgba(255, 255, 255, 0.05); box-shadow: 0 4px 12px rgba(0,0,0,0.3); transition: transform 0.2s ease, background-color 0.2s ease; cursor: pointer; }
        .support-item:active { transform: scale(0.98); background-color: rgba(255, 255, 255, 0.05); }

        .support-left { display: flex; align-items: center; gap: 15px; }
        .icon-box { width: 45px; height: 45px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 22px; }
        
        .icon-wa { background: linear-gradient(135deg, #25D366, #128C7E); color: #fff; }
        .icon-ticket { background: linear-gradient(135deg, #f27914, #d95e04); color: #fff; }
        .icon-history { background: linear-gradient(135deg, #6c757d, #495057); color: #fff; }

        .support-text { display: flex; flex-direction: column; gap: 4px; }
        .support-title { font-size: 16px; font-weight: 600; }
        .support-subtitle { font-size: 12px; color: #a0938a; }
        .support-right { color: #a0938a; font-size: 16px; }

        /* Modals & Popups */
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.85); z-index: 10000; display: flex; flex-direction: column; align-items: center; justify-content: center; opacity: 0; pointer-events: none; transition: opacity 0.3s ease; }
        .modal-overlay.active { opacity: 1; pointer-events: all; }
        .modal-content { width: 90%; max-width: 380px; max-height: 85vh; background-color: #241b16; border-radius: 12px; display: flex; flex-direction: column; overflow: hidden; box-shadow: 0 10px 30px rgba(0,0,0,0.8); transform: scale(0.9); transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
        .modal-overlay.active .modal-content { transform: scale(1); }
        .modal-header { padding: 18px; text-align: center; font-size: 18px; font-weight: bold; color: #fff; border-bottom: 1px solid rgba(255,255,255,0.1); display: flex; justify-content: space-between; align-items: center; }
        .modal-body { padding: 20px; display: flex; flex-direction: column; gap: 15px; overflow-y: auto; }

        .close-txt-btn { color: #a0938a; cursor: pointer; font-size: 14px; }

        .input-field { background: #140904; border: 1px solid #4a3429; color: #fff; padding: 12px 15px; border-radius: 8px; font-size: 15px; width: 100%; outline: none; }
        .input-field:focus { border-color: #d95e04; }
        textarea.input-field { resize: none; min-height: 100px; }
        .btn-main { background: linear-gradient(to right, #f27914, #d95e04); color: #fff; border: none; padding: 12px; border-radius: 25px; font-size: 16px; font-weight: bold; cursor: pointer; width: 100%; }
        .btn-main:active { opacity: 0.8; }
        .btn-wa { background: linear-gradient(135deg, #25D366, #128C7E); color: #fff; border: none; padding: 12px; border-radius: 25px; font-size: 16px; font-weight: bold; cursor: pointer; width: 100%; }
        .btn-wa:active { opacity: 0.8; }

        /* History List */
        .ticket-list-item { background: #1a120e; padding: 15px; border-radius: 8px; border: 1px solid #3a2a22; cursor: pointer; margin-bottom: 10px; }
        .ticket-list-item:active { background: #140904; }
        .t-head { display: flex; justify-content: space-between; margin-bottom: 8px; }
        .t-subj { font-weight: 600; color: #fff; font-size: 15px; }
        .t-date { font-size: 11px; color: #a0938a; }
        
        .badge { padding: 3px 8px; border-radius: 4px; font-size: 11px; font-weight: bold; }
        .bg-open { background: #ff9800; color: #000; }
        .bg-prog { background: #00e5ff; color: #000; }
        .bg-res { background: #00e676; color: #000; }

        /* Chat UI for View Ticket */
        .chat-box { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 15px; margin-bottom: 15px; }
        .chat-bubble { max-width: 85%; padding: 12px; border-radius: 12px; font-size: 14px; line-height: 1.4; position: relative; word-wrap: break-word; }
        .chat-user { align-self: flex-end; background: #d95e04; color: #fff; border-bottom-right-radius: 2px; }
        .chat-admin { align-self: flex-start; background: #3a2a22; color: #fff; border-bottom-left-radius: 2px; }
        .chat-time { display: block; font-size: 10px; opacity: 0.7; margin-top: 5px; text-align: right; }

        .reply-box { display: flex; gap: 10px; }
        .reply-box input { flex: 1; }
        .reply-btn { background: #d95e04; color: #fff; border: none; border-radius: 8px; padding: 0 15px; cursor: pointer; }

        /* iPhone Style Glassy Toast */
        .custom-toast { visibility: hidden; min-width: auto; background: rgba(20, 20, 20, 0.75); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); color: #fff; text-align: center; border-radius: 50px; padding: 10px 24px; position: fixed; z-index: 999999; left: 50%; bottom: 50px; transform: translateX(-50%); font-size: 13px; font-weight: 500; opacity: 0; transition: opacity 0.3s, bottom 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); border: 1px solid rgba(255, 255, 255, 0.15); box-shadow: 0 4px 15px rgba(0,0,0,0.3); white-space: nowrap; }
        .custom-toast.show { visibility: visible; opacity: 1; bottom: 90px; }
    </style>
</head>
<body>

    <div style="display: none !important; visibility: hidden !important;">
        <?php include 'external/header.php'; ?>
    </div>

    <div class="top-header">
        <a href="javascript:history.back()" class="back-btn"><i class="fa-solid fa-chevron-left"></i></a>
        <div class="page-title">Customer Service</div>
        <div class="header-placeholder"></div>
    </div>

    <img src="https://pakclub.bet/img/6004/other/065238324-31671-file_20260417065238295.webp" alt="Support Banner" class="support-banner">

    <div class="support-container">
        
        <div class="support-item" onclick="handleWhatsAppContact()">
            <div class="support-left">
                <div class="icon-box icon-wa">
                    <i class="fa-brands fa-whatsapp"></i>
                </div>
                <div class="support-text">
                    <span class="support-title">WhatsApp Support</span>
                    <span class="support-subtitle">Chat with us directly</span>
                </div>
            </div>
            <div class="support-right">
                <i class="fa-solid fa-chevron-right"></i>
            </div>
        </div>

        <div class="support-item" onclick="window.location.href='https://www.whatsapp.com/channel/0029Vb7Phpp1NCrddQ1bQK0a'">
            <div class="support-left">
                <div class="icon-box icon-wa">
                    <i class="fa-brands fa-whatsapp"></i>
                </div>
                <div class="support-text">
                    <span class="support-title">WhatsApp Channel</span>
                    <span class="support-subtitle">Join for official updates</span>
                </div>
            </div>
            <div class="support-right">
                <i class="fa-solid fa-chevron-right"></i>
            </div>
        </div>

        <div class="support-item" onclick="openModal('submitTicketModal')">
            <div class="support-left">
                <div class="icon-box icon-ticket">
                    <i class="fa-solid fa-headset"></i>
                </div>
                <div class="support-text">
                    <span class="support-title">Live Chat</span>
                    <span class="support-subtitle">Submit a request to our team</span>
                </div>
            </div>
            <div class="support-right">
                <i class="fa-solid fa-pen-to-square"></i>
            </div>
        </div>

        <div class="support-item" onclick="openHistory()">
            <div class="support-left">
                <div class="icon-box icon-history">
                    <i class="fa-solid fa-clock-rotate-left"></i>
                </div>
                <div class="support-text">
                    <span class="support-title">My Tickets</span>
                    <span class="support-subtitle">View and reply to requests</span>
                </div>
            </div>
            <div class="support-right">
                <i class="fa-solid fa-chevron-right"></i>
            </div>
        </div>

    </div>

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

    <div class="modal-overlay" id="whatsappCopyModal">
        <div class="modal-content">
            <div class="modal-header">
                <span>WhatsApp Support</span>
                <span class="close-txt-btn" onclick="closeModal('whatsappCopyModal')">Close</span>
            </div>
            <div class="modal-body" style="text-align: center;">
                <p style="color:#fff; font-size: 15px; margin-bottom: 10px;">Please contact on this number:</p>
                <h2 style="color: #25D366; margin-bottom: 20px; letter-spacing: 1px;">+16396528088</h2>
                <button type="button" class="btn-wa" onclick="copyWhatsAppNumber()">Copy Number</button>
            </div>
        </div>
    </div>

    <div class="modal-overlay" id="submitTicketModal">
        <div class="modal-content">
            <div class="modal-header">
                <span>Submit a Ticket</span>
                <span class="close-txt-btn" onclick="closeModal('submitTicketModal')">Close</span>
            </div>
            <form class="modal-body" onsubmit="submitTicket(event)">
                <?php if (!$is_logged_in): ?>
                    <input type="text" name="phone" class="input-field guest-input" placeholder="Your Phone Number" required>
                    <input type="text" name="uid" class="input-field guest-input" placeholder="Your UID" required>
                <?php endif; ?>
                <input type="text" name="subject" class="input-field" placeholder="Subject" required>
                <textarea name="message" class="input-field" placeholder="Describe your issue in detail..." required></textarea>
                <button type="submit" class="btn-main">Submit Request</button>
            </form>
        </div>
    </div>

    <div class="modal-overlay" id="authHistoryModal">
        <div class="modal-content">
            <div class="modal-header">
                <span>Check History</span>
                <span class="close-txt-btn" onclick="closeModal('authHistoryModal')">Close</span>
            </div>
            <form class="modal-body" onsubmit="saveGuestAuth(event)">
                <p style="font-size:13px; color:#a0938a; text-align:center;">Enter your details to view past tickets.</p>
                <input type="text" id="histPhone" class="input-field" placeholder="Your Phone Number" required>
                <input type="text" id="histUid" class="input-field" placeholder="Your UID" required>
                <button type="submit" class="btn-main">View Tickets</button>
            </form>
        </div>
    </div>

    <div class="modal-overlay" id="historyModal">
        <div class="modal-content">
            <div class="modal-header">
                <span>My Tickets</span>
                <span class="close-txt-btn" onclick="closeModal('historyModal')">Close</span>
            </div>
            <div class="modal-body" id="ticketList" style="padding-top: 10px;">
                </div>
        </div>
    </div>

    <div class="modal-overlay" id="viewTicketModal">
        <div class="modal-content" style="height: 85vh;">
            <div class="modal-header">
                <span id="vtTitle">Ticket Details</span>
                <span class="close-txt-btn" onclick="closeModal('viewTicketModal'); openHistory();">Back</span>
            </div>
            <div class="modal-body" style="flex:1; overflow:hidden; padding-bottom:10px;">
                
                <div class="chat-box" id="chatContainer">
                    </div>

                <form class="reply-box" id="replyForm" onsubmit="replyTicket(event)" style="display:none;">
                    <input type="hidden" id="replyTicketId" name="ticket_id">
                    <input type="text" name="message" class="input-field" placeholder="Type a reply..." required autocomplete="off">
                    <button type="submit" class="reply-btn"><i class="fa-solid fa-paper-plane"></i></button>
                </form>
                <div id="resolvedNotice" style="display:none; text-align:center; color:#00e676; font-size:13px; font-weight:bold;">
                    <i class="fa-solid fa-check-circle"></i> Ticket is Resolved
                </div>

            </div>
        </div>
    </div>

    <div id="customToast" class="custom-toast"></div>

    <script>
        const isLogged = <?php echo $is_logged_in ? 'true' : 'false'; ?>;

        // Auto-fill inputs if guest has localStorage saved
        if (!isLogged) {
            let gp = localStorage.getItem('guestPhone');
            let gu = localStorage.getItem('guestUid');
            if(gp && gu) {
                document.querySelectorAll('input[name="phone"]').forEach(i => i.value = gp);
                document.querySelectorAll('input[name="uid"]').forEach(i => i.value = gu);
            }
        }

        // WhatsApp Handler (Updated to attempt opening the app from WebViews)
        function handleWhatsAppContact() {
            var phoneNumber = "16396528088"; 
            var isAndroidWebView = /wv/.test(navigator.userAgent) || (/Android/.test(navigator.userAgent) && /Version\//.test(navigator.userAgent));

            if (isAndroidWebView) {
                // Try to trigger the intent to open the app directly from within a WebView
                window.location.href = "https://api.whatsapp.com/send/?phone=" + phoneNumber + "&text&type=phone_number&app_absent=0";
                
                // Set a timeout to show the copy modal fallback in case the intent is blocked/fails
                setTimeout(function() { 
                    openModal('whatsappCopyModal'); 
                }, 1000);
            } else {
                // Normal browsers / iOS
                window.location.href = "https://api.whatsapp.com/send/?phone=" + phoneNumber + "&text&type=phone_number&app_absent=0";
            }
        }

        // Function to copy WhatsApp Number to clipboard
        function copyWhatsAppNumber() {
            var textToCopy = "+16396528088";
            
            if (navigator.clipboard && window.isSecureContext) {
                // Navigator clipboard api method
                navigator.clipboard.writeText(textToCopy).then(function() {
                    showToast("Number copied successfully!");
                    closeModal('whatsappCopyModal');
                });
            } else {
                // Textarea fallback
                let textArea = document.createElement("textarea");
                textArea.value = textToCopy;
                textArea.style.position = "fixed";
                textArea.style.left = "-999999px";
                textArea.style.top = "-999999px";
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();
                try {
                    document.execCommand('copy');
                    showToast("Number copied successfully!");
                    closeModal('whatsappCopyModal');
                } catch (error) {
                    showToast("Failed to copy. Please copy manually.");
                }
                textArea.remove();
            }
        }

        // Modals
        function openModal(id) { document.getElementById(id).classList.add('active'); }
        function closeModal(id) { document.getElementById(id).classList.remove('active'); }

        // Toast
        function showToast(message) {
            if (!message) return;
            var toast = document.getElementById("customToast");
            if(window.toastTimeout) { clearTimeout(window.toastTimeout); toast.className = "custom-toast"; }
            toast.innerText = message;
            void toast.offsetWidth; 
            toast.className = "custom-toast show";
            window.toastTimeout = setTimeout(() => { toast.className = toast.className.replace("show", ""); }, 1500); 
        }

        // Generic AJAX caller
        async function doAjax(formData) {
            // Append credentials for guests
            if(!isLogged) {
                let gp = localStorage.getItem('guestPhone');
                let gu = localStorage.getItem('guestUid');
                if(!formData.has('phone') && gp) formData.append('phone', gp);
                if(!formData.has('uid') && gu) formData.append('uid', gu);
            }
            try {
                const response = await fetch('', { method: 'POST', body: formData });
                return await response.json();
            } catch (e) {
                return { success: false, message: "Network Error" };
            }
        }

        // Submit Ticket
        async function submitTicket(e) {
            e.preventDefault();
            const fd = new FormData(e.target);
            fd.append('ajax_action', 'submit_ticket');
            
            // Save guest details locally to skip asking them later
            if(!isLogged) {
                localStorage.setItem('guestPhone', fd.get('phone'));
                localStorage.setItem('guestUid', fd.get('uid'));
            }

            const res = await doAjax(fd);
            if(res.success) {
                showToast("Ticket submitted successfully");
                closeModal('submitTicketModal');
                e.target.reset();
                if(!isLogged) {
                    // Restore inputs
                    document.querySelectorAll('input[name="phone"]').forEach(i => i.value = localStorage.getItem('guestPhone'));
                    document.querySelectorAll('input[name="uid"]').forEach(i => i.value = localStorage.getItem('guestUid'));
                }
            } else {
                showToast(res.message);
            }
        }

        // Auth for history (Guest)
        function saveGuestAuth(e) {
            e.preventDefault();
            localStorage.setItem('guestPhone', document.getElementById('histPhone').value);
            localStorage.setItem('guestUid', document.getElementById('histUid').value);
            closeModal('authHistoryModal');
            openHistory();
        }

        // Open History List
        async function openHistory() {
            if(!isLogged && (!localStorage.getItem('guestPhone') || !localStorage.getItem('guestUid'))) {
                openModal('authHistoryModal');
                return;
            }
            
            openModal('historyModal');
            document.getElementById('ticketList').innerHTML = '<div style="text-align:center;color:#a0938a;"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div>';
            
            const fd = new FormData();
            fd.append('ajax_action', 'get_history');
            const res = await doAjax(fd);
            
            const list = document.getElementById('ticketList');
            if(res.success) {
                if(res.data.length === 0) {
                    list.innerHTML = '<div style="text-align:center;color:#a0938a;padding:20px;">No tickets found.</div>';
                    return;
                }
                
                let html = '';
                res.data.forEach(t => {
                    let badgeClass = t.status === 'Open' ? 'bg-open' : (t.status === 'Resolved' ? 'bg-res' : 'bg-prog');
                    html += `
                        <div class="ticket-list-item" onclick="openTicket(${t.id})">
                            <div class="t-head">
                                <span class="t-subj">#${t.id} - ${t.subject}</span>
                                <span class="badge ${badgeClass}">${t.status}</span>
                            </div>
                            <div class="t-date">${t.created_at}</div>
                        </div>
                    `;
                });
                list.innerHTML = html;
            } else {
                list.innerHTML = `<div style="text-align:center;color:#ff453a;">${res.message}</div>`;
                if(res.message.includes('required') && !isLogged) {
                    localStorage.removeItem('guestPhone');
                    localStorage.removeItem('guestUid');
                    closeModal('historyModal');
                    openModal('authHistoryModal');
                }
            }
        }

        function formatTime(timestamp) {
            const d = new Date(timestamp);
            return d.toLocaleString();
        }

        // Open Single Ticket
        async function openTicket(id) {
            closeModal('historyModal');
            openModal('viewTicketModal');
            document.getElementById('replyTicketId').value = id;
            document.getElementById('vtTitle').innerText = "Ticket #" + id;
            
            const chat = document.getElementById('chatContainer');
            chat.innerHTML = '<div style="text-align:center;color:#a0938a; margin-top:20px;"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div>';
            
            document.getElementById('replyForm').style.display = 'none';
            document.getElementById('resolvedNotice').style.display = 'none';

            const fd = new FormData();
            fd.append('ajax_action', 'get_ticket');
            fd.append('ticket_id', id);

            const res = await doAjax(fd);
            if(res.success) {
                let t = res.ticket;
                
                // Original Message
                let html = `
                    <div class="chat-bubble chat-user">
                        <strong>${t.subject}</strong><br><br>
                        ${t.message}
                        <span class="chat-time">${formatTime(t.created_at)}</span>
                    </div>
                `;

                // Replies
                res.replies.forEach(r => {
                    let bubbleClass = r.sender_type === 'User' ? 'chat-user' : 'chat-admin';
                    html += `
                        <div class="chat-bubble ${bubbleClass}">
                            ${r.message}
                            <span class="chat-time">${r.sender_type} • ${formatTime(r.created_at)}</span>
                        </div>
                    `;
                });

                chat.innerHTML = html;
                chat.scrollTop = chat.scrollHeight; // Scroll to bottom

                // Toggle Reply Box
                if(t.status === 'Resolved') {
                    document.getElementById('resolvedNotice').style.display = 'block';
                } else {
                    document.getElementById('replyForm').style.display = 'flex';
                }
            } else {
                chat.innerHTML = `<div style="text-align:center;color:#ff453a;margin-top:20px;">${res.message}</div>`;
            }
        }

        // Submit Reply
        async function replyTicket(e) {
            e.preventDefault();
            const fd = new FormData(e.target);
            fd.append('ajax_action', 'reply_ticket');
            
            const btn = e.target.querySelector('button');
            btn.disabled = true;

            const res = await doAjax(fd);
            if(res.success) {
                e.target.reset();
                openTicket(fd.get('ticket_id')); // reload ticket
            } else {
                showToast(res.message);
            }
            btn.disabled = false;
        }
    </script>
</body>
</html>