<?php
require_once 'config/database.php';
secureSessionStart();
requireLogin();

$conn = getConnection();
$admin_id = $_SESSION['admin_user'];

// Handle reply to ticket - AJAX endpoint
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_ticket'])) {
    header('Content-Type: application/json');
    
    $ticket_id = intval($_POST['ticket_id']);
    $message = mysqli_real_escape_string($conn, $_POST['message']);
    
    if (empty($message)) {
        echo json_encode(['success' => false, 'error' => 'Message cannot be empty']);
        exit();
    }
    
    // Insert admin reply
    $reply_query = "INSERT INTO support_messages (ticket_id, sender_type, sender_id, message, created_at) 
                    VALUES ('$ticket_id', 'admin', '$admin_id', '$message', NOW())";
    
    if (mysqli_query($conn, $reply_query)) {
        $message_id = mysqli_insert_id($conn);
        
        // Update ticket
        mysqli_query($conn, "UPDATE support_tickets SET updated_at = NOW() WHERE id = '$ticket_id'");
        
        echo json_encode([
            'success' => true, 
            'message_id' => $message_id,
            'time' => date('h:i A')
        ]);
        exit();
    } else {
        echo json_encode(['success' => false, 'error' => mysqli_error($conn)]);
        exit();
    }
}

// Handle ticket status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    header('Content-Type: application/json');
    
    $ticket_id = intval($_POST['ticket_id']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    
    $update_query = "UPDATE support_tickets SET status = '$status', updated_at = NOW() WHERE id = '$ticket_id'";
    
    if (mysqli_query($conn, $update_query)) {
        echo json_encode(['success' => true]);
        exit();
    } else {
        echo json_encode(['success' => false, 'error' => mysqli_error($conn)]);
        exit();
    }
}

// Handle assign to self
if (isset($_GET['assign'])) {
    header('Content-Type: application/json');
    
    $ticket_id = intval($_GET['assign']);
    $assign_query = "UPDATE support_tickets SET assigned_to = '$admin_id', status = 'in_progress', updated_at = NOW() WHERE id = '$ticket_id'";
    
    if (mysqli_query($conn, $assign_query)) {
        echo json_encode(['success' => true]);
        exit();
    }
    echo json_encode(['success' => false]);
    exit();
}

// Get filters
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$priority_filter = isset($_GET['priority']) ? $_GET['priority'] : 'all';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';

// Build WHERE clause
$where = ["1=1"];
if ($status_filter != 'all') {
    $where[] = "t.status = '$status_filter'";
}
if ($priority_filter != 'all') {
    $where[] = "t.priority = '$priority_filter'";
}
if ($search) {
    $where[] = "(t.ticket_id LIKE '%$search%' OR t.subject LIKE '%$search%' OR u.name LIKE '%$search%')";
}
$where_clause = implode(" AND ", $where);

// Get tickets
$tickets_query = "SELECT t.*, 
                         u.name as user_name, 
                         u.user_id as user_user_id,
                         u.image as user_image,
                         (SELECT COUNT(*) FROM support_messages WHERE ticket_id = t.id AND sender_type = 'user' AND is_read = 0) as unread_user,
                         (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
                  LEFT JOIN users u ON t.user_id = u.user_id
                  WHERE $where_clause
                  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);

// Get current ticket
$current_ticket = isset($_GET['ticket']) ? intval($_GET['ticket']) : 0;
$current_ticket_data = null;
$messages = [];
$user_details = null;
$last_message_id = 0;

