<?php

require 'element/connection.php';

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


$my_id = $_SESSION['user_id'];

// Fetch user data
$user_query = mysqli_query($conn, "SELECT * FROM users WHERE user_id = '$my_id'");
$user_data = mysqli_fetch_assoc($user_query);

// Handle new ticket submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_ticket'])) {
    $subject = mysqli_real_escape_string($conn, $_POST['subject']);
    $category = mysqli_real_escape_string($conn, $_POST['category']);
    $priority = mysqli_real_escape_string($conn, $_POST['priority']);
    $message = mysqli_real_escape_string($conn, $_POST['message']);
    
    // Generate unique ticket ID
    $ticket_id = 'TKT' . time() . rand(100, 999);
    
    // Insert ticket
    $insert_query = "INSERT INTO support_tickets (ticket_id, user_id, subject, category, priority, status, created_at) 
                     VALUES ('$ticket_id', '$my_id', '$subject', '$category', '$priority', 'open', NOW())";
    
    if (mysqli_query($conn, $insert_query)) {
        $ticket_db_id = mysqli_insert_id($conn);
        
        // Insert first message
        $message_query = "INSERT INTO support_messages (ticket_id, sender_type, sender_id, message, status, created_at) 
                          VALUES ('$ticket_db_id', 'user', '$my_id', '$message', 'sent', NOW())";
        mysqli_query($conn, $message_query);
        $message_id = mysqli_insert_id($conn);
        
        // Handle file attachments
        if (!empty($_FILES['attachments']['name'][0])) {
            $upload_dir = '../uploads/support/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            foreach ($_FILES['attachments']['tmp_name'] as $key => $tmp_name) {
                if ($_FILES['attachments']['error'][$key] == 0) {
                    $file_name = time() . '_' . $_FILES['attachments']['name'][$key];
                    $file_path = $upload_dir . $file_name;
                    $file_size = $_FILES['attachments']['size'][$key];
                    $file_type = $_FILES['attachments']['type'][$key];
                    
                    if (move_uploaded_file($tmp_name, $file_path)) {
                        $attach_query = "INSERT INTO support_attachments (message_id, file_name, file_path, file_size, file_type) 
                                         VALUES ('$message_id', '$file_name', '$file_path', '$file_size', '$file_type')";
                        mysqli_query($conn, $attach_query);
                    }
                }
            }
        }
        
        $_SESSION['success_message'] = "Ticket created successfully! Ticket ID: $ticket_id";
        header("Location: help.php?ticket=" . $ticket_db_id);
        exit();
    } else {
        $error_message = "Failed to create ticket. Please try again.";
    }
}

// Handle reply to ticket
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_ticket'])) {
    $ticket_id = intval($_POST['ticket_id']);
    $message = mysqli_real_escape_string($conn, $_POST['message']);
    
    // Verify ticket belongs to user
    $check_query = "SELECT id, status FROM support_tickets WHERE id = '$ticket_id' AND user_id = '$my_id'";
    $check_result = mysqli_query($conn, $check_query);
    $ticket = mysqli_fetch_assoc($check_result);
    
    if ($ticket) {
        // Insert reply
        $reply_query = "INSERT INTO support_messages (ticket_id, sender_type, sender_id, message, status, created_at) 
                        VALUES ('$ticket_id', 'user', '$my_id', '$message', 'sent', NOW())";
        
        if (mysqli_query($conn, $reply_query)) {
            $message_id = mysqli_insert_id($conn);
            
            // Update ticket status if it was resolved/closed
            if (in_array($ticket['status'], ['resolved', 'closed'])) {
                mysqli_query($conn, "UPDATE support_tickets SET status = 'open', updated_at = NOW() WHERE id = '$ticket_id'");
            } else {
                mysqli_query($conn, "UPDATE support_tickets SET updated_at = NOW() WHERE id = '$ticket_id'");
            }
            
            // Handle attachments
            if (!empty($_FILES['attachments']['name'][0])) {
                $upload_dir = '../uploads/support/';
                foreach ($_FILES['attachments']['tmp_name'] as $key => $tmp_name) {
                    if ($_FILES['attachments']['error'][$key] == 0) {
                        $file_name = time() . '_' . $_FILES['attachments']['name'][$key];
                        $file_path = $upload_dir . $file_name;
                        $file_size = $_FILES['attachments']['size'][$key];
                        $file_type = $_FILES['attachments']['type'][$key];
                        
                        if (move_uploaded_file($tmp_name, $file_path)) {
                            $attach_query = "INSERT INTO support_attachments (message_id, file_name, file_path, file_size, file_type) 
                                             VALUES ('$message_id', '$file_name', '$file_path', '$file_size', '$file_type')";
                            mysqli_query($conn, $attach_query);
                        }
                    }
                }
            }
            
            $_SESSION['success_message'] = "Reply sent successfully!";
        } else {
            $error_message = "Failed to send reply.";
        }
    } else {
        $error_message = "Invalid ticket.";
    }
    
    header("Location: help.php?ticket=" . $ticket_id);
    exit();
}

// Get ticket ID from URL
$current_ticket = isset($_GET['ticket']) ? intval($_GET['ticket']) : 0;

