<?php
session_start();
require_once 'db.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_role = $_SESSION['role'] ?? 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    if (isset($_POST['action'])) {
        $db1 = getDB1Connection();
        
        switch ($_POST['action']) {
            case 'send_reply':
                $ticket_id = intval($_POST['ticket_id']);
                $message = trim($_POST['message']);
                
                if (!empty($message)) {
                    $stmt = $db1->prepare("INSERT INTO ticket_responses (ticket_id, user_id, response, is_staff) VALUES (?, ?, ?, ?)");
                    $success = $stmt->execute([$ticket_id, $_SESSION['user_id'], $message, $user_role]);
                    
                    if ($success) {
                        $ticket_stmt = $db1->prepare("SELECT u.email, u.username, st.subject FROM support_tickets st JOIN utilisateurs u ON st.user_id = u.id WHERE st.id = ?");
                        $ticket_stmt->execute([$ticket_id]);
                        $ticket_info = $ticket_stmt->fetch(PDO::FETCH_ASSOC);
                        
                        if ($ticket_info) {
                            $to = $ticket_info['email'];
                            $subject = "Response to your ticket: " . $ticket_info['subject'];
                            $email_message = "Hello " . $ticket_info['username'] . ",\n\n";
                            $email_message .= "You have received a new response to your support ticket #" . $ticket_id . ".\n\n";
                            $email_message .= "Response: " . $message . "\n\n";
                            $email_message .= "Response to the support on https://idsma.imators.com/dashboard. Best regards,\nImators Support Team";
                            
                            $headers = "From: no-reply@imators.com\r\n";
                            $headers .= "X-Mailer: PHP/" . phpversion();
                            
                            mail($to, $subject, $email_message, $headers);
                        }
                        
                        echo json_encode(['success' => true]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Failed to send reply']);
                    }
                }
                break;
                
            case 'update_status':
                $ticket_id = intval($_POST['ticket_id']);
                $status = $_POST['status'];
                
                $stmt = $db1->prepare("UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE id = ?");
                $success = $stmt->execute([$status, $ticket_id]);
                
                echo json_encode(['success' => $success]);
                break;
                
            case 'get_tickets':
                $tickets = [];
                $query = "SELECT st.*, u.username, u.email FROM support_tickets st 
                         JOIN utilisateurs u ON st.user_id = u.id 
                         ORDER BY st.created_at DESC";
                
                $stmt = $db1->query($query);
                while ($ticket = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    $ticket['created_at'] = date('M d, Y H:i', strtotime($ticket['created_at']));
                    $tickets[] = $ticket;
                }
                
                echo json_encode($tickets);
                break;
                
            case 'get_conversation':
                $ticket_id = intval($_POST['ticket_id']);
                
                $ticket_stmt = $db1->prepare("SELECT st.*, u.username, u.email FROM support_tickets st JOIN utilisateurs u ON st.user_id = u.id WHERE st.id = ?");
                $ticket_stmt->execute([$ticket_id]);
                $ticket = $ticket_stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($ticket) {
                    $ticket['created_at'] = date('M d, Y H:i', strtotime($ticket['created_at']));
                    
                    $responses_stmt = $db1->prepare("SELECT tr.*, u.username FROM ticket_responses tr JOIN utilisateurs u ON tr.user_id = u.id WHERE tr.ticket_id = ? ORDER BY tr.created_at ASC");
                    $responses_stmt->execute([$ticket_id]);
                    $responses = $responses_stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    foreach ($responses as &$response) {
                        $response['created_at'] = date('M d, Y H:i', strtotime($response['created_at']));
                    }
                    
                    echo json_encode(['ticket' => $ticket, 'responses' => $responses]);
                } else {
                    echo json_encode(['error' => 'Ticket not found']);
                }
                break;
        }
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Support Tickets - Imators</title>
    <link href="https://cdn.imators.com/logo.png" rel="icon" type="image/png" />
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    fontFamily: {
                        'inter': ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        body { font-family: 'Inter', sans-serif; }
    </style>
</head>
<body class="bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100">
    
    <div class="lg:hidden">
        <div id="mobile-header" class="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-3">
                    <button id="mobile-menu-toggle" class="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
                        </svg>
                    </button>
                    <img src="https://cdn.imators.com/logo.png" alt="Imators" class="h-6 w-auto">
                    <span class="font-semibold text-sm">Support</span>
                </div>
                <div class="flex items-center space-x-2">
                    <button id="theme-toggle-mobile" class="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
                        <svg class="w-4 h-4 dark:hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"></path>
                        </svg>
                        <svg class="w-4 h-4 hidden dark:block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path>
                        </svg>
                    </button>
                    <a href="index.php" class="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                        </svg>
                    </a>
                </div>
            </div>
        </div>

        <div id="mobile-sidebar" class="fixed inset-0 z-50 lg:hidden hidden">
            <div class="fixed inset-0 bg-black/50" id="mobile-overlay"></div>
            <div class="fixed left-0 top-0 h-full w-80 bg-white dark:bg-gray-800 transform -translate-x-full transition-transform duration-300" id="mobile-sidebar-content">
                <div class="p-4 border-b border-gray-200 dark:border-gray-700">
                    <div class="flex items-center justify-between">
                        <h2 class="font-semibold">Tickets</h2>
                        <button id="mobile-sidebar-close" class="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>
                    <div class="flex flex-wrap gap-2 mt-4">
                        <button class="status-filter-mobile active px-3 py-1 text-xs rounded-full bg-black dark:bg-white text-white dark:text-black" data-status="all">All</button>
                        <button class="status-filter-mobile px-3 py-1 text-xs rounded-full bg-gray-100 dark:bg-gray-700" data-status="open">Open</button>
                        <button class="status-filter-mobile px-3 py-1 text-xs rounded-full bg-gray-100 dark:bg-gray-700" data-status="in_progress">In Progress</button>
                        <button class="status-filter-mobile px-3 py-1 text-xs rounded-full bg-gray-100 dark:bg-gray-700" data-status="resolved">Resolved</button>
                    </div>
                </div>
                <div class="flex-1 overflow-y-auto" id="tickets-list-mobile"></div>
            </div>
        </div>

        <div class="p-4">
            <div id="mobile-conversation">
                <div class="text-center py-12">
                    <div class="w-16 h-16 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mx-auto mb-4">
                        <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                        </svg>
                    </div>
                    <h3 class="text-lg font-medium mb-2">Select a ticket</h3>
                    <p class="text-gray-500 dark:text-gray-400 text-sm">Tap the menu button to choose a ticket</p>
                </div>
            </div>

            <div id="mobile-ticket-header" class="bg-white dark:bg-gray-800 rounded-lg p-4 mb-4 hidden">
                <div class="flex items-center justify-between mb-2">
                    <h3 class="font-semibold text-sm" id="mobile-ticket-subject"></h3>
                    <select id="mobile-ticket-status" class="text-xs px-2 py-1 rounded border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700">
                        <option value="open">Open</option>
                        <option value="in_progress">In Progress</option>
                        <option value="resolved">Resolved</option>
                        <option value="closed">Closed</option>
                    </select>
                </div>
                <p class="text-xs text-gray-500 dark:text-gray-400" id="mobile-ticket-info"></p>
            </div>

            <div id="mobile-messages" class="space-y-4 mb-4"></div>

            <div id="mobile-reply-section" class="bg-white dark:bg-gray-800 rounded-lg p-4 hidden">
                <div class="mb-4">
                    <p class="text-xs font-medium text-gray-700 dark:text-gray-300 mb-3">Quick replies:</p>
                    <div class="grid grid-cols-1 gap-2">
                        <button class="preset-phrase-mobile text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">Thank you for contacting Imators Support</button>
                        <button class="preset-phrase-mobile text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">I'm looking into this issue for you</button>
                        <button class="preset-phrase-mobile text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">Could you provide more details?</button>
                        <button class="preset-phrase-mobile text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">This issue has been resolved</button>
                        <button class="preset-phrase-mobile text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">Please try clearing your cache and reloading</button>
                        <button class="preset-phrase-mobile text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">I'll escalate this to our development team</button>
                    </div>
                </div>
                <div class="space-y-3">
                    <textarea id="mobile-reply-input" rows="3" 
                             class="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 resize-none focus:outline-none focus:ring-2 focus:ring-blue-500"
                             placeholder="Type your response..."></textarea>
                    <button id="mobile-send-reply" 
                            class="w-full py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors">
                        Send Reply
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="hidden lg:flex h-screen">
        <aside class="w-80 bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex flex-col">
            <div class="p-6 border-b border-gray-200 dark:border-gray-700">
                <div class="flex items-center justify-between mb-6">
                    <div class="flex items-center space-x-3">
                        <img src="https://cdn.imators.com/logo.png" alt="Imators" class="h-8 w-auto">
                        <div>
                            <h1 class="text-lg font-semibold">Support</h1>
                            <p class="text-xs text-gray-500 dark:text-gray-400">Ticket management</p>
                        </div>
                    </div>
                    <div class="flex items-center space-x-2">
                        <button id="theme-toggle" class="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                            <svg class="w-4 h-4 dark:hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"></path>
                            </svg>
                            <svg class="w-4 h-4 hidden dark:block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path>
                            </svg>
                        </button>
                        <a href="index.php" class="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                            </svg>
                        </a>
                    </div>
                </div>
                
                <div class="flex flex-wrap gap-2 mb-4">
                    <button class="status-filter active px-3 py-1.5 text-xs rounded-full bg-black dark:bg-white text-white dark:text-black" data-status="all">All</button>
                    <button class="status-filter px-3 py-1.5 text-xs rounded-full bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700" data-status="open">Open</button>
                    <button class="status-filter px-3 py-1.5 text-xs rounded-full bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700" data-status="in_progress">In Progress</button>
                    <button class="status-filter px-3 py-1.5 text-xs rounded-full bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700" data-status="resolved">Resolved</button>
                </div>
            </div>
            
            <div class="flex-1 overflow-y-auto" id="tickets-list">
                <div class="p-6 text-center text-gray-500">
                    <div class="w-6 h-6 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin mx-auto mb-2"></div>
                    <p class="text-sm">Loading tickets...</p>
                </div>
            </div>
        </aside>

        <main class="flex-1 flex flex-col">
            <header class="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 p-6">
                <div class="flex items-center justify-between">
                    <div class="flex-1">
                        <h2 class="text-xl font-semibold" id="ticket-subject">Select a ticket</h2>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mt-1" id="ticket-info">Choose a ticket from the sidebar to view details</p>
                    </div>
                    <div class="flex items-center space-x-3" id="ticket-actions" style="display: none;">
                        <select id="ticket-status" class="px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="open">Open</option>
                            <option value="in_progress">In Progress</option>
                            <option value="resolved">Resolved</option>
                            <option value="closed">Closed</option>
                        </select>
                        <button id="refresh-tickets" class="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                            </svg>
                        </button>
                    </div>
                </div>
            </header>

            <div class="flex-1 overflow-y-auto p-6" id="messages-container">
                <div class="text-center py-20">
                    <div class="w-16 h-16 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mx-auto mb-4">
                        <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                        </svg>
                    </div>
                    <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">Select a ticket</h3>
                    <p class="text-gray-500 dark:text-gray-400">Choose a ticket from the sidebar to start viewing the conversation</p>
                </div>
            </div>

            <div class="bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 p-6" id="reply-section" style="display: none;">
                <div class="space-y-4">
                    <div>
                        <p class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Quick replies:</p>
                        <div class="grid grid-cols-2 gap-2">
                            <button class="preset-phrase text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">Thank you for contacting Imators Support</button>
                            <button class="preset-phrase text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">I'm looking into this issue for you</button>
                            <button class="preset-phrase text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">Could you provide more details?</button>
                            <button class="preset-phrase text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">This issue has been resolved</button>
                            <button class="preset-phrase text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">Please try clearing your cache and reloading</button>
                            <button class="preset-phrase text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">I'll escalate this to our development team</button>
                            <button class="preset-phrase text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">Is there anything else I can help with?</button>
                            <button class="preset-phrase text-left px-3 py-2 text-sm bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors">We'll keep you updated on this issue</button>
                        </div>
                    </div>
                    
                    <div class="flex space-x-3">
                        <input type="text" id="reply-input" 
                               class="flex-1 px-4 py-3 rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 placeholder-gray-400"
                               placeholder="Type your response...">
                        <button id="send-reply" 
                                class="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors flex items-center space-x-2 font-medium">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
                            </svg>
                            <span>Send</span>
                        </button>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        let currentTicketId = null;
        let tickets = [];
        let isMobile = window.innerWidth < 1024;

        document.addEventListener('DOMContentLoaded', function() {
            loadTickets();
            setupEventListeners();
            setupThemeToggle();
            setupMobileHandlers();
        });

        function setupMobileHandlers() {
            const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
            const mobileSidebar = document.getElementById('mobile-sidebar');
            const mobileSidebarContent = document.getElementById('mobile-sidebar-content');
            const mobileOverlay = document.getElementById('mobile-overlay');
            const mobileSidebarClose = document.getElementById('mobile-sidebar-close');

            function openMobileSidebar() {
                mobileSidebar.classList.remove('hidden');
                setTimeout(() => {
                    mobileSidebarContent.classList.remove('-translate-x-full');
                }, 10);
            }

            function closeMobileSidebar() {
                mobileSidebarContent.classList.add('-translate-x-full');
                setTimeout(() => {
                    mobileSidebar.classList.add('hidden');
                }, 300);
            }

            mobileMenuToggle.addEventListener('click', openMobileSidebar);
            mobileOverlay.addEventListener('click', closeMobileSidebar);
            mobileSidebarClose.addEventListener('click', closeMobileSidebar);

            document.querySelectorAll('.status-filter-mobile').forEach(button => {
                button.addEventListener('click', function() {
                    document.querySelectorAll('.status-filter-mobile').forEach(b => {
                        b.classList.remove('active', 'bg-black', 'dark:bg-white', 'text-white', 'dark:text-black');
                        b.classList.add('bg-gray-100', 'dark:bg-gray-700');
                    });
                    
                    this.classList.add('active', 'bg-black', 'dark:bg-white', 'text-white', 'dark:text-black');
                    this.classList.remove('bg-gray-100', 'dark:bg-gray-700');
                    
                    filterTickets(this.dataset.status);
                });
            });

            document.querySelectorAll('.preset-phrase-mobile').forEach(button => {
                button.addEventListener('click', function() {
                    const input = document.getElementById('mobile-reply-input');
                    if (input.value.trim()) {
                        input.value += ' ' + this.textContent.trim();
                    } else {
                        input.value = this.textContent.trim();
                    }
                    input.focus();
                });
            });

            document.getElementById('mobile-send-reply').addEventListener('click', function() {
                const message = document.getElementById('mobile-reply-input').value.trim();
                if (!message || !currentTicketId) return;

                const sendButton = this;
                const originalContent = sendButton.innerHTML;
                sendButton.disabled = true;
                sendButton.innerHTML = 'Sending...';

                fetch('', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `action=send_reply&ticket_id=${currentTicketId}&message=${encodeURIComponent(message)}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('mobile-reply-input').value = '';
                        showTicketConversationMobile(currentTicketId);
                    } else {
                        alert('Error sending reply. Please try again.');
                    }
                })
                .catch(error => {
                    console.error('Error sending reply:', error);
                    alert('Error sending reply. Please try again.');
                })
                .finally(() => {
                    sendButton.disabled = false;
                    sendButton.innerHTML = originalContent;
                });
            });

            document.getElementById('mobile-ticket-status').addEventListener('change', function() {
                const newStatus = this.value;
                if (!currentTicketId) return;

                fetch('', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `action=update_status&ticket_id=${currentTicketId}&status=${newStatus}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        loadTickets();
                    } else {
                        alert('Error updating status. Please try again.');
                    }
                })
                .catch(error => {
                    console.error('Error updating status:', error);
                    alert('Error updating status. Please try again.');
                });
            });
        }

        function setupEventListeners() {
            document.getElementById('refresh-tickets').addEventListener('click', loadTickets);
            document.getElementById('send-reply').addEventListener('click', sendReply);
            document.getElementById('ticket-status').addEventListener('change', updateTicketStatus);
            
            document.getElementById('reply-input').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    sendReply();
                }
            });

            document.querySelectorAll('.preset-phrase').forEach(button => {
                button.addEventListener('click', function() {
                    const input = document.getElementById('reply-input');
                    if (input.value.trim()) {
                        input.value += ' ' + this.textContent.trim();
                    } else {
                        input.value = this.textContent.trim();
                    }
                    input.focus();
                });
            });

            document.querySelectorAll('.status-filter').forEach(button => {
                button.addEventListener('click', function() {
                    document.querySelectorAll('.status-filter').forEach(b => {
                        b.classList.remove('active', 'bg-black', 'dark:bg-white', 'text-white', 'dark:text-black');
                        b.classList.add('bg-gray-100', 'dark:bg-gray-800');
                    });
                    
                    this.classList.add('active', 'bg-black', 'dark:bg-white', 'text-white', 'dark:text-black');
                    this.classList.remove('bg-gray-100', 'dark:bg-gray-800');
                    
                    filterTickets(this.dataset.status);
                });
            });
        }

        function setupThemeToggle() {
            const themeToggle = document.getElementById('theme-toggle');
            const themeToggleMobile = document.getElementById('theme-toggle-mobile');
            const html = document.documentElement;
            
            if (localStorage.getItem('theme') === 'dark') {
                html.classList.add('dark');
            }
            
            function toggleTheme() {
                html.classList.toggle('dark');
                localStorage.setItem('theme', html.classList.contains('dark') ? 'dark' : 'light');
            }
            
            if (themeToggle) themeToggle.addEventListener('click', toggleTheme);
            if (themeToggleMobile) themeToggleMobile.addEventListener('click', toggleTheme);
        }

        function loadTickets() {
            fetch('', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'action=get_tickets'
            })
            .then(response => response.json())
            .then(data => {
                tickets = data;
                displayTickets(tickets);
                displayTicketsMobile(tickets);
            })
            .catch(error => {
                console.error('Error loading tickets:', error);
                const errorMessage = '<div class="p-6 text-center text-red-500 text-sm">Error loading tickets</div>';
                document.getElementById('tickets-list').innerHTML = errorMessage;
                document.getElementById('tickets-list-mobile').innerHTML = errorMessage;
            });
        }

        function displayTickets(ticketsToShow) {
            const container = document.getElementById('tickets-list');
            
            if (ticketsToShow.length === 0) {
                container.innerHTML = '<div class="p-6 text-center text-gray-500 text-sm">No tickets found</div>';
                return;
            }

            container.innerHTML = '';
            
            ticketsToShow.forEach(ticket => {
                const statusColors = {
                    'open': 'bg-red-500',
                    'in_progress': 'bg-yellow-500', 
                    'resolved': 'bg-green-500',
                    'closed': 'bg-gray-500'
                };

                const ticketElement = document.createElement('div');
                ticketElement.className = 'ticket-item p-4 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer transition-colors border-l-4 border-transparent';
                ticketElement.dataset.ticketId = ticket.id;
                
                ticketElement.innerHTML = `
                    <div class="flex items-start space-x-3">
                        <div class="w-2 h-2 rounded-full mt-2 flex-shrink-0 ${statusColors[ticket.status] || 'bg-gray-500'}"></div>
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center justify-between mb-1">
                                <h3 class="font-medium text-sm truncate text-gray-900 dark:text-gray-100">${escapeHtml(ticket.subject)}</h3>
                                <span class="text-xs text-gray-500 dark:text-gray-400 ml-2">#${ticket.id}</span>
                            </div>
                            <p class="text-xs text-gray-600 dark:text-gray-400 truncate mb-2">${escapeHtml(ticket.username)}</p>
                            <div class="flex items-center justify-between">
                                <span class="inline-flex items-center px-2 py-1 text-xs rounded-full bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 capitalize">
                                    ${ticket.priority}
                                </span>
                                <span class="text-xs text-gray-500 dark:text-gray-400">${ticket.created_at}</span>
                            </div>
                        </div>
                    </div>
                `;
                
                ticketElement.addEventListener('click', () => showTicketConversation(ticket.id));
                container.appendChild(ticketElement);
            });
        }

        function displayTicketsMobile(ticketsToShow) {
            const container = document.getElementById('tickets-list-mobile');
            
            if (ticketsToShow.length === 0) {
                container.innerHTML = '<div class="p-4 text-center text-gray-500 text-sm">No tickets found</div>';
                return;
            }

            container.innerHTML = '';
            
            ticketsToShow.forEach(ticket => {
                const statusColors = {
                    'open': 'bg-red-500',
                    'in_progress': 'bg-yellow-500', 
                    'resolved': 'bg-green-500',
                    'closed': 'bg-gray-500'
                };

                const ticketElement = document.createElement('div');
                ticketElement.className = 'p-4 border-b border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer';
                ticketElement.dataset.ticketId = ticket.id;
                
                ticketElement.innerHTML = `
                    <div class="flex items-start space-x-3">
                        <div class="w-2 h-2 rounded-full mt-2 flex-shrink-0 ${statusColors[ticket.status] || 'bg-gray-500'}"></div>
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center justify-between mb-1">
                                <h3 class="font-medium text-sm truncate">${escapeHtml(ticket.subject)}</h3>
                                <span class="text-xs text-gray-500">#${ticket.id}</span>
                            </div>
                            <p class="text-xs text-gray-600 dark:text-gray-400 truncate mb-2">${escapeHtml(ticket.username)}</p>
                            <div class="flex items-center justify-between">
                                <span class="text-xs px-2 py-1 rounded-full bg-gray-100 dark:bg-gray-700 capitalize">
                                    ${ticket.priority}
                                </span>
                                <span class="text-xs text-gray-500">${ticket.created_at}</span>
                            </div>
                        </div>
                    </div>
                `;
                
                ticketElement.addEventListener('click', () => {
                    showTicketConversationMobile(ticket.id);
                    document.getElementById('mobile-sidebar-content').classList.add('-translate-x-full');
                    setTimeout(() => {
                        document.getElementById('mobile-sidebar').classList.add('hidden');
                    }, 300);
                });
                container.appendChild(ticketElement);
            });
        }

        function filterTickets(status) {
            if (status === 'all') {
                displayTickets(tickets);
                displayTicketsMobile(tickets);
            } else {
                const filtered = tickets.filter(ticket => ticket.status === status);
                displayTickets(filtered);
                displayTicketsMobile(filtered);
            }
        }

        function showTicketConversation(ticketId) {
            currentTicketId = ticketId;
            
            document.querySelectorAll('.ticket-item').forEach(item => {
                item.classList.remove('bg-blue-50', 'dark:bg-blue-950', 'border-l-4', 'border-blue-500');
                item.classList.add('border-transparent');
            });
            
            const selectedItem = document.querySelector(`[data-ticket-id="${ticketId}"]`);
            if (selectedItem) {
                selectedItem.classList.add('bg-blue-50', 'dark:bg-blue-950', 'border-l-4', 'border-blue-500');
                selectedItem.classList.remove('border-transparent');
            }

            document.getElementById('messages-container').innerHTML = '<div class="text-center py-8"><div class="w-6 h-6 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin mx-auto"></div></div>';
            document.getElementById('reply-section').style.display = 'block';
            document.getElementById('ticket-actions').style.display = 'flex';

            fetch('', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=get_conversation&ticket_id=${ticketId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.ticket) {
                    document.getElementById('ticket-subject').textContent = data.ticket.subject;
                    document.getElementById('ticket-info').textContent = `Ticket #${data.ticket.id} by ${data.ticket.username} (${data.ticket.email}) - ${data.ticket.created_at}`;
                    document.getElementById('ticket-status').value = data.ticket.status;
                    
                    displayMessages(data.ticket, data.responses);
                }
            })
            .catch(error => {
                console.error('Error loading conversation:', error);
                document.getElementById('messages-container').innerHTML = '<div class="text-center py-8 text-red-500">Error loading conversation</div>';
            });
        }

        function showTicketConversationMobile(ticketId) {
            currentTicketId = ticketId;

            document.getElementById('mobile-ticket-header').classList.remove('hidden');
            document.getElementById('mobile-reply-section').classList.remove('hidden');
            document.getElementById('mobile-conversation').innerHTML = '<div class="text-center py-8"><div class="w-6 h-6 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin mx-auto"></div></div>';

            fetch('', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=get_conversation&ticket_id=${ticketId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.ticket) {
                    document.getElementById('mobile-ticket-subject').textContent = data.ticket.subject;
                    document.getElementById('mobile-ticket-info').textContent = `#${data.ticket.id} by ${data.ticket.username} - ${data.ticket.created_at}`;
                    document.getElementById('mobile-ticket-status').value = data.ticket.status;
                    
                    displayMessagesMobile(data.ticket, data.responses);
                }
            })
            .catch(error => {
                console.error('Error loading conversation:', error);
                document.getElementById('mobile-conversation').innerHTML = '<div class="text-center py-8 text-red-500">Error loading conversation</div>';
            });
        }

        function displayMessages(ticket, responses) {
            const container = document.getElementById('messages-container');
            container.innerHTML = '';

            const initialMessage = document.createElement('div');
            initialMessage.className = 'max-w-4xl rounded-2xl p-4 mb-4 bg-gray-50 dark:bg-gray-800';
            initialMessage.innerHTML = `
                <div class="flex items-start space-x-3">
                    <div class="w-8 h-8 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center flex-shrink-0">
                        <span class="text-xs font-medium text-gray-700 dark:text-gray-300">${ticket.username.charAt(0).toUpperCase()}</span>
                    </div>
                    <div class="flex-1">
                        <div class="flex items-center space-x-2 mb-1">
                            <span class="font-medium text-sm text-gray-900 dark:text-gray-100">${escapeHtml(ticket.username)}</span>
                            <span class="text-xs text-gray-500 dark:text-gray-400">${ticket.created_at}</span>
                        </div>
                        <div class="text-gray-700 dark:text-gray-300 text-sm leading-relaxed">${escapeHtml(ticket.description)}</div>
                    </div>
                </div>
            `;
            container.appendChild(initialMessage);

            responses.forEach(response => {
                const messageElement = document.createElement('div');
                const isStaff = response.is_staff == 1;
                
                messageElement.className = `max-w-4xl rounded-2xl p-4 mb-4 ${isStaff ? 'bg-blue-50 dark:bg-blue-950 ml-8' : 'bg-gray-50 dark:bg-gray-800'}`;
                messageElement.innerHTML = `
                    <div class="flex items-start space-x-3">
                        <div class="w-8 h-8 rounded-full ${isStaff ? 'bg-blue-500' : 'bg-gray-300 dark:bg-gray-600'} flex items-center justify-center flex-shrink-0">
                            ${isStaff ? 
                                '<svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M12 14l9-5-9-5-9 5 9 5z"/><path d="M12 14l6.16-3.422a12.083 12.083 0 01.665 6.479A11.952 11.952 0 0012 20.055a11.952 11.952 0 00-6.824-2.998 12.078 12.078 0 01.665-6.479L12 14z"/></svg>' : 
                                `<span class="text-xs font-medium text-gray-700 dark:text-gray-300">${response.username.charAt(0).toUpperCase()}</span>`
                            }
                        </div>
                        <div class="flex-1">
                            <div class="flex items-center space-x-2 mb-1">
                                <span class="font-medium text-sm text-gray-900 dark:text-gray-100">${escapeHtml(response.username)}</span>
                                ${isStaff ? '<span class="text-xs bg-blue-100 dark:bg-blue-900 text-blue-600 dark:text-blue-400 px-2 py-0.5 rounded-full font-medium">Staff</span>' : ''}
                                <span class="text-xs text-gray-500 dark:text-gray-400">${response.created_at}</span>
                            </div>
                            <div class="text-gray-700 dark:text-gray-300 text-sm leading-relaxed">${escapeHtml(response.response)}</div>
                        </div>
                    </div>
                `;
                container.appendChild(messageElement);
            });

            container.scrollTop = container.scrollHeight;
        }

        function displayMessagesMobile(ticket, responses) {
            const container = document.getElementById('mobile-messages');
            container.innerHTML = '';

            const initialMessage = document.createElement('div');
            initialMessage.className = 'bg-white dark:bg-gray-800 rounded-lg p-4 mb-4';
            initialMessage.innerHTML = `
                <div class="flex items-start space-x-3">
                    <div class="w-8 h-8 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center flex-shrink-0">
                        <span class="text-xs font-medium">${ticket.username.charAt(0).toUpperCase()}</span>
                    </div>
                    <div class="flex-1">
                        <div class="flex items-center space-x-2 mb-1">
                            <span class="font-medium text-sm">${escapeHtml(ticket.username)}</span>
                            <span class="text-xs text-gray-500">${ticket.created_at}</span>
                        </div>
                        <div class="text-sm leading-relaxed">${escapeHtml(ticket.description)}</div>
                    </div>
                </div>
            `;
            container.appendChild(initialMessage);

            responses.forEach(response => {
                const messageElement = document.createElement('div');
                const isStaff = response.is_staff == 1;
                
                messageElement.className = 'bg-white dark:bg-gray-800 rounded-lg p-4 mb-4';
                messageElement.innerHTML = `
                    <div class="flex items-start space-x-3">
                        <div class="w-8 h-8 rounded-full ${isStaff ? 'bg-blue-500' : 'bg-gray-300 dark:bg-gray-600'} flex items-center justify-center flex-shrink-0">
                            ${isStaff ? 
                                '<svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M12 14l9-5-9-5-9 5 9 5z"/></svg>' : 
                                `<span class="text-xs font-medium">${response.username.charAt(0).toUpperCase()}</span>`
                            }
                        </div>
                        <div class="flex-1">
                            <div class="flex items-center space-x-2 mb-1">
                                <span class="font-medium text-sm">${escapeHtml(response.username)}</span>
                                ${isStaff ? '<span class="text-xs bg-blue-100 text-blue-600 px-2 py-0.5 rounded-full">Staff</span>' : ''}
                                <span class="text-xs text-gray-500">${response.created_at}</span>
                            </div>
                            <div class="text-sm leading-relaxed">${escapeHtml(response.response)}</div>
                        </div>
                    </div>
                `;
                container.appendChild(messageElement);
            });
        }

        function sendReply() {
            const message = document.getElementById('reply-input').value.trim();
            if (!message || !currentTicketId) return;

            const sendButton = document.getElementById('send-reply');
            const originalContent = sendButton.innerHTML;
            sendButton.disabled = true;
            sendButton.innerHTML = '<div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>';

            fetch('', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=send_reply&ticket_id=${currentTicketId}&message=${encodeURIComponent(message)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('reply-input').value = '';
                    showTicketConversation(currentTicketId);
                } else {
                    alert('Error sending reply. Please try again.');
                }
            })
            .catch(error => {
                console.error('Error sending reply:', error);
                alert('Error sending reply. Please try again.');
            })
            .finally(() => {
                sendButton.disabled = false;
                sendButton.innerHTML = originalContent;
            });
        }

        function updateTicketStatus() {
            const newStatus = document.getElementById('ticket-status').value;
            if (!currentTicketId) return;

            fetch('', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=update_status&ticket_id=${currentTicketId}&status=${newStatus}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadTickets();
                    showTicketConversation(currentTicketId);
                } else {
                    alert('Error updating status. Please try again.');
                }
            })
            .catch(error => {
                console.error('Error updating status:', error);
                alert('Error updating status. Please try again.');
            });
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>