if ($current_ticket > 0) {
    // Get ticket details
    $ticket_query = "SELECT t.*, u.* 
                     FROM support_tickets t 
                     LEFT JOIN users u ON t.user_id = u.user_id 
                     WHERE t.id = '$current_ticket'";
    $ticket_result = mysqli_query($conn, $ticket_query);
    $current_ticket_data = mysqli_fetch_assoc($ticket_result);
    
    if ($current_ticket_data) {
        $user_details = $current_ticket_data;
        
        // Mark user messages as read
        mysqli_query($conn, "UPDATE support_messages SET is_read = 1, read_at = NOW() 
                            WHERE ticket_id = '$current_ticket' AND sender_type = 'user' AND is_read = 0");
        
        // Get messages
        $messages_query = "SELECT m.*, 
                                  GROUP_CONCAT(a.file_name) as attachment_names,
                                  GROUP_CONCAT(a.file_path) as attachment_paths
                           FROM support_messages m
                           LEFT JOIN support_attachments a ON m.id = a.message_id
                           WHERE m.ticket_id = '$current_ticket'
                           GROUP BY m.id
                           ORDER BY m.created_at ASC";
        $messages_result = mysqli_query($conn, $messages_query);
        
        while ($row = mysqli_fetch_assoc($messages_result)) {
            $messages[] = $row;
            if ($row['id'] > $last_message_id) {
                $last_message_id = $row['id'];
            }
        }
    }
}

// Get stats
$stats = [];
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM support_tickets WHERE status IN ('open', 'in_progress')");
$stats['open'] = mysqli_fetch_assoc($result)['total'];
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM support_tickets WHERE priority = 'urgent' AND status IN ('open', 'in_progress')");
$stats['urgent'] = mysqli_fetch_assoc($result)['total'];

// Get templates
$templates_query = "SELECT * FROM support_templates ORDER BY title ASC";
$templates_result = mysqli_query($conn, $templates_query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>Support Management</title>
    
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Bootstrap -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Main CSS -->
    <link href="assets/css/style.css" rel="stylesheet">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border: 1px solid #e2e8f0;
        }

        .stat-icon {
            width: 45px;
            height: 45px;
            border-radius: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            margin-bottom: 15px;
        }

        .stat-value {
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 5px;
            color: #1e293b;
        }

        .stat-label {
            color: #64748b;
            font-size: 0.9rem;
        }

        /* Main Container */
        .support-container {
            display: flex;
            height: calc(100vh - 250px);
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border: 1px solid #e2e8f0;
        }

        /* Sidebar */
        .tickets-sidebar {
            width: 350px;
            border-right: 1px solid #e2e8f0;
            display: flex;
            flex-direction: column;
            background: white;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #e2e8f0;
        }

        .filter-buttons {
            display: flex;
            gap: 8px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        .filter-btn {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
            border: 1px solid #e2e8f0;
            background: white;
            color: #64748b;
            cursor: pointer;
            transition: all 0.2s;
        }

        .filter-btn.active,
        .filter-btn:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .search-input {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid #e2e8f0;
            border-radius: 25px;
            font-size: 0.95rem;
        }

        .search-input:focus {
            outline: none;
            border-color: #667eea;
        }

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

        .ticket-item {
            display: flex;
            gap: 12px;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.2s;
            background: #f8fafc;
            border: 1px solid transparent;
            position: relative;
        }

        .ticket-item:hover {
            border-color: #667eea;
            transform: translateX(3px);
        }

        .ticket-item.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

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

        .ticket-avatar {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            overflow: hidden;
            background: white;
        }

        .ticket-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

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

        .ticket-subject {
            font-weight: 600;
            font-size: 0.95rem;
            margin-bottom: 4px;
            color: #1e293b;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .ticket-meta {
            display: flex;
            gap: 8px;
            margin-bottom: 4px;
            font-size: 0.7rem;
        }

        .ticket-priority {
            padding: 2px 8px;
            border-radius: 12px;
            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: 12px;
            font-weight: 600;
        }

        .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; }

        .unread-badge {
            position: absolute;
            top: 8px;
            right: 8px;
            min-width: 18px;
            height: 18px;
            border-radius: 9px;
            background: #667eea;
            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: 15px 20px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .chat-user-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .chat-user-avatar {
            width: 45px;
            height: 45px;
            border-radius: 12px;
            overflow: hidden;
            border: 2px solid #667eea;
            cursor: pointer;
        }

        .chat-user-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .chat-user-details h4 {
            font-size: 1.1rem;
            font-weight: 600;
            margin-bottom: 4px;
            color: #1e293b;
        }

        .chat-user-meta {
            font-size: 0.8rem;
            color: #64748b;
            display: flex;
            gap: 12px;
        }

        .chat-actions {
            display: flex;
            gap: 8px;
        }

        .action-btn {
            width: 35px;
            height: 35px;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            background: white;
            color: #64748b;
            cursor: pointer;
            transition: all 0.2s;
        }

        .action-btn:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .status-select {
            padding: 5px 10px;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            font-size: 0.9rem;
        }

        /* Messages */
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f8fafc;
        }

        .message-wrapper {
            display: flex;
            margin-bottom: 20px;
            animation: fadeIn 0.3s;
        }

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

        .message-bubble {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            position: relative;
        }

        .message-bubble.admin {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-bottom-right-radius: 5px;
        }

        .message-bubble.user {
            background: white;
            color: #1e293b;
            border-bottom-left-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }

        .message-sender {
            font-size: 0.8rem;
            font-weight: 600;
            margin-bottom: 5px;
            opacity: 0.8;
        }

        .message-text {
            line-height: 1.5;
            word-wrap: break-word;
        }

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

        .message-time {
            opacity: 0.7;
        }

        .message-status i {
            font-size: 0.8rem;
        }

        .message-status .read { color: #3b82f6; }
        .message-status .unread { color: #94a3b8; }

        /* Chat Footer */
        .chat-footer {
            padding: 15px 20px;
            border-top: 1px solid #e2e8f0;
            background: white;
        }

        .reply-form {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }

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

        .message-input {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #e2e8f0;
            border-radius: 25px;
            font-size: 0.95rem;
            resize: none;
            min-height: 45px;
            max-height: 120px;
        }

        .message-input:focus {
            outline: none;
            border-color: #667eea;
        }

        .send-btn {
            width: 45px;
            height: 45px;
            border-radius: 25px;
            border: none;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .send-btn:hover:not(:disabled) {
            transform: scale(1.05);
        }

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

        .quick-replies {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-top: 10px;
        }

        .quick-reply-btn {
            padding: 5px 12px;
            border-radius: 20px;
            border: 1px solid #e2e8f0;
            background: white;
            color: #64748b;
            font-size: 0.8rem;
            cursor: pointer;
            transition: all 0.2s;
        }

        .quick-reply-btn:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        /* Notification */
        .new-message-notification {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 20px;
            border-radius: 30px;
            cursor: pointer;
            animation: slideIn 0.3s;
            z-index: 1000;
            display: flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.3);
        }

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

        @keyframes slideIn {
            from { transform: translateX(100%); }
            to { transform: translateX(0); }
        }

        .loading-spinner {
            display: inline-block;
            width: 18px;
            height: 18px;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 0.8s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        @media (max-width: 768px) {
            .support-container {
                flex-direction: column;
                height: auto;
            }
            .tickets-sidebar {
                width: 100%;
                height: 300px;
            }
        }
        
        /* Input group for email editing */
.input-group {
    display: flex;
    gap: 10px;
}

.input-group .composer-input {
    flex: 1;
}

.input-group .btn {
    padding: 8px 15px;
    border-radius: 10px;
    border: 1px solid #e2e8f0;
    background: white;
    color: #667eea;
    font-size: 0.85rem;
    cursor: pointer;
    white-space: nowrap;
}

.input-group .btn:hover {
    background: #667eea;
    color: white;
    border-color: #667eea;
}

/* Alert info box */
.alert-info {
    background: #dbeafe;
    border: 1px solid #3b82f6;
    color: #1e40af;
    border-radius: 10px;
    padding: 12px 15px;
    margin-bottom: 20px;
}

.alert-info .btn-outline-primary {
    border: 1px solid #3b82f6;
    color: #1e40af;
    background: white;
    padding: 5px 12px;
    border-radius: 8px;
    font-size: 0.85rem;
}

.alert-info .btn-outline-primary:hover {
    background: #3b82f6;
    color: white;
}
    </style>
</head>
<body>

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

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>Support Management</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                    <li class="breadcrumb-item active">Support</li>
                </ol>
            </nav>
        </div>

        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon"><i class="fas fa-ticket-alt"></i></div>
                <div class="stat-value" id="openTickets"><?php echo $stats['open']; ?></div>
                <div class="stat-label">Open Tickets</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon"><i class="fas fa-exclamation-triangle"></i></div>
                <div class="stat-value" id="urgentTickets"><?php echo $stats['urgent']; ?></div>
                <div class="stat-label">Urgent Tickets</div>
            </div>
        </div>

        <!-- Main Container -->
        <div class="support-container">
            <!-- Sidebar -->
            <div class="tickets-sidebar">
                <div class="sidebar-header">
                    <div class="filter-buttons">
                        <button class="filter-btn <?php echo $status_filter == 'all' ? 'active' : ''; ?>" onclick="filterTickets('status', 'all')">All</button>
                        <button class="filter-btn <?php echo $status_filter == 'open' ? 'active' : ''; ?>" onclick="filterTickets('status', 'open')">Open</button>
                        <button class="filter-btn <?php echo $status_filter == 'in_progress' ? 'active' : ''; ?>" onclick="filterTickets('status', 'in_progress')">In Progress</button>
                        <button class="filter-btn <?php echo $status_filter == 'resolved' ? 'active' : ''; ?>" onclick="filterTickets('status', 'resolved')">Resolved</button>
                    </div>
                    <div class="filter-buttons mt-2">
                        <button class="filter-btn <?php echo $priority_filter == 'all' ? 'active' : ''; ?>" onclick="filterTickets('priority', 'all')">All</button>
                        <button class="filter-btn <?php echo $priority_filter == 'urgent' ? 'active' : ''; ?>" onclick="filterTickets('priority', 'urgent')">Urgent</button>
                        <button class="filter-btn <?php echo $priority_filter == 'high' ? 'active' : ''; ?>" onclick="filterTickets('priority', 'high')">High</button>
                        <button class="filter-btn <?php echo $priority_filter == 'medium' ? 'active' : ''; ?>" onclick="filterTickets('priority', 'medium')">Medium</button>
                    </div>
                    <input type="text" class="search-input mt-3" placeholder="Search tickets..." id="searchInput" value="<?php echo htmlspecialchars($search); ?>">
                </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' : ''; ?>" 
                                 data-ticket-id="<?php echo $ticket['id']; ?>"
                                 onclick="selectTicket(<?php echo $ticket['id']; ?>)">
                                <div class="ticket-avatar">
                                    <img src="../uploads/profile/<?php echo $ticket['user_image'] ?: 'noprofil.jpg'; ?>" 
                                         onerror="this.src='../uploads/profiles/noprofil.jpg'">
                                </div>
                                <div class="ticket-info">
                                    <div class="ticket-subject"><?php echo htmlspecialchars(substr($ticket['subject'], 0, 30)); ?></div>
                                    <div class="ticket-meta">
                                        <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="small text-muted"><?php echo htmlspecialchars($ticket['user_name'] ?: 'User'); ?></div>
                                </div>
                                <?php if ($ticket['unread_user'] > 0): ?>
                                    <div class="unread-badge"><?php echo $ticket['unread_user']; ?></div>
                                <?php endif; ?>
                            </div>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Chat Area -->
            <div class="chat-area">
                <?php if ($current_ticket_data): ?>
                    <!-- Header -->
                    <div class="chat-header">
                        <div class="chat-user-info">
                            <div class="chat-user-avatar" onclick="showUserDetails(<?php echo $user_details['user_id']; ?>)">
                                <img src="../uploads/profile/<?php echo $user_details['image'] ?: 'noprofil.jpg'; ?>">
                            </div>
                            <div class="chat-user-details">
                                <h4><?php echo htmlspecialchars($user_details['name'] ?: 'User'); ?></h4>
                                <div class="chat-user-meta">
                                    <span><i class="fas fa-id-card"></i> <?php echo $user_details['user_id']; ?></span>
                                    <span><i class="fas fa-phone"></i> <?php echo $user_details['mobile'] ?: 'N/A'; ?></span>
                                </div>
                            </div>
                        </div>
                        <div class="chat-actions">
                            <?php if (!$current_ticket_data['assigned_to']): ?>
                                <button class="action-btn" onclick="assignToMe(<?php echo $current_ticket; ?>)" title="Assign to me">
                                    <i class="fas fa-hand-pointer"></i>
                                </button>
                            <?php endif; ?>
                            <select class="status-select" onchange="updateStatus(this.value)">
                                <option value="open" <?php echo $current_ticket_data['status'] == 'open' ? 'selected' : ''; ?>>Open</option>
                                <option value="in_progress" <?php echo $current_ticket_data['status'] == 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                                <option value="resolved" <?php echo $current_ticket_data['status'] == 'resolved' ? 'selected' : ''; ?>>Resolved</option>
                                <option value="closed" <?php echo $current_ticket_data['status'] == 'closed' ? 'selected' : ''; ?>>Closed</option>
                            </select>
                        </div>
                    </div>

                    <!-- Messages -->
                    <div class="chat-messages" id="chatMessages">
                        <?php foreach ($messages as $message): ?>
                            <div class="message-wrapper <?php echo $message['sender_type']; ?>" data-message-id="<?php echo $message['id']; ?>">
                                <div class="message-bubble <?php echo $message['sender_type']; ?>">
                                    <div class="message-sender">
                                        <i class="fas fa-<?php echo $message['sender_type'] == 'admin' ? 'shield-alt' : 'user'; ?>"></i>
                                        <?php echo $message['sender_type'] == 'admin' ? 'You' : htmlspecialchars($user_details['name'] ?: 'User'); ?>
                                    </div>
                                    <div class="message-text"><?php echo nl2br(htmlspecialchars($message['message'])); ?></div>
                                    <div class="message-footer">
                                        <span class="message-time"><?php echo date('h:i A', strtotime($message['created_at'])); ?></span>
                                        <?php if ($message['sender_type'] == 'admin'): ?>
                                            <span class="message-status">
                                                <i class="fas fa-<?php echo $message['is_read'] ? 'check-double read' : 'check unread'; ?>"></i>
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Footer -->
                    <div class="chat-footer">
                        <form id="replyForm">
                            <input type="hidden" name="ticket_id" value="<?php echo $current_ticket; ?>">
                            <div class="reply-form">
                                <div class="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>
                                <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>
                            
                            <?php if (mysqli_num_rows($templates_result) > 0): ?>
                                <div class="quick-replies">
                                    <?php while ($template = mysqli_fetch_assoc($templates_result)): ?>
                                        <button type="button" class="quick-reply-btn" 
                                                onclick="insertTemplate('<?php echo addslashes($template['content']); ?>')">
                                            <?php echo htmlspecialchars($template['title']); ?>
                                        </button>
                                    <?php endwhile; ?>
                                </div>
                            <?php endif; ?>
                        </form>
                    </div>
                <?php else: ?>
                    <div class="d-flex flex-column align-items-center justify-content-center h-100 text-muted">
                        <i class="fas fa-comments fa-4x mb-3"></i>
                        <h5>Select a ticket to start chatting</h5>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Draggable User Panel -->
<div class="user-panel" id="userPanel" style="display: none;">
    <div class="panel-header" id="panelHeader">
        <h5><i class="fas fa-user-circle me-2"></i>User Details</h5>
        <div class="panel-header-actions">
            <button class="panel-btn" onclick="toggleEmailComposer()" title="Send Email">
                <i class="fas fa-envelope"></i>
            </button>
            <button class="panel-btn" onclick="togglePanel()">
                <i class="fas fa-times"></i>
            </button>
        </div>
    </div>
    
    <div class="panel-tabs">
        <button class="panel-tab active" onclick="switchPanelTab('info')">
            <i class="fas fa-info-circle"></i> Info
        </button>
        <button class="panel-tab" onclick="switchPanelTab('edit')">
            <i class="fas fa-edit"></i> Edit
        </button>
        <button class="panel-tab" onclick="switchPanelTab('email')">
            <i class="fas fa-paper-plane"></i> Email
            <span class="email-badge" id="emailBadge" style="display: none;">⚡</span>
        </button>
        <button class="panel-tab" onclick="switchPanelTab('notes')">
            <i class="fas fa-sticky-note"></i> Notes
        </button>
    </div>
    
    <div class="panel-content" id="panelContent">
        <!-- Loading Spinner -->
        <div class="panel-loading" id="panelLoading">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        </div>
        
        <!-- Info Tab -->
        <div class="panel-tab-content active" id="infoTab">
            <!-- Content loaded via AJAX -->
        </div>
        
        <!-- Edit Tab -->
        <div class="panel-tab-content" id="editTab">
            <!-- Content loaded via AJAX -->
        </div>
        
        <!-- Email Tab -->
        <div class="panel-tab-content" id="emailTab">
            <!-- Content loaded via AJAX -->
        </div>
        
        <!-- Notes Tab -->
        <div class="panel-tab-content" id="notesTab">
            <!-- Content loaded via AJAX -->
        </div>
    </div>
</div>

<!-- Email Composer Modal -->
<!-- Email Composer Modal -->
<div class="email-composer" id="emailComposer" style="display: none;">
    <div class="composer-header" id="composerHeader">
        <h6><i class="fas fa-paper-plane me-2"></i>Compose Email</h6>
        <div>
            <button class="composer-close me-2" onclick="editRecipientEmail()" title="Edit Recipient Email">
                <i class="fas fa-pencil-alt"></i>
            </button>
            <button class="composer-close" onclick="toggleEmailComposer()">
                <i class="fas fa-times"></i>
            </button>
        </div>
    </div>
    
    <div class="composer-body">
        <form id="emailForm">
            <input type="hidden" name="user_id" id="emailUserId" value="">
            
            <div class="composer-field">
                <label>To:</label>
                <div class="input-group">
                    <input type="email" class="composer-input" id="emailTo" name="to_email" readonly required>
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="editRecipientEmail()">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                </div>
                <small class="text-muted">Click edit to change recipient email</small>
            </div>
            
            <div class="composer-field">
                <label>Subject:</label>
                <input type="text" class="composer-input" id="emailSubject" name="subject" placeholder="Email subject" required>
            </div>
            
            <div class="composer-field">
                <label>Template:</label>
                <select class="composer-select" id="emailTemplate" onchange="loadEmailTemplate()">
                    <option value="">Select a template...</option>
                    <option value="welcome">👋 Welcome Message</option>
                    <option value="thankyou">🙏 Thank You</option>
                    <option value="update">✅ Account Updated</option>
                    <option value="kyc">🔐 KYC Verification</option>
                    <option value="withdrawal">💰 Withdrawal Processed</option>
                    <option value="pin">🔑 PIN Generated</option>
                    <option value="support">🎫 Support Response</option>
                </select>
            </div>
            
            <div class="composer-field">
                <label>Message:</label>
                <textarea class="composer-textarea" id="emailMessage" name="message" rows="10" required></textarea>
            </div>
            
            <div class="composer-field">
                <label>Placeholders:</label>
                <div class="placeholder-buttons">
                    <button type="button" class="placeholder-btn" onclick="insertPlaceholder('{user_name}')">
                        <i class="fas fa-user"></i> Name
                    </button>
                    <button type="button" class="placeholder-btn" onclick="insertPlaceholder('{user_id}')">
                        <i class="fas fa-id-card"></i> User ID
                    </button>
                    <button type="button" class="placeholder-btn" onclick="insertPlaceholder('{user_email}')">
                        <i class="fas fa-envelope"></i> Email
                    </button>
                    <button type="button" class="placeholder-btn" onclick="insertPlaceholder('{user_mobile}')">
                        <i class="fas fa-phone"></i> Mobile
                    </button>
                    <button type="button" class="placeholder-btn" onclick="insertPlaceholder('{company_name}')">
                        <i class="fas fa-building"></i> Company
                    </button>
                    <button type="button" class="placeholder-btn" onclick="insertPlaceholder('{date}')">
                        <i class="fas fa-calendar"></i> Date
                    </button>
                    <button type="button" class="placeholder-btn" onclick="insertPlaceholder('{ticket_id}')">
                        <i class="fas fa-ticket"></i> Ticket ID
                    </button>
                </div>
            </div>
            
            <div class="composer-actions">
                <button type="button" class="composer-btn secondary" onclick="toggleEmailComposer()">
                    Cancel
                </button>
                <button type="submit" class="composer-btn primary" id="sendEmailBtn">
                    <i class="fas fa-paper-plane me-2"></i>Send Email
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Add CSS for the panel -->
<style>
/* Draggable User Panel */
.user-panel {
    position: fixed;
    top: 100px;
    right: 20px;
    width: 400px;
    height: 600px;
    background: white;
    border-radius: 20px;
    box-shadow: 0 20px 40px rgba(0,0,0,0.15);
    z-index: 9999;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    border: 1px solid #e2e8f0;
    resize: both;
    min-width: 350px;
    min-height: 500px;
    max-width: 800px;
    max-height: 800px;
}

.panel-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 15px 20px;
    cursor: move;
    display: flex;
    align-items: center;
    justify-content: space-between;
    user-select: none;
}

.panel-header h5 {
    margin: 0;
    font-size: 1rem;
    font-weight: 600;
}

.panel-header-actions {
    display: flex;
    gap: 10px;
}

.panel-btn {
    background: rgba(255,255,255,0.2);
    border: none;
    color: white;
    width: 30px;
    height: 30px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
}

.panel-btn:hover {
    background: rgba(255,255,255,0.3);
    transform: scale(1.05);
}

.panel-tabs {
    display: flex;
    background: #f8fafc;
    border-bottom: 1px solid #e2e8f0;
    padding: 5px;
}

.panel-tab {
    flex: 1;
    padding: 10px;
    background: none;
    border: none;
    border-radius: 10px;
    font-size: 0.85rem;
    font-weight: 500;
    color: #64748b;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
    position: relative;
}

.panel-tab:hover {
    background: #e2e8f0;
    color: #1e293b;
}

.panel-tab.active {
    background: white;
    color: #667eea;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.email-badge {
    position: absolute;
    top: 2px;
    right: 2px;
    font-size: 0.7rem;
}

.panel-content {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: white;
}

.panel-tab-content {
    display: none;
}

.panel-tab-content.active {
    display: block;
}

.panel-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

/* Info Tab Styles */
.info-section {
    margin-bottom: 25px;
}

.info-title {
    font-size: 0.9rem;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 2px solid #e2e8f0;
}

.info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
}

.info-item {
    background: #f8fafc;
    border-radius: 10px;
    padding: 12px;
}

.info-label {
    font-size: 0.7rem;
    color: #64748b;
    margin-bottom: 5px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.info-value {
    font-size: 0.9rem;
    font-weight: 600;
    color: #1e293b;
    word-break: break-word;
}

.user-avatar-large {
    width: 80px;
    height: 80px;
    border-radius: 20px;
    margin: 0 auto 15px;
    overflow: hidden;
    border: 3px solid #667eea;
}

.user-avatar-large img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.user-name-large {
    text-align: center;
    font-size: 1.2rem;
    font-weight: 700;
    margin-bottom: 5px;
}

.user-id-large {
    text-align: center;
    color: #64748b;
    margin-bottom: 20px;
}

/* Edit Tab Styles */
.edit-form .form-group {
    margin-bottom: 15px;
}

.edit-form label {
    font-size: 0.85rem;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 5px;
    display: block;
}

.edit-form .form-control {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    font-size: 0.9rem;
    transition: all 0.2s;
}

.edit-form .form-control:focus {
    border-color: #667eea;
    outline: none;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.edit-form select.form-control {
    height: 42px;
}

.save-btn {
    width: 100%;
    padding: 12px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    margin-top: 10px;
}

.save-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
}

/* Email Tab Styles */
.email-stats {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    margin-bottom: 20px;
}

.email-stat-item {
    background: #f8fafc;
    border-radius: 10px;
    padding: 12px;
    text-align: center;
}

.email-stat-value {
    font-size: 1.2rem;
    font-weight: 700;
    color: #667eea;
    margin-bottom: 5px;
}

.email-stat-label {
    font-size: 0.7rem;
    color: #64748b;
    text-transform: uppercase;
}

.template-list {
    max-height: 300px;
    overflow-y: auto;
}

.template-item {
    padding: 12px;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    margin-bottom: 8px;
    cursor: pointer;
    transition: all 0.2s;
}

.template-item:hover {
    border-color: #667eea;
    background: #f8fafc;
}

.template-item h6 {
    font-size: 0.9rem;
    font-weight: 600;
    margin-bottom: 5px;
    color: #1e293b;
}

.template-item p {
    font-size: 0.8rem;
    color: #64748b;
    margin: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* Email Composer Modal */
.email-composer {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 600px;
    max-width: 90vw;
    background: white;
    border-radius: 20px;
    box-shadow: 0 30px 60px rgba(0,0,0,0.3);
    z-index: 10000;
    overflow: hidden;
}

.composer-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 15px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: move;
}

.composer-header h6 {
    margin: 0;
    font-size: 1rem;
    font-weight: 600;
}

.composer-close {
    background: rgba(255,255,255,0.2);
    border: none;
    color: white;
    width: 30px;
    height: 30px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.composer-body {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
}

.composer-field {
    margin-bottom: 15px;
}

.composer-field label {
    font-size: 0.85rem;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 5px;
    display: block;
}

.composer-input,
.composer-select,
.composer-textarea {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    font-size: 0.9rem;
}

.composer-textarea {
    resize: vertical;
    min-height: 150px;
    font-family: inherit;
}

.composer-input:focus,
.composer-select:focus,
.composer-textarea:focus {
    border-color: #667eea;
    outline: none;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.placeholder-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    margin-top: 5px;
}

.placeholder-btn {
    padding: 5px 10px;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-size: 0.8rem;
    color: #64748b;
    cursor: pointer;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 5px;
}

.placeholder-btn:hover {
    background: #667eea;
    color: white;
    border-color: #667eea;
}

.composer-actions {
    display: flex;
    gap: 10px;
    margin-top: 20px;
}

.composer-btn {
    flex: 1;
    padding: 12px;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
}

.composer-btn.primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.composer-btn.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
}

.composer-btn.secondary {
    background: #f8fafc;
    color: #64748b;
    border: 1px solid #e2e8f0;
}

.composer-btn.secondary:hover {
    background: #e2e8f0;
}

/* Success/Error Messages */
.alert-message {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 15px 25px;
    border-radius: 50px;
    color: white;
    font-weight: 500;
    z-index: 10001;
    animation: slideInRight 0.3s;
}

.alert-success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
}

.alert-error {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
}

@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

/* Responsive */
@media (max-width: 768px) {
    .user-panel {
        width: 90%;
        right: 5%;
        left: 5%;
    }
    
    .email-composer {
        width: 95%;
    }
}
    
    /* Ensure line breaks work in all email clients */
.content br {
    display: block !important;
    content: "" !important;
    margin: 5px 0 !important;
}

.content p {
    white-space: pre-line;
    margin: 10px 0 !important;
}
</style>
            
        </div>
    </main>

    <!-- New Message Notification -->
    <div id="newMessageNotification" class="new-message-notification" style="display: none;">
        <i class="fas fa-envelope"></i>
        <span>New message</span>
        <span class="badge bg-light text-primary" id="newMessageCount">1</span>
    </div>

    <!-- Footer -->
    <?php include 'includes/footer.php'; ?>

    <!-- Scripts -->
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Configuration
        const CURRENT_TICKET = <?php echo $current_ticket ?: 0; ?>;
        let LAST_MESSAGE_ID = <?php echo $last_message_id; ?>;
        let NEW_MESSAGE_COUNT = 0;
        let POLLING_ACTIVE = true;
        let searchTimeout;

        // Use a flag to prevent multiple submissions
let isEmailSending = false;

// Set up the form submission handler once
document.addEventListener('DOMContentLoaded', function() {
    const emailForm = document.getElementById('emailForm');
    if (!emailForm) return;
    
    // Remove any existing listeners by cloning
    const newForm = emailForm.cloneNode(true);
    emailForm.parentNode.replaceChild(newForm, emailForm);
    
    // Add fresh listener
    newForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        // Prevent double submission
        if (isEmailSending) {
            console.log('Email already sending, please wait...');
            return;
        }
        
        // Get form values
        const userId = document.getElementById('emailUserId')?.value;
        const toEmail = document.getElementById('emailTo')?.value;
        const subject = document.getElementById('emailSubject')?.value.trim();
        const message = document.getElementById('emailMessage')?.value.trim();
        
        // Validate
        if (!userId || !toEmail || !subject || !message) {
            showAlert('Please fill in all fields', 'error');
            return;
        }
        
        // Format the message with enhanced HTML
        const formattedMessage = formatEmailContent(message);
        
        // Create a preview to debug
        console.log('SENDING EMAIL:');
        console.log('To:', toEmail);
        console.log('Subject:', subject);
        console.log('Formatted message:', formattedMessage);
        
        // Show a preview in a small popup for debugging (remove in production)
        const debugPreview = confirm('Check console for formatted message. Send email?');
        if (!debugPreview) return;
        
        // Set sending flag
        isEmailSending = true;
        
        // Disable button
        const sendBtn = document.getElementById('sendEmailBtn');
        const originalText = sendBtn.innerHTML;
        sendBtn.disabled = true;
        sendBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';
        
        try {
            // Create form data
            const formData = new FormData();
            formData.append('user_id', userId);
            formData.append('to_email', toEmail);
            formData.append('subject', subject);
            formData.append('message', formattedMessage); // Send formatted HTML
            formData.append('raw_message', message); // Also send raw for logging
            
            const response = await fetch('ajax/send_email.php', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                showAlert('Email sent successfully!', 'success');
                // Clear form
                document.getElementById('emailSubject').value = '';
                document.getElementById('emailMessage').value = '';
                document.getElementById('emailTemplate').value = '';
                toggleEmailComposer();
            } else {
                showAlert('Error: ' + (result.error || 'Unknown error'), 'error');
            }
        } catch (error) {
            console.error('Send error:', error);
            showAlert('Failed to send email: ' + error.message, 'error');
        } finally {
            // Reset sending flag
            isEmailSending = false;
            sendBtn.disabled = false;
            sendBtn.innerHTML = originalText;
        }
    });
});

        // ========== TICKET FUNCTIONS ==========
        
        function selectTicket(ticketId) {
            window.location.href = `support.php?ticket=${ticketId}&status=<?php echo $status_filter; ?>&priority=<?php echo $priority_filter; ?>&search=<?php echo urlencode($search); ?>`;
        }

        function filterTickets(type, value) {
            const url = new URL(window.location.href);
            url.searchParams.set(type, value);
            url.searchParams.delete('ticket');
            window.location.href = url.toString();
        }

        // Search with debounce
        document.getElementById('searchInput')?.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                const url = new URL(window.location.href);
                url.searchParams.set('search', this.value);
                url.searchParams.delete('ticket');
                window.location.href = url.toString();
            }, 500);
        });

        // ========== MESSAGE FUNCTIONS ==========

        // Send message
        document.getElementById('replyForm')?.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();
            
            if (!message) return;
            
            // Disable send button
            const sendBtn = document.getElementById('sendBtn');
            sendBtn.disabled = true;
            sendBtn.innerHTML = '<div class="loading-spinner"></div>';
            
            const formData = new FormData(this);
            formData.append('reply_ticket', '1');
            
            try {
                const response = await fetch('support.php', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // Add message to chat
                    addOwnMessage(message, result.message_id, result.time);
                    
                    // Clear input
                    messageInput.value = '';
                    messageInput.style.height = 'auto';
                    
                    // Update last message ID
                    LAST_MESSAGE_ID = result.message_id;
                    
                    // Scroll to bottom
                    scrollToBottom();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                console.error('Error:', error);
                alert('Failed to send message');
            } finally {
                sendBtn.disabled = false;
                sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i>';
            }
        });

        // Add own message
        function addOwnMessage(message, messageId, time) {
            const chatMessages = document.getElementById('chatMessages');
            const messageHtml = `
                <div class="message-wrapper admin" data-message-id="${messageId}">
                    <div class="message-bubble admin">
                        <div class="message-sender"><i class="fas fa-shield-alt"></i> You</div>
                        <div class="message-text">${message.replace(/\n/g, '<br>')}</div>
                        <div class="message-footer">
                            <span class="message-time">Just now</span>
                            <span class="message-status"><i class="fas fa-check unread"></i></span>
                        </div>
                    </div>
                </div>
            `;
            chatMessages.insertAdjacentHTML('beforeend', messageHtml);
        }

        // Receive new message
        function receiveNewMessage(message) {
            const chatMessages = document.getElementById('chatMessages');
            
            // Check if already exists
            if (document.querySelector(`[data-message-id="${message.id}"]`)) {
                return;
            }
            
            const messageHtml = `
                <div class="message-wrapper user" data-message-id="${message.id}">
                    <div class="message-bubble user">
                        <div class="message-sender"><i class="fas fa-user"></i> User</div>
                        <div class="message-text">${message.message.replace(/\n/g, '<br>')}</div>
                        <div class="message-footer">
                            <span class="message-time">${message.time}</span>
                        </div>
                    </div>
                </div>
            `;
            
            chatMessages.insertAdjacentHTML('beforeend', messageHtml);
            scrollToBottom();
            
            // Show notification if not at bottom
            const container = document.getElementById('chatMessages');
            const isAtBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 100;
            
            if (!isAtBottom) {
                showNotification();
            }
            
            // Play sound
            playNotificationSound();
        }

        // ========== POLLING ==========

        function startPolling() {
            if (!POLLING_ACTIVE || !CURRENT_TICKET) return;
            pollMessages();
        }

        async function pollMessages() {
            try {
                const response = await fetch(`ajax/poll_messages.php?ticket_id=${CURRENT_TICKET}&last_id=${LAST_MESSAGE_ID}`);
                const data = await response.json();
                
                if (data.success && data.messages && data.messages.length > 0) {
                    data.messages.forEach(message => {
                        if (message.sender_type === 'user') {
                            receiveNewMessage(message);
                            if (message.id > LAST_MESSAGE_ID) {
                                LAST_MESSAGE_ID = message.id;
                            }
                        }
                    });
                }
                
                setTimeout(pollMessages, 2000);
                
            } catch (error) {
                console.error('Polling error:', error);
                setTimeout(pollMessages, 5000);
            }
        }

        // ========== NOTIFICATIONS ==========

        function showNotification() {
            const notification = document.getElementById('newMessageNotification');
            const countSpan = document.getElementById('newMessageCount');
            
            NEW_MESSAGE_COUNT++;
            countSpan.textContent = NEW_MESSAGE_COUNT;
            notification.style.display = 'flex';
            
            setTimeout(() => {
                NEW_MESSAGE_COUNT--;
                if (NEW_MESSAGE_COUNT <= 0) {
                    notification.style.display = 'none';
                } else {
                    countSpan.textContent = NEW_MESSAGE_COUNT;
                }
            }, 3000);
        }

        document.getElementById('newMessageNotification')?.addEventListener('click', function() {
            scrollToBottom();
            this.style.display = 'none';
            NEW_MESSAGE_COUNT = 0;
        });

        function playNotificationSound() {
            const audio = new Audio('assets/sounds/notification.mp3');
            audio.play().catch(() => {});
        }

        // ========== UTILITY FUNCTIONS ==========

        function scrollToBottom() {
            const chatMessages = document.getElementById('chatMessages');
            if (chatMessages) {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
        }

        function insertTemplate(content) {
            document.getElementById('messageInput').value = content;
            document.getElementById('messageInput').focus();
        }

        async function updateStatus(status) {
            if (!CURRENT_TICKET) return;
            
            const formData = new FormData();
            formData.append('ticket_id', CURRENT_TICKET);
            formData.append('status', status);
            formData.append('update_status', '1');
            
            try {
                await fetch('support.php', {
                    method: 'POST',
                    body: formData
                });
            } catch (error) {
                console.error('Error updating status:', error);
            }
        }

        async function assignToMe(ticketId) {
            if (!confirm('Assign this ticket to yourself?')) return;
            
            try {
                const response = await fetch(`support.php?assign=${ticketId}`);
                const result = await response.json();
                if (result.success) {
                    location.reload();
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }

        function showUserDetails(userId) {
            window.open(`users.php?view=${userId}`, '_blank');
        }

        // Auto-resize textarea
        document.getElementById('messageInput')?.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });

        // Cleanup
        window.addEventListener('beforeunload', function() {
            POLLING_ACTIVE = false;
        });
    </script>
    
    <script>
// User Panel functionality
let currentUserId = null;
let panelDraggable = null;
let composerDraggable = null;

// Initialize panel
function initPanel() {
    // Make panel draggable
    const panel = document.getElementById('userPanel');
    const header = document.getElementById('panelHeader');
    
    let isDragging = false;
    let offsetX, offsetY;
    
    header.addEventListener('mousedown', startDragging);
    
    function startDragging(e) {
        if (e.target.tagName === 'BUTTON' || e.target.tagName === 'I') return;
        
        isDragging = true;
        offsetX = e.clientX - panel.offsetLeft;
        offsetY = e.clientY - panel.offsetTop;
        
        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', stopDragging);
        
        panel.style.transition = 'none';
    }
    
    function drag(e) {
        if (!isDragging) return;
        
        let newX = e.clientX - offsetX;
        let newY = e.clientY - offsetY;
        
        // Keep panel within window bounds
        newX = Math.max(0, Math.min(newX, window.innerWidth - panel.offsetWidth));
        newY = Math.max(0, Math.min(newY, window.innerHeight - panel.offsetHeight));
        
        panel.style.left = newX + 'px';
        panel.style.top = newY + 'px';
        panel.style.right = 'auto';
    }
    
    function stopDragging() {
        isDragging = false;
        panel.style.transition = '';
        document.removeEventListener('mousemove', drag);
        document.removeEventListener('mouseup', stopDragging);
    }
}

// Toggle panel
function togglePanel() {
    const panel = document.getElementById('userPanel');
    if (panel.style.display === 'none') {
        panel.style.display = 'flex';
        panel.style.top = '100px';
        panel.style.right = '20px';
        panel.style.left = 'auto';
    } else {
        panel.style.display = 'none';
    }
}

// Show user details
function showUserDetails(userId) {
    currentUserId = userId;
    const panel = document.getElementById('userPanel');
    panel.style.display = 'flex';
    
    // Load user details
    loadPanelTab('info');
}

// Load panel tab
function loadPanelTab(tab) {
    if (!currentUserId) return;
    
    const loading = document.getElementById('panelLoading');
    const content = document.getElementById(tab + 'Tab');
    
    loading.style.display = 'flex';
    
    let url = '';
    switch(tab) {
        case 'info':
            url = `ajax/get_user_details.php?user_id=${currentUserId}`;
            break;
        case 'edit':
            url = `ajax/get_edit_form.php?user_id=${currentUserId}`;
            break;
        case 'email':
            url = `ajax/get_email_tab.php?user_id=${currentUserId}`;
            break;
        case 'notes':
            url = `ajax/get_notes.php?ticket_id=${CURRENT_TICKET}`;
            break;
    }
    
    fetch(url)
        .then(response => response.text())
        .then(html => {
            content.innerHTML = html;
            loading.style.display = 'none';
        })
        .catch(error => {
            console.error('Error loading tab:', error);
            loading.style.display = 'none';
        });
}

// Switch panel tab
function switchPanelTab(tab) {
    // Update active tab
    document.querySelectorAll('.panel-tab').forEach(t => t.classList.remove('active'));
    event.target.closest('.panel-tab').classList.add('active');
    
    // Hide all tab contents
    document.querySelectorAll('.panel-tab-content').forEach(c => c.classList.remove('active'));
    
    // Show selected tab
    document.getElementById(tab + 'Tab').classList.add('active');
    
    // Load content if needed
    loadPanelTab(tab);
}

// Email Composer functionality
function toggleEmailComposer() {
    const composer = document.getElementById('emailComposer');
    if (composer.style.display === 'none') {
        composer.style.display = 'block';
        initComposerDraggable();
    } else {
        composer.style.display = 'none';
    }
}

function initComposerDraggable() {
    const composer = document.getElementById('emailComposer');
    const header = document.getElementById('composerHeader');
    
    let isDragging = false;
    let offsetX, offsetY;
    
    header.addEventListener('mousedown', startDragging);
    
    function startDragging(e) {
        if (e.target.tagName === 'BUTTON' || e.target.tagName === 'I') return;
        
        isDragging = true;
        offsetX = e.clientX - composer.offsetLeft;
        offsetY = e.clientY - composer.offsetTop;
        
        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', stopDragging);
        
        composer.style.transition = 'none';
    }
    
    function drag(e) {
        if (!isDragging) return;
        
        let newX = e.clientX - offsetX;
        let newY = e.clientY - offsetY;
        
        newX = Math.max(0, Math.min(newX, window.innerWidth - composer.offsetWidth));
        newY = Math.max(0, Math.min(newY, window.innerHeight - composer.offsetHeight));
        
        composer.style.left = newX + 'px';
        composer.style.top = newY + 'px';
        composer.style.transform = 'none';
    }
    
    function stopDragging() {
        isDragging = false;
        composer.style.transition = '';
        document.removeEventListener('mousemove', drag);
        document.removeEventListener('mouseup', stopDragging);
    }
}

// Global variables
let currentComposerUserId = null;
let currentComposerEmail = null;
let currentComposerName = null;

// Open email composer with user details
function openEmailComposer(userId, email, name) {
    console.log('Opening composer for:', userId, email, name); // Debug log
    
    currentComposerUserId = userId;
    currentComposerEmail = email;
    currentComposerName = name;
    
    // Set form values
    document.getElementById('emailUserId').value = userId;
    document.getElementById('emailTo').value = email;
    document.getElementById('emailSubject').value = '';
    document.getElementById('emailMessage').value = '';
    document.getElementById('emailTemplate').value = '';
    
    // Show the composer
    toggleEmailComposer();
}

// Toggle email composer
function toggleEmailComposer() {
    const composer = document.getElementById('emailComposer');
    if (composer.style.display === 'none' || composer.style.display === '') {
        composer.style.display = 'block';
        initComposerDraggable();
    } else {
        composer.style.display = 'none';
    }
}

// Handle email form submission
document.getElementById('emailForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    // Get form data
    const formData = new FormData(this);
    
    // Debug: Log form data
    for (let pair of formData.entries()) {
        console.log(pair[0] + ': ' + pair[1]);
    }
    
    // Validate manually
    const userId = document.getElementById('emailUserId').value;
    const toEmail = document.getElementById('emailTo').value;
    const subject = document.getElementById('emailSubject').value.trim();
    const message = document.getElementById('emailMessage').value.trim();
    
    if (!userId || !toEmail || !subject || !message) {
        showAlert('Please fill in all fields', 'error');
        return;
    }
    
    // Disable button
    const sendBtn = document.getElementById('sendEmailBtn');
    const originalText = sendBtn.innerHTML;
    sendBtn.disabled = true;
    sendBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';
    
    try {
        const response = await fetch('ajax/send_email.php', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        console.log('Send result:', result); // Debug log
        
        if (result.success) {
            showAlert('Email sent successfully!', 'success');
            toggleEmailComposer();
        } else {
            showAlert('Error: ' + (result.error || 'Unknown error'), 'error');
        }
    } catch (error) {
        console.error('Send error:', error);
        showAlert('Failed to send email: ' + error.message, 'error');
    } finally {
        sendBtn.disabled = false;
        sendBtn.innerHTML = originalText;
    }
});

// Load email template
function loadEmailTemplate() {
    const template = document.getElementById('emailTemplate').value;
    const toEmail = document.getElementById('emailTo').value;
    const userId = document.getElementById('emailUserId').value;
    const userName = toEmail ? toEmail.split('@')[0] : 'User';
    
    // Get company name from PHP
    const companyName = '<?php 
        require_once 'includes/company_config.php';
        $conn = getConnection();
        $company = getCompanyDetails($conn);
        echo addslashes($company['name']);
    ?>';
    
    let subject = '';
    let message = '';
    
    switch(template) {
        case 'welcome':
            subject = 'Welcome to ' + companyName + '!';
            message = `Dear {user_name},\n\nWelcome to ${companyName}! We're excited to have you on board.\n\nYour account has been successfully created with User ID: {user_id}\n\nBest regards,\n${companyName} Team`;
            break;
            
        case 'thankyou':
            subject = 'Thank You from ' + companyName;
            message = `Dear {user_name},\n\nThank you for being a valued member of ${companyName}.\n\nWe appreciate your trust in us.\n\nBest regards,\n${companyName} Team`;
            break;
            
        case 'update':
            subject = 'Account Updated Successfully';
            message = `Dear {user_name},\n\nYour account details have been successfully updated on {date}.\n\nIf you did not make these changes, please contact ${companyName} support immediately.\n\nBest regards,\n${companyName} Team`;
            break;
            
        case 'kyc':
            subject = 'KYC Verification Required';
            message = `Dear {user_name},\n\nPlease complete your KYC verification to continue using all features of ${companyName}.\n\nRequired documents:\n- PAN Card\n- Aadhaar Card\n- Bank Details\n\nUpload documents in your profile.\n\nBest regards,\n${companyName} Team`;
            break;
            
        case 'withdrawal':
            subject = 'Withdrawal Processed Successfully';
            message = `Dear {user_name},\n\nYour withdrawal request has been processed successfully by ${companyName}.\n\nAmount: ₹{amount}\nDate: {date}\n\nIt will reflect in your account within 2-3 business days.\n\nBest regards,\n${companyName} Team`;
            break;
            
        case 'pin':
            subject = 'PIN Generated Successfully';
            message = `Dear {user_name},\n\nYour E-PIN has been generated successfully by ${companyName}.\n\nPIN: {pin}\nAmount: ₹{amount}\n\nUse this PIN for registration.\n\nBest regards,\n${companyName} Team`;
            break;
            
        case 'support':
            subject = 'Support Ticket Update';
            message = `Dear {user_name},\n\nYour support ticket #{ticket_id} has been updated.\n\nOur team at ${companyName} has responded to your query. Please check your support center for details.\n\nBest regards,\n${companyName} Support Team`;
            break;
            
        default:
            return;
    }
    
    // Replace placeholders
    message = message.replace(/{user_name}/g, userName);
    message = message.replace(/{user_id}/g, userId);
    message = message.replace(/{date}/g, new Date().toLocaleDateString());
    message = message.replace(/{company_name}/g, companyName);
    
    document.getElementById('emailSubject').value = subject;
    document.getElementById('emailMessage').value = message;
}

// Insert placeholder into message
function insertPlaceholder(placeholder) {
    const messageArea = document.getElementById('emailMessage');
    const start = messageArea.selectionStart;
    const end = messageArea.selectionEnd;
    const text = messageArea.value;
    
    messageArea.value = text.substring(0, start) + placeholder + text.substring(end);
    messageArea.focus();
    messageArea.selectionStart = start + placeholder.length;
    messageArea.selectionEnd = start + placeholder.length;
}

// Show alert message
function showAlert(message, type) {
    const alert = document.createElement('div');
    alert.className = `alert-message alert-${type}`;
    alert.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
        ${message}
        <button type="button" class="btn-close btn-close-white ms-3" onclick="this.parentElement.remove()"></button>
    `;
    
    document.body.appendChild(alert);
    
    setTimeout(() => {
        if (alert.parentElement) alert.remove();
    }, 5000);
}

// Handle email form submission
document.getElementById('emailForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const sendBtn = document.getElementById('sendEmailBtn');
    
    sendBtn.disabled = true;
    sendBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';
    
    try {
        const response = await fetch('ajax/send_email.php', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            showAlert('Email sent successfully!', 'success');
            toggleEmailComposer();
        } else {
            showAlert('Error: ' + result.error, 'error');
        }
    } catch (error) {
        showAlert('Failed to send email', 'error');
    } finally {
        sendBtn.disabled = false;
        sendBtn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Send Email';
    }
});

// Handle edit form submission
document.addEventListener('submit', function(e) {
    if (e.target.id === 'editUserForm') {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        formData.append('action', 'update_user');
        
        fetch('ajax/update_user.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showAlert('User details updated successfully!', 'success');
                loadPanelTab('info'); // Refresh info tab
            } else {
                showAlert('Error: ' + result.error, 'error');
            }
        })
        .catch(error => {
            showAlert('Failed to update user', 'error');
        });
    }
});

// Show alert message
function showAlert(message, type) {
    const alert = document.createElement('div');
    alert.className = `alert-message alert-${type}`;
    alert.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
        ${message}
    `;
    
    document.body.appendChild(alert);
    
    setTimeout(() => {
        alert.remove();
    }, 3000);
}

// Initialize panel when ticket is selected
if (CURRENT_TICKET) {
    initPanel();
    
    // Add button to show panel
    const chatHeader = document.querySelector('.chat-header .chat-user-info');
    if (chatHeader) {
        const viewDetailsBtn = document.createElement('button');
        viewDetailsBtn.className = 'btn btn-sm btn-outline-primary ms-2';
        viewDetailsBtn.innerHTML = '<i class="fas fa-user"></i> View Details';
        viewDetailsBtn.onclick = () => showUserDetails(<?php echo $user_details['user_id'] ?? 0; ?>);
        chatHeader.appendChild(viewDetailsBtn);
    }
}
        
        // Edit recipient email
function editRecipientEmail() {
    const emailInput = document.getElementById('emailTo');
    const currentEmail = emailInput.value;
    
    // Create a prompt for email editing
    const newEmail = prompt('Enter recipient email address:', currentEmail);
    
    if (newEmail && newEmail !== currentEmail) {
        // Basic email validation
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (emailRegex.test(newEmail)) {
            emailInput.value = newEmail;
            showAlert('Email updated successfully', 'success');
        } else {
            showAlert('Please enter a valid email address', 'error');
        }
    }
}

// Also add a direct edit in the email tab
function editUserEmail(userId, currentEmail) {
    const newEmail = prompt('Edit user email address:', currentEmail);
    
    if (newEmail && newEmail !== currentEmail) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (emailRegex.test(newEmail)) {
            // Update email via AJAX
            fetch('ajax/update_user_email.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `user_id=${userId}&email=${encodeURIComponent(newEmail)}`
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showAlert('Email updated successfully', 'success');
                    // Update the email in the composer if open
                    document.getElementById('emailTo').value = newEmail;
                } else {
                    showAlert('Error: ' + result.error, 'error');
                }
            })
            .catch(error => {
                showAlert('Failed to update email', 'error');
            });
        } else {
            showAlert('Please enter a valid email address', 'error');
        }
    }
}
        
        let isSending = false;