// Fetch user's tickets
$tickets_query = "SELECT t.*, 
                         (SELECT COUNT(*) FROM support_messages WHERE ticket_id = t.id AND sender_type = 'admin' AND is_read = 0) as unread_admin,
                         (SELECT message FROM support_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_message,
                         (SELECT created_at FROM support_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_activity
                  FROM support_tickets t 
                  WHERE t.user_id = '$my_id' 
                  ORDER BY 
                    CASE t.priority 
                      WHEN 'urgent' THEN 1 
                      WHEN 'high' THEN 2 
                      WHEN 'medium' THEN 3 
                      WHEN 'low' THEN 4 
                    END,
                    t.updated_at DESC";
$tickets_result = mysqli_query($conn, $tickets_query);

// Fetch current ticket details if selected
$current_ticket_data = null;
$messages = [];
$last_message_id = 0;
$debug_info = [];

if ($current_ticket > 0) {
    // Check if ticket exists
    $ticket_check = mysqli_query($conn, "SELECT * FROM support_tickets WHERE id = '$current_ticket' AND user_id = '$my_id'");
    
    if (!$ticket_check) {
        $debug_info[] = "Ticket query failed: " . mysqli_error($conn);
    } else {
        $current_ticket_data = mysqli_fetch_assoc($ticket_check);
        
        if ($current_ticket_data) {
            $debug_info[] = "✓ Ticket found: " . $current_ticket_data['ticket_id'];
            
            // Mark admin messages as read
            $update_query = "UPDATE support_messages SET is_read = 1, read_at = NOW(), status = 'read' 
                             WHERE ticket_id = '$current_ticket' AND sender_type = 'admin' AND is_read = 0";
            $update_result = mysqli_query($conn, $update_query);
            
            if (!$update_result) {
                $debug_info[] = "⚠ Update query warning: " . mysqli_error($conn);
            } else {
                $debug_info[] = "✓ Marked admin messages as read";
            }
            
            // Count messages
            $count_query = "SELECT COUNT(*) as total FROM support_messages WHERE ticket_id = '$current_ticket'";
            $count_result = mysqli_query($conn, $count_query);
            $count_row = mysqli_fetch_assoc($count_result);
            $debug_info[] = "📊 Total messages in DB: " . $count_row['total'];
            
            // Fetch messages
            $messages_query = "SELECT m.*, 
                                      a.id as attachment_id,
                                      a.file_name as attachment_name,
                                      a.file_path as attachment_path
                               FROM support_messages m
                               LEFT JOIN support_attachments a ON m.id = a.message_id
                               WHERE m.ticket_id = '$current_ticket'
                               ORDER BY m.created_at ASC";
            $messages_result = mysqli_query($conn, $messages_query);
            
            if (!$messages_result) {
                $debug_info[] = "❌ Messages query failed: " . mysqli_error($conn);
            } else {
                $message_count = 0;
                
                // Group messages by ID to handle multiple attachments
                $message_groups = [];
                while ($row = mysqli_fetch_assoc($messages_result)) {
                    $msg_id = $row['id'];
                    
                    if (!isset($message_groups[$msg_id])) {
                        $message_groups[$msg_id] = [
                            'id' => $row['id'],
                            'ticket_id' => $row['ticket_id'],
                            'sender_type' => $row['sender_type'],
                            'sender_id' => $row['sender_id'],
                            'message' => $row['message'],
                            'status' => $row['status'],
                            'is_read' => $row['is_read'],
                            'created_at' => $row['created_at'],
                            'attachments' => []
                        ];
                        
                        if ($row['id'] > $last_message_id) {
                            $last_message_id = $row['id'];
                        }
                    }
                    
                    // Add attachment if exists
                    if ($row['attachment_id']) {
                        $message_groups[$msg_id]['attachments'][] = [
                            'name' => $row['attachment_name'],
                            'path' => $row['attachment_path']
                        ];
                    }
                }
                
                $messages = array_values($message_groups);
                $message_count = count($messages);
                $debug_info[] = "✓ Retrieved $message_count messages with attachments";
            }
        } else {
            $debug_info[] = "❌ No ticket found with ID: $current_ticket for user: $my_id";
        }
    }
}

// Get unread count for header
$unread_query = "SELECT COUNT(DISTINCT t.id) as total 
                 FROM support_tickets t 
                 JOIN support_messages m ON t.id = m.ticket_id 
                 WHERE t.user_id = '$my_id' AND m.sender_type = 'admin' AND m.is_read = 0";
$unread_result = mysqli_query($conn, $unread_query);
$unread_count = mysqli_fetch_assoc($unread_result)['total'];

// Success/Error messages
$success_message = $_SESSION['success_message'] ?? '';
$error_message = $_SESSION['error_message'] ?? '';
unset($_SESSION['success_message'], $_SESSION['error_message']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>Help & Support - <?php echo htmlspecialchars($user_data['name']); ?></title>
    
    <!-- Favicons -->
    <link href="../img/logo/logo22222.png" rel="icon">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <!-- Vendor CSS Files -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">
    
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            --warning-gradient: linear-gradient(135deg, #fad0c4 0%, #ffd1ff 100%);
            --primary-color: #667eea;
            --secondary-color: #764ba2;
            --bg-light: #f8fafc;
            --text-primary: #1e293b;
            --text-secondary: #64748b;
            --border-color: #e2e8f0;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg-light);
            color: var(--text-primary);
            height: 100vh;
            overflow: hidden;
        }

        /* Debug Panel */
        .debug-panel {
            background: #1e293b;
            color: #e2e8f0;
            padding: 15px;
            margin: 10px 20px;
            border-radius: 12px;
            font-family: monospace;
            font-size: 13px;
            border-left: 4px solid #3b82f6;
            max-height: 200px;
            overflow-y: auto;
        }

        .debug-panel h6 {
            color: #94a3b8;
            margin-bottom: 10px;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .debug-panel ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .debug-panel li {
            padding: 3px 0;
            border-bottom: 1px solid #334155;
        }

        .debug-panel li:last-child {
            border-bottom: none;
        }

        /* Main Layout */
        .support-container {
            display: flex;
            height: calc(100vh - 180px);
            background: white;
            border-radius: 30px;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0,0,0,0.05);
            margin: 0 20px 20px;
        }

        /* Tickets Sidebar */
        .tickets-sidebar {
            width: 380px;
            background: white;
            border-right: 2px solid var(--border-color);
            display: flex;
            flex-direction: column;
        }

        .sidebar-header {
            padding: 25px;
            border-bottom: 2px solid var(--border-color);
        }

        .sidebar-header h3 {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 15px;
            color: var(--text-primary);
        }

        .new-ticket-btn {
            width: 100%;
            padding: 14px;
            border: none;
            border-radius: 16px;
            background: var(--primary-gradient);
            color: white;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .new-ticket-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
        }

        .tickets-search {
            padding: 15px 20px;
            border: 2px solid var(--border-color);
            border-radius: 16px;
            width: 100%;
            margin-top: 15px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }

        .tickets-search:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        }

        .tickets-list {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
        }

        .ticket-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px;
            border-radius: 20px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid transparent;
            background: var(--bg-light);
            position: relative;
        }

        .ticket-item:hover {
            transform: translateX(5px);
            border-color: var(--primary-color);
        }

        .ticket-item.active {
            background: var(--primary-gradient);
            border-color: transparent;
        }

        .ticket-item.active .ticket-subject,
        .ticket-item.active .ticket-id,
        .ticket-item.active .ticket-time,
        .ticket-item.active .ticket-priority {
            color: white;
        }

        .ticket-avatar {
            width: 50px;
            height: 50px;
            border-radius: 16px;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: var(--primary-color);
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }

        .ticket-info {
            flex: 1;
            min-width: 0;
        }

        .ticket-subject {
            font-weight: 600;
            margin-bottom: 5px;
            color: var(--text-primary);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .ticket-meta {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 0.75rem;
            margin-bottom: 5px;
            flex-wrap: wrap;
        }

        .ticket-id {
            color: var(--text-secondary);
        }

        .ticket-priority {
            padding: 2px 8px;
            border-radius: 30px;
            font-weight: 600;
        }

        .priority-urgent { background: #fee2e2; color: #991b1b; }
        .priority-high { background: #ffedd5; color: #9a3412; }
        .priority-medium { background: #dbeafe; color: #1e40af; }
        .priority-low { background: #dcfce7; color: #166534; }

        .ticket-status {
            padding: 2px 8px;
            border-radius: 30px;
            font-weight: 600;
            font-size: 0.7rem;
        }

        .status-open { background: #dbeafe; color: #1e40af; }
        .status-in_progress { background: #fed7aa; color: #9a3412; }
        .status-resolved { background: #dcfce7; color: #166534; }
        .status-closed { background: #e2e8f0; color: #475569; }

        .ticket-time {
            font-size: 0.7rem;
            color: var(--text-secondary);
        }

        .unread-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            min-width: 20px;
            height: 20px;
            border-radius: 10px;
            background: var(--primary-color);
            color: white;
            font-size: 0.7rem;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0 5px;
        }

        /* Chat Area */
        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: white;
        }

        .chat-header {
            padding: 20px 30px;
            border-bottom: 2px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .chat-header-info h4 {
            font-weight: 700;
            margin-bottom: 5px;
            color: var(--text-primary);
        }

        .chat-header-meta {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 30px;
            background: var(--bg-light);
            position: relative;
        }

        .message-wrapper {
            display: flex;
            margin-bottom: 20px;
            animation: slideIn 0.3s ease;
            position: relative;
        }

        .message-wrapper.user {
            justify-content: flex-end;
        }

        .message-bubble {
            max-width: 70%;
            padding: 15px 20px;
            border-radius: 20px;
            position: relative;
            word-wrap: break-word;
        }

        .message-bubble.user {
            background: var(--primary-gradient);
            color: white;
            border-bottom-right-radius: 5px;
        }

        .message-bubble.admin {
            background: white;
            color: var(--text-primary);
            border-bottom-left-radius: 5px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }

        .message-sender {
            font-size: 0.85rem;
            font-weight: 600;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .message-text {
            line-height: 1.6;
            margin-bottom: 5px;
        }

        .message-footer {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 5px;
            margin-top: 5px;
        }

        .message-time {
            font-size: 0.7rem;
            opacity: 0.7;
        }

        .message-status {
            font-size: 0.8rem;
            display: flex;
            align-items: center;
        }

        .status-sent { color: #94a3b8; }
        .status-delivered { color: #64748b; }
        .status-read { color: #3b82f6; }

        .message-attachment {
            margin-top: 10px;
            padding: 10px;
            background: rgba(255,255,255,0.1);
            border-radius: 10px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            max-width: 100%;
        }

        .message-attachment a {
            color: inherit;
            text-decoration: none;
            word-break: break-all;
        }

        .message-attachment img {
            max-width: 150px;
            max-height: 150px;
            border-radius: 8px;
            cursor: pointer;
        }

        /* Typing Indicator */
        .typing-indicator {
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 10px 20px;
            background: white;
            border-radius: 20px;
            width: fit-content;
            margin-bottom: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            border-radius: 4px;
            background: var(--primary-color);
            animation: typing 1.5s infinite ease-in-out;
        }

        .typing-dot:nth-child(1) { animation-delay: 0s; }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typing {
            0%, 60%, 100% { transform: translateY(0); opacity: 0.5; }
            30% { transform: translateY(-10px); opacity: 1; }
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Chat Footer */
        .chat-footer {
            padding: 20px 30px;
            border-top: 2px solid var(--border-color);
            margin-bottom: 66px;
        }

        .message-input-container {
            display: flex;
            align-items: flex-end;
            gap: 15px;
        }

        .message-input-wrapper {
            flex: 1;
            position: relative;
        }

        .message-input {
            width: 100%;
            padding: 15px 100px 15px 20px;
            border: 2px solid var(--border-color);
            border-radius: 25px;
            font-size: 0.95rem;
            resize: none;
            max-height: 120px;
            transition: all 0.3s ease;
        }

        .message-input:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        }

        .input-actions {
            position: absolute;
            right: 15px;
            bottom: 15px;
            display: flex;
            gap: 10px;
        }

        .input-action-btn {
            background: none;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            transition: all 0.2s ease;
            padding: 5px;
            font-size: 1.1rem;
        }

        .input-action-btn:hover {
            color: var(--primary-color);
            transform: scale(1.1);
        }

        .send-btn {
            width: 50px;
            height: 50px;
            border-radius: 25px;
            border: none;
            background: var(--primary-gradient);
            color: white;
            font-size: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .send-btn:hover:not(:disabled) {
            transform: scale(1.1);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
        }

        .send-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* New message notification */
        .new-message-notification {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: var(--primary-gradient);
            color: white;
            padding: 15px 25px;
            border-radius: 50px;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
            cursor: pointer;
            animation: slideIn 0.3s ease;
            z-index: 1000;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .new-message-notification:hover {
            transform: translateY(-2px);
            box-shadow: 0 15px 35px rgba(102, 126, 234, 0.4);
        }

        .notification-badge {
            background: white;
            color: var(--primary-color);
            border-radius: 20px;
            padding: 2px 10px;
            font-weight: 600;
        }

        /* New Ticket Modal */
        .modal-content-modern {
            border-radius: 30px;
            border: none;
        }

        .modal-header-modern {
            background: var(--primary-gradient);
            color: white;
            padding: 25px 30px;
            border-radius: 30px 30px 0 0;
        }

        .modal-body-modern {
            padding: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 8px;
            display: block;
        }

        .form-control-modern {
            width: 100%;
            padding: 14px 20px;
            border: 2px solid var(--border-color);
            border-radius: 16px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }

        .form-control-modern:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        }

        .file-upload-area {
            border: 2px dashed var(--border-color);
            border-radius: 16px;
            padding: 30px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .file-upload-area:hover {
            border-color: var(--primary-color);
            background: rgba(102, 126, 234, 0.05);
        }

        .file-upload-area i {
            font-size: 40px;
            color: var(--primary-color);
            margin-bottom: 10px;
        }

        .file-list {
            margin-top: 15px;
        }

        .file-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px;
            background: var(--bg-light);
            border-radius: 12px;
            margin-bottom: 8px;
        }

        .file-item i {
            color: var(--primary-color);
            margin-right: 10px;
        }

        .file-remove {
            color: #ef4444;
            cursor: pointer;
        }

        /* Image Preview Modal */
        .image-preview-modal .modal-dialog {
            max-width: 90vw;
            max-height: 90vh;
        }

        .image-preview-modal img {
            width: 100%;
            height: auto;
        }

        /* Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: var(--bg-light);
        }

        ::-webkit-scrollbar-thumb {
            background: var(--border-color);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--primary-color);
        }

        /* Responsive */
        @media (max-width: 768px) {
            .support-container {
                flex-direction: column;
                height: auto;
            }
            
            .tickets-sidebar {
                width: 100%;
                height: 300px;
            }
            
            .message-bubble {
                max-width: 90%;
            }
        }
    </style>
</head>
<body>

    <!-- Header -->
    <?php include 'element/header.php'; ?>
    
    <!-- Sidebar -->
    <?php include 'element/sidebar.php'; ?>

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>Help & Support</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Support</li>
                </ol>
            </nav>
        </div>

        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show mx-3" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo htmlspecialchars($success_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show mx-3" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo htmlspecialchars($error_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

       

        <!-- Support Container -->
        <div class="support-container">
            <!-- Tickets Sidebar -->
            <div class="tickets-sidebar">
                <div class="sidebar-header">
                    <h3>My Support Tickets</h3>
                    <button class="new-ticket-btn" data-bs-toggle="modal" data-bs-target="#newTicketModal">
                        <i class="fas fa-plus-circle"></i>
                        <span>Create New Ticket</span>
                    </button>
                    <input type="text" class="tickets-search" placeholder="Search tickets..." id="searchTickets">
                </div>
                
                <div class="tickets-list" id="ticketsList">
                    <?php if (mysqli_num_rows($tickets_result) > 0): ?>
                        <?php while ($ticket = mysqli_fetch_assoc($tickets_result)): ?>
                            <div class="ticket-item <?php echo $current_ticket == $ticket['id'] ? 'active' : ''; ?>" 
                                 onclick="window.location.href='help.php?ticket=<?php echo $ticket['id']; ?>'">
                                <div class="ticket-avatar">
                                    <i class="fas fa-ticket-alt"></i>
                                </div>
                                <div class="ticket-info">
                                    <div class="ticket-subject">
                                        <?php echo htmlspecialchars(substr($ticket['subject'], 0, 30)) . (strlen($ticket['subject']) > 30 ? '...' : ''); ?>
                                    </div>
                                    <div class="ticket-meta">
                                        <span class="ticket-id">#<?php echo $ticket['ticket_id']; ?></span>
                                        <span class="ticket-priority priority-<?php echo $ticket['priority']; ?>">
                                            <?php echo ucfirst($ticket['priority']); ?>
                                        </span>
                                        <span class="ticket-status status-<?php echo $ticket['status']; ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?>
                                        </span>
                                    </div>
                                    <div class="ticket-time">
                                        <i class="far fa-clock me-1"></i>
                                        <?php echo $ticket['last_activity'] ? date('d M H:i', strtotime($ticket['last_activity'])) : date('d M H:i', strtotime($ticket['created_at'])); ?>
                                    </div>
                                </div>
                                <?php if ($ticket['unread_admin'] > 0): ?>
                                    <div class="unread-badge"><?php echo $ticket['unread_admin']; ?></div>
                                <?php endif; ?>
                            </div>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="text-center py-5">
                            <i class="fas fa-ticket-alt fa-4x text-muted mb-3"></i>
                            <h5 class="text-muted">No tickets yet</h5>
                            <p class="text-muted">Create your first support ticket</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Chat Area -->
            <div class="chat-area">
                <?php if ($current_ticket_data): ?>
                    <!-- Chat Header -->
                    <div class="chat-header">
                        <div class="chat-header-info">
                            <h4><?php echo htmlspecialchars($current_ticket_data['subject']); ?></h4>
                            <div class="chat-header-meta">
                                <span class="ticket-id">#<?php echo $current_ticket_data['ticket_id']; ?></span>
                                <span class="ticket-priority priority-<?php echo $current_ticket_data['priority']; ?>">
                                    <i class="fas fa-flag"></i>
                                    <?php echo ucfirst($current_ticket_data['priority']); ?>
                                </span>
                                <span class="ticket-status status-<?php echo $current_ticket_data['status']; ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $current_ticket_data['status'])); ?>
                                </span>
                            </div>
                        </div>
                        <div>
                            <span class="online-status" id="adminOnlineStatus">
                                <i class="fas fa-circle text-secondary me-1" style="font-size: 10px;"></i>
                                <span id="adminStatusText">Checking...</span>
                            </span>
                        </div>
                    </div>

                    <!-- Chat Messages -->
                    <div class="chat-messages" id="chatMessages">
                        <?php if (!empty($messages)): ?>
                            <?php foreach ($messages as $message): ?>
                                <div class="message-wrapper <?php echo $message['sender_type']; ?>" id="message-<?php echo $message['id']; ?>" data-message-id="<?php echo $message['id']; ?>">
                                    <div class="message-bubble <?php echo $message['sender_type']; ?>">
                                        <?php if ($message['sender_type'] == 'admin'): ?>
                                            <div class="message-sender">
                                                <i class="fas fa-shield-alt"></i> Support Team
                                            </div>
                                        <?php endif; ?>
                                        
                                        <div class="message-text">
                                            <?php echo nl2br(htmlspecialchars($message['message'])); ?>
                                        </div>
                                        
                                        <?php if (!empty($message['attachments'])): ?>
                                            <?php foreach ($message['attachments'] as $attachment): ?>
                                                <?php 
                                                $ext = strtolower(pathinfo($attachment['name'], PATHINFO_EXTENSION));
                                                $is_image = in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp']);
                                                ?>
                                                <div class="message-attachment">
                                                    <?php if ($is_image): ?>
                                                        <i class="fas fa-image"></i>
                                                        <a href="javascript:void(0)" onclick="previewImage('<?php echo $attachment['path']; ?>')">
                                                            <img src="<?php echo $attachment['path']; ?>" alt="Attachment">
                                                        </a>
                                                    <?php else: ?>
                                                        <i class="fas fa-paperclip"></i>
                                                        <a href="<?php echo $attachment['path']; ?>" download="<?php echo $attachment['name']; ?>">
                                                            <?php echo $attachment['name']; ?>
                                                        </a>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                        
                                        <div class="message-footer">
                                            <span class="message-time">
                                                <?php echo date('h:i A', strtotime($message['created_at'])); ?>
                                            </span>
                                            <?php if ($message['sender_type'] == 'user'): ?>
                                                <span class="message-status" id="status-<?php echo $message['id']; ?>">
                                                    <?php if ($message['status'] == 'read'): ?>
                                                        <i class="fas fa-check-double text-primary" title="Read"></i>
                                                    <?php elseif ($message['status'] == 'delivered'): ?>
                                                        <i class="fas fa-check text-muted" title="Delivered"></i>
                                                    <?php else: ?>
                                                        <i class="far fa-clock text-muted" title="Sent"></i>
                                                    <?php endif; ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-center py-5 text-muted">
                                <i class="fas fa-comments fa-4x mb-3"></i>
                                <h5>No messages yet</h5>
                                <p>Start the conversation by sending a message below</p>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Typing Indicator -->
                        <div class="typing-indicator" id="typingIndicator" style="display: none;">
                            <div class="typing-dot"></div>
                            <div class="typing-dot"></div>
                            <div class="typing-dot"></div>
                            <span>Support is typing...</span>
                        </div>
                    </div>

                    <!-- Chat Footer -->
                    <div class="chat-footer">
                        <form method="POST" enctype="multipart/form-data" id="replyForm">
                            <input type="hidden" name="reply_ticket" value="1">
                            <input type="hidden" name="ticket_id" value="<?php echo $current_ticket; ?>">
                            
                            <div class="message-input-container">
                                <div class="message-input-wrapper">
                                    <textarea class="message-input" 
                                              name="message" 
                                              id="messageInput" 
                                              placeholder="Type your message..."
                                              rows="1"
                                              <?php echo in_array($current_ticket_data['status'], ['resolved', 'closed']) ? 'disabled' : ''; ?>
                                              required></textarea>
                                    
                                    <div class="input-actions">
                                        <button type="button" class="input-action-btn" onclick="document.getElementById('fileUpload').click()">
                                            <i class="fas fa-paperclip"></i>
                                        </button>
                                    </div>
                                </div>
                                
                                <button type="submit" class="send-btn" id="sendBtn" 
                                        <?php echo in_array($current_ticket_data['status'], ['resolved', 'closed']) ? 'disabled' : ''; ?>>
                                    <i class="fas fa-paper-plane"></i>
                                </button>
                            </div>
                            
                            <!-- File Upload -->
                            <input type="file" name="attachments[]" id="fileUpload" style="display: none;" multiple>
                            <div id="filePreview" class="file-list mt-2" style="display: none;"></div>
                        </form>
                        
                        <?php if (in_array($current_ticket_data['status'], ['resolved', 'closed'])): ?>
                            <div class="alert alert-warning mt-3 mb-0">
                                <i class="fas fa-lock me-2"></i>
                                This ticket is <?php echo $current_ticket_data['status']; ?>. Create a new ticket for further assistance.
                            </div>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <!-- No Ticket Selected -->
                    <div class="d-flex flex-column align-items-center justify-content-center h-100">
                        <i class="fas fa-comments fa-5x text-muted mb-4"></i>
                        <h3 class="text-muted">Select a ticket to start chatting</h3>
                        <p class="text-muted">Or create a new ticket to get support</p>
                        <button class="new-ticket-btn" style="width: auto; padding: 12px 30px;" data-bs-toggle="modal" data-bs-target="#newTicketModal">
                            <i class="fas fa-plus-circle"></i>
                            Create New Ticket
                        </button>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <!-- New Ticket Modal -->
    <div class="modal fade" id="newTicketModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content modal-content-modern">
                <div class="modal-header modal-header-modern">
                    <h5 class="modal-title"><i class="fas fa-plus-circle me-2"></i>Create New Support Ticket</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" enctype="multipart/form-data" id="ticketForm">
                    <div class="modal-body modal-body-modern">
                        <div class="form-group">
                            <label class="form-label">Subject</label>
                            <input type="text" class="form-control-modern" name="subject" required 
                                   placeholder="Brief description of your issue">
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label">Category</label>
                                    <select class="form-control-modern" name="category" required>
                                        <option value="general">General Inquiry</option>
                                        <option value="technical">Technical Issue</option>
                                        <option value="withdrawal">Withdrawal Issue</option>
                                        <option value="pin">PIN Related</option>
                                        <option value="account">Account Issue</option>
                                        <option value="other">Other</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label">Priority</label>
                                    <select class="form-control-modern" name="priority" required>
                                        <option value="low">Low</option>
                                        <option value="medium" selected>Medium</option>
                                        <option value="high">High</option>
                                        <option value="urgent">Urgent</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Message</label>
                            <textarea class="form-control-modern" name="message" rows="5" required 
                                      placeholder="Describe your issue in detail..."></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Attachments (Optional)</label>
                            <div class="file-upload-area" onclick="document.getElementById('modalFileInput').click()">
                                <i class="fas fa-cloud-upload-alt"></i>
                                <p>Click to upload or drag and drop</p>
                                <small class="text-muted">Supported: Images, PDF, DOC (Max 10MB)</small>
                            </div>
                            <input type="file" name="attachments[]" id="modalFileInput" multiple style="display: none;" 
                                   onchange="updateModalFileList(this)">
                            <div class="file-list" id="modalFileList"></div>
                        </div>
                        
                        <input type="hidden" name="create_ticket" value="1">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Create Ticket</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Image Preview Modal -->
    <div class="modal fade image-preview-modal" id="imagePreviewModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body p-0">
                    <img src="" id="previewImage" class="img-fluid" alt="Preview">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <a href="" id="downloadImage" class="btn btn-primary" download>Download</a>
                </div>
            </div>
        </div>
    </div>

    <!-- New Message Notification -->
    <div id="newMessageNotification" class="new-message-notification" style="display: none;" onclick="scrollToBottom()">
        <i class="fas fa-envelope"></i>
        <span>New message from Support</span>
        <span class="notification-badge" id="newMessageCount">1</span>
    </div>

    <!-- Footer -->
    <?php include('element/footer.php'); ?>

    <a href="#" class="back-to-top d-flex align-items-center justify-content-center">
        <i class="bi bi-arrow-up-short"></i>
    </a>

    <!-- Vendor JS Files -->
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/vendor/jquery/jquery-3.6.0.min.js"></script>
    <script src="assets/js/main.js"></script>

    <script>
        // Current ticket and user info
        const currentTicketId = <?php echo $current_ticket ?: 0; ?>;
        const userId = <?php echo $my_id; ?>;
        let lastMessageId = <?php echo $last_message_id; ?>;
        let newMessageCount = 0;
        let typingTimeout;
        let longPollingActive = true;

        // Auto-resize textarea
        const textarea = document.getElementById('messageInput');
        if (textarea) {
            textarea.addEventListener('input', function() {
                this.style.height = 'auto';
                this.style.height = (this.scrollHeight) + 'px';
                
                // Send typing indicator
                // Mark messages as read when viewing ticket
if (currentTicketId) {
    // Clear notification badge immediately
    const badge = document.getElementById('supportBadge');
    if (badge) {
        badge.style.display = 'none';
    }
    
    // Update server that messages are read
    fetch('ajax/mark_messages_read.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `ticket_id=${currentTicketId}&user_id=${userId}`
    }).catch(e => console.log('Error marking read:', e));
}
            });
        }

        // Scroll to bottom of chat
        function scrollToBottom() {
            const chatMessages = document.getElementById('chatMessages');
            if (chatMessages) {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
        }
        
        // Scroll to bottom on page load
        setTimeout(scrollToBottom, 100);

        // Search tickets
        document.getElementById('searchTickets')?.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const tickets = document.querySelectorAll('.ticket-item');
            
            tickets.forEach(ticket => {
                const subject = ticket.querySelector('.ticket-subject')?.textContent.toLowerCase() || '';
                const id = ticket.querySelector('.ticket-id')?.textContent.toLowerCase() || '';
                
                if (subject.includes(searchTerm) || id.includes(searchTerm)) {
                    ticket.style.display = 'flex';
                } else {
                    ticket.style.display = 'none';
                }
            });
        });

        // File upload handling for modal
        window.updateModalFileList = function(input) {
            const fileList = document.getElementById('modalFileList');
            fileList.innerHTML = '';
            
            for (let i = 0; i < input.files.length; i++) {
                const file = input.files[i];
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.innerHTML = `
                    <div>
                        <i class="fas fa-file"></i>
                        <span>${file.name}</span>
                        <small class="text-muted ms-2">(${(file.size / 1024).toFixed(2)} KB)</small>
                    </div>
                    <i class="fas fa-times file-remove" onclick="removeModalFile(${i})"></i>
                `;
                fileList.appendChild(fileItem);
            }
        }

        window.removeModalFile = function(index) {
            const input = document.getElementById('modalFileInput');
            const dt = new DataTransfer();
            
            for (let i = 0; i < input.files.length; i++) {
                if (i !== index) {
                    dt.items.add(input.files[i]);
                }
            }
            
            input.files = dt.files;
            updateModalFileList(input);
        }

        // File upload for reply
        document.getElementById('fileUpload')?.addEventListener('change', function(e) {
            const preview = document.getElementById('filePreview');
            preview.innerHTML = '';
            
            if (this.files.length > 0) {
                preview.style.display = 'block';
                for (let i = 0; i < this.files.length; i++) {
                    const file = this.files[i];
                    const fileItem = document.createElement('div');
                    fileItem.className = 'file-item';
                    fileItem.innerHTML = `
                        <div>
                            <i class="fas fa-file"></i>
                            <span>${file.name}</span>
                            <small class="text-muted ms-2">(${(file.size / 1024).toFixed(2)} KB)</small>
                        </div>
                        <i class="fas fa-times file-remove" onclick="removeReplyFile(${i})"></i>
                    `;
                    preview.appendChild(fileItem);
                }
            } else {
                preview.style.display = 'none';
            }
        });

        window.removeReplyFile = function(index) {
            const input = document.getElementById('fileUpload');
            const dt = new DataTransfer();
            
            for (let i = 0; i < input.files.length; i++) {
                if (i !== index) {
                    dt.items.add(input.files[i]);
                }
            }
            
            input.files = dt.files;
            const event = new Event('change');
            input.dispatchEvent(event);
        }

        // Image preview
        window.previewImage = function(src) {
            document.getElementById('previewImage').src = src;
            document.getElementById('downloadImage').href = src;
            new bootstrap.Modal(document.getElementById('imagePreviewModal')).show();
        }

        // Send typing status
        function sendTypingStatus(typing) {
            if (!currentTicketId) return;
            
            fetch('ajax/user_typing.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `ticket_id=${currentTicketId}&typing=${typing}`
            }).catch(e => console.log('Typing error:', e));
        }

        // Long polling for new messages
        function longPollMessages() {
            if (!currentTicketId || !longPollingActive) return;
            
            fetch(`ajax/poll_messages.php?ticket_id=${currentTicketId}&last_id=${lastMessageId}&user_id=${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.messages && data.messages.length > 0) {
                        data.messages.forEach(message => {
                            receiveNewMessage(message);
                            if (message.id > lastMessageId) {
                                lastMessageId = message.id;
                            }
                        });
                    }
                    
                    // Update typing indicator
                    const indicator = document.getElementById('typingIndicator');
                    if (indicator) {
                        indicator.style.display = data.is_typing ? 'flex' : 'none';
                    }
                    
                    // Update online status
                    if (data.admin_online !== undefined) {
                        const statusElement = document.getElementById('adminOnlineStatus');
                        const statusText = document.getElementById('adminStatusText');
                        
                        if (data.admin_online) {
                            statusElement.innerHTML = '<i class="fas fa-circle text-success me-1" style="font-size: 10px;"></i><span id="adminStatusText">Support Online</span>';
                        } else {
                            statusElement.innerHTML = '<i class="fas fa-circle text-secondary me-1" style="font-size: 10px;"></i><span id="adminStatusText">Support Offline</span>';
                        }
                    }
                    
                    setTimeout(longPollMessages, 2000);
                })
                .catch(error => {
                    console.log('Polling error:', error);
                    setTimeout(longPollMessages, 5000);
                });
        }

        // Receive new message
        function receiveNewMessage(message) {
            const chatMessages = document.getElementById('chatMessages');
            
            const messageHtml = createMessageHtml(message);
            chatMessages.insertAdjacentHTML('beforeend', messageHtml);
            scrollToBottom();
            
            // Show notification
            showNewMessageNotification();
            
            // Play notification sound
            playNotificationSound();
        }

        // Create message HTML
        function createMessageHtml(message) {
            let attachmentsHtml = '';
            if (message.attachments && message.attachments.length > 0) {
                message.attachments.forEach(att => {
                    const ext = att.split('.').pop().toLowerCase();
                    const isImage = ['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext);
                    
                    attachmentsHtml += `
                        <div class="message-attachment">
                            ${isImage ? 
                                `<i class="fas fa-image"></i>
                                 <a href="javascript:void(0)" onclick="previewImage('${att}')">
                                     <img src="${att}" alt="Attachment">
                                 </a>` :
                                `<i class="fas fa-paperclip"></i>
                                 <a href="${att}" download>Attachment</a>`
                            }
                        </div>
                    `;
                });
            }
            
            const statusIcon = message.sender_type === 'user' ? 
                (message.status === 'read' ? 
                    '<i class="fas fa-check-double text-primary" title="Read"></i>' : 
                    '<i class="far fa-clock text-muted" title="Sent"></i>') : '';
            
            return `
                <div class="message-wrapper ${message.sender_type}" id="message-${message.id}">
                    <div class="message-bubble ${message.sender_type}">
                        ${message.sender_type === 'admin' ? 
                            '<div class="message-sender"><i class="fas fa-shield-alt"></i> Support Team</div>' : ''}
                        <div class="message-text">${message.message.replace(/\n/g, '<br>')}</div>
                        ${attachmentsHtml}
                        <div class="message-footer">
                            <span class="message-time">${message.time_formatted || new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
                            ${message.sender_type === 'user' ? 
                                `<span class="message-status">${statusIcon}</span>` : ''}
                        </div>
                    </div>
                </div>
            `;
        }

        // Show new message notification
        function showNewMessageNotification() {
            const notification = document.getElementById('newMessageNotification');
            const countSpan = document.getElementById('newMessageCount');
            
            newMessageCount++;
            countSpan.textContent = newMessageCount;
            notification.style.display = 'flex';
            
            setTimeout(() => {
                newMessageCount--;
                if (newMessageCount <= 0) {
                    notification.style.display = 'none';
                } else {
                    countSpan.textContent = newMessageCount;
                }
            }, 5000);
        }

        // Play notification sound
        function playNotificationSound() {
            const audio = new Audio('assets/sounds/notification.mp3');
            audio.play().catch(e => console.log('Audio play failed:', e));
        }

        // Start long polling if ticket selected
        if (currentTicketId) {
            longPollMessages();
        }

        // Form validation
        document.getElementById('ticketForm')?.addEventListener('submit', function(e) {
            const subject = this.subject.value.trim();
            const message = this.message.value.trim();
            
            if (!subject || !message) {
                e.preventDefault();
                alert('Please fill in all required fields');
                return;
            }
        });

        document.getElementById('replyForm')?.addEventListener('submit', function(e) {
            const message = this.message.value.trim();
            
            if (!message && document.getElementById('fileUpload').files.length === 0) {
                e.preventDefault();
                alert('Please enter a message or attach a file');
                return;
            }
            
            document.getElementById('sendBtn').disabled = true;
            document.getElementById('sendBtn').innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
            sendTypingStatus(false);
        });

        // Stop long polling on page unload
        window.addEventListener('beforeunload', function() {
            longPollingActive = false;
        });
    </script>
</body>
</html>