// Handle email form submission with double-submit prevention
document.getElementById('emailForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    // Prevent double submission
    if (isSending) {
        console.log('Already sending email...');
        return;
    }
    
    // Get form data
    const formData = new FormData(this);
    
    // Validate manually
    const userId = document.getElementById('emailUserId').value;
    const toEmail = document.getElementById('emailTo').value;
    const subject = document.getElementById('emailSubject').value.trim();
    const message = document.getElementById('emailMessage').value.trim();
    
    if (!userId || !toEmail || !subject || !message) {
        showAlert('Please fill in all fields', 'error');
        return;
    }
    
    // Disable button and set sending flag
    isSending = true;
    const sendBtn = document.getElementById('sendEmailBtn');
    const originalText = sendBtn.innerHTML;
    sendBtn.disabled = true;
    sendBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';
    
    try {
        const response = await fetch('ajax/send_email.php', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        
        const result = await response.json();
        
        if (result.success) {
            showAlert('Email sent successfully!', 'success');
            // Clear form
            document.getElementById('emailSubject').value = '';
            document.getElementById('emailMessage').value = '';
            document.getElementById('emailTemplate').value = '';
            toggleEmailComposer();
        } else {
            showAlert('Error: ' + (result.error || 'Unknown error'), 'error');
        }
    } catch (error) {
        console.error('Send error:', error);
        showAlert('Failed to send email: ' + error.message, 'error');
    } finally {
        // Reset button and sending flag
        isSending = false;
        sendBtn.disabled = false;
        sendBtn.innerHTML = originalText;
    }
});
    // Add this at the very top of your JavaScript section
function formatEmailContent(text) {
    if (!text) return '';
    
    console.log('Original text:', text);
    
    // Step 1: Decode any HTML entities
    let decoded = text.replace(/&lt;/g, '<')
                     .replace(/&gt;/g, '>')
                     .replace(/&amp;/g, '&')
                     .replace(/&quot;/g, '"')
                     .replace(/&#039;/g, "'")
                     .replace(/\\r\\n/g, '\n')
                     .replace(/\\n/g, '\n');
    
    // Step 2: Split into lines
    let lines = decoded.split(/\r?\n/);
    let html = '';
    let inParagraph = false;
    
    for (let i = 0; i < lines.length; i++) {
        let line = lines[i].trim();
        
        if (line === '') {
            // Empty line - end current paragraph if we're in one
            if (inParagraph) {
                html += '</p>';
                inParagraph = false;
            }
            // Add a blank line (visible space)
            html += '<p style="margin: 10px 0;">&nbsp;</p>';
        } else {
            // Non-empty line
            if (!inParagraph) {
                // Start a new paragraph
                html += '<p style="margin: 10px 0; line-height: 1.6;">';
                inParagraph = true;
            } else {
                // Add a line break within the paragraph
                html += '<br>';
            }
            
            // Make text between ** bold
            line = line.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            
            // Add the line content
            html += line;
        }
    }
    
    // Close any open paragraph
    if (inParagraph) {
        html += '</p>';
    }
    
    console.log('Final HTML:', html);
    return html;
}    
        // Remove all existing event listeners from the form
const emailForm = document.getElementById('emailForm');
if (emailForm) {
    // Clone and replace the form to remove all listeners
    const newForm = emailForm.cloneNode(true);
    emailForm.parentNode.replaceChild(newForm, emailForm);
}
</script>
</body>
</html>
<?php mysqli_close($conn); ?>