<?php
// customer/support.php - نسخة مصححة ومحسنة
require_once 'config.php';

// التحقق من تسجيل الدخول
if (!checkCustomerAuth(false)) {
    echo json_encode(['success' => false, 'message' => 'الرجاء تسجيل الدخول أولاً']);
    exit();
}

$customer_id = $_SESSION['customer_id'];

// ============================================
// معالجة طلبات AJAX
// ============================================
if (isset($_GET['action']) || isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    try {
        // 1. جلب التذاكر
        if (isset($_GET['action']) && $_GET['action'] == 'get_tickets') {
            $stmt = $conn->prepare("
                SELECT 
                    t.*,
                    (SELECT COUNT(*) FROM ticket_messages WHERE ticket_id = t.id AND sender_type = 'admin' AND is_read = 0) as unread_count,
                    (SELECT message FROM ticket_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_message,
                    (SELECT created_at FROM ticket_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_message_time,
                    (SELECT sender_type FROM ticket_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_sender
                FROM customer_tickets t
                WHERE t.customer_id = ?
                ORDER BY 
                    CASE t.status
                        WHEN 'open' THEN 1
                        WHEN 'in_progress' THEN 2
                        ELSE 3
                    END,
                    t.created_at DESC
            ");
            
            $stmt->bind_param("i", $customer_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $tickets = [];
            while ($row = $result->fetch_assoc()) {
                $tickets[] = $row;
            }
            
            echo json_encode(['success' => true, 'tickets' => $tickets]);
            exit;
        }
        
        // 2. جلب رسائل تذكرة محددة
        if (isset($_GET['action']) && $_GET['action'] == 'get_messages' && isset($_GET['ticket_id'])) {
            $ticket_id = (int)$_GET['ticket_id'];
            
            // التحقق من ملكية التذكرة
            $check = $conn->prepare("SELECT id FROM customer_tickets WHERE id = ? AND customer_id = ?");
            $check->bind_param("ii", $ticket_id, $customer_id);
            $check->execute();
            
            if ($check->get_result()->num_rows == 0) {
                echo json_encode(['success' => false, 'message' => 'لا يمكن الوصول لهذه التذكرة']);
                exit;
            }
            
            // تحديث قراءة رسائل الادمن
            $update = $conn->prepare("UPDATE ticket_messages SET is_read = 1 WHERE ticket_id = ? AND sender_type = 'admin'");
            $update->bind_param("i", $ticket_id);
            $update->execute();
            
            // جلب الرسائل
            $stmt = $conn->prepare("
                SELECT 
                    m.*,
                    DATE_FORMAT(m.created_at, '%H:%i') as time_formatted,
                    DATE_FORMAT(m.created_at, '%Y-%m-%d') as date_formatted
                FROM ticket_messages m
                WHERE m.ticket_id = ?
                ORDER BY m.created_at ASC
            ");
            
            $stmt->bind_param("i", $ticket_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $messages = [];
            while ($row = $result->fetch_assoc()) {
                $messages[] = $row;
            }
            
            echo json_encode(['success' => true, 'messages' => $messages]);
            exit;
        }
        
    } catch (Exception $e) {
        logError("خطأ في AJAX", ['error' => $e->getMessage()]);
        echo json_encode(['success' => false, 'message' => 'حدث خطأ في الاتصال بقاعدة البيانات']);
        exit;
    }
}

// ============================================
// معالجة طلبات POST
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    try {
        // 3. إرسال رسالة جديدة
        if (isset($_POST['action']) && $_POST['action'] == 'send_message') {
            $ticket_id = (int)$_POST['ticket_id'];
            $message = trim($_POST['message'] ?? '');
            
            // التحقق من ملكية التذكرة
            $check = $conn->prepare("SELECT id, status FROM customer_tickets WHERE id = ? AND customer_id = ?");
            $check->bind_param("ii", $ticket_id, $customer_id);
            $check->execute();
            $ticket = $check->get_result()->fetch_assoc();
            
            if (!$ticket) {
                echo json_encode(['success' => false, 'message' => 'لا يمكن الوصول لهذه التذكرة']);
                exit;
            }
            
            if ($ticket['status'] == 'closed') {
                echo json_encode(['success' => false, 'message' => 'لا يمكن إرسال رسائل في تذكرة مغلقة']);
                exit;
            }
            
            // معالجة الصورة
            $image_path = null;
            if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
                $validation = validateImage($_FILES['image']);
                if (!$validation['success']) {
                    echo json_encode(['success' => false, 'message' => $validation['error']]);
                    exit;
                }
                
                $target_dir = __DIR__ . '/../admin/uploads/tickets/';
                if (!file_exists($target_dir)) {
                    mkdir($target_dir, 0777, true);
                }
                
                $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                $filename = time() . '_' . uniqid() . '.' . $ext;
                
                if (move_uploaded_file($_FILES['image']['tmp_name'], $target_dir . $filename)) {
                    $image_path = $filename;
                }
            }
            
            // إدراج الرسالة
            $insert = $conn->prepare("INSERT INTO ticket_messages (ticket_id, sender_type, message, image, created_at) VALUES (?, 'customer', ?, ?, NOW())");
            $insert->bind_param("iss", $ticket_id, $message, $image_path);
            
            if ($insert->execute()) {
                // تحديث وقت آخر نشاط
                $update = $conn->prepare("UPDATE customer_tickets SET last_activity = NOW(), updated_at = NOW() WHERE id = ?");
                $update->bind_param("i", $ticket_id);
                $update->execute();
                
                echo json_encode(['success' => true, 'message' => 'تم إرسال الرسالة بنجاح']);
            } else {
                echo json_encode(['success' => false, 'message' => 'حدث خطأ في إرسال الرسالة']);
            }
            exit;
        }
        
        // 4. إنشاء تذكرة جديدة
        if (isset($_POST['action']) && $_POST['action'] == 'create_ticket') {
            $subject = trim($_POST['subject'] ?? '');
            $message = trim($_POST['message'] ?? '');
            $order_id = !empty($_POST['order_id']) ? (int)$_POST['order_id'] : null;
            
            if (empty($subject) || empty($message)) {
                echo json_encode(['success' => false, 'message' => 'الرجاء إدخال الموضوع والرسالة']);
                exit;
            }
            
            if (strlen($subject) < 3) {
                echo json_encode(['success' => false, 'message' => 'الموضوع قصير جداً']);
                exit;
            }
            
            if (strlen($message) < 5) {
                echo json_encode(['success' => false, 'message' => 'الرسالة قصيرة جداً']);
                exit;
            }
            
            // معالجة الصورة
            $image_path = null;
            if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
                $validation = validateImage($_FILES['image']);
                if (!$validation['success']) {
                    echo json_encode(['success' => false, 'message' => $validation['error']]);
                    exit;
                }
                
                $target_dir = __DIR__ . '/../admin/uploads/tickets/';
                if (!file_exists($target_dir)) {
                    mkdir($target_dir, 0777, true);
                }
                
                $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                $filename = time() . '_' . uniqid() . '.' . $ext;
                
                if (move_uploaded_file($_FILES['image']['tmp_name'], $target_dir . $filename)) {
                    $image_path = $filename;
                }
            }
            
            // بدء المعاملة
            $conn->begin_transaction();
            
            // إنشاء التذكرة
            $insert_ticket = $conn->prepare("INSERT INTO customer_tickets (customer_id, order_id, subject, message, status, last_activity, created_at, updated_at) VALUES (?, ?, ?, ?, 'open', NOW(), NOW(), NOW())");
            $insert_ticket->bind_param("iiss", $customer_id, $order_id, $subject, $message);
            
            if (!$insert_ticket->execute()) {
                throw new Exception("فشل في إنشاء التذكرة");
            }
            
            $ticket_id = $conn->insert_id;
            
            // إضافة الرسالة الأولى
            $insert_msg = $conn->prepare("INSERT INTO ticket_messages (ticket_id, sender_type, message, image, created_at) VALUES (?, 'customer', ?, ?, NOW())");
            $insert_msg->bind_param("iss", $ticket_id, $message, $image_path);
            
            if (!$insert_msg->execute()) {
                throw new Exception("فشل في إضافة الرسالة");
            }
            
            $conn->commit();
            
            echo json_encode([
                'success' => true, 
                'ticket_id' => $ticket_id,
                'message' => 'تم إنشاء التذكرة بنجاح'
            ]);
            exit;
        }
        
    } catch (Exception $e) {
        if (isset($conn)) $conn->rollback();
        logError("خطأ في إنشاء التذكرة", ['error' => $e->getMessage()]);
        echo json_encode(['success' => false, 'message' => 'حدث خطأ: ' . $e->getMessage()]);
        exit;
    }
}

// ============================================
// عرض الصفحة العادية
// ============================================

// جلب الطلبات الأخيرة للقائمة المنسدلة
$orders = $conn->prepare("SELECT id, total, status FROM orders WHERE customer_id = ? ORDER BY created_at DESC LIMIT 10");
$orders->bind_param("i", $customer_id);
$orders->execute();
$orders_result = $orders->get_result();

// تحديث CSRF token
$csrf_token = generateCSRFToken();
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ماكس - الدعم الفني</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Tajawal', sans-serif;
        }

        :root {
            --primary: #F57C00;
            --primary-dark: #E65100;
            --primary-light: #FFB74D;
            --primary-soft: #FFF3E0;
            --danger: #F44336;
            --success: #4CAF50;
            --gray: #78909C;
            --gray-light: #ECEFF1;
            --dark: #2E3B4E;
            --header-height: 60px;
        }

        body {
            background: #f8f9fa;
            min-height: 100vh;
            padding-top: var(--header-height);
        }

        /* الهيدر */
        .main-header {
            background: linear-gradient(135deg, var(--primary), #FF9800);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: var(--header-height);
            z-index: 1000;
            display: flex;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .header-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            padding: 0 16px;
        }

        .menu-btn, .action-btn {
            background: rgba(255,255,255,0.2);
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            color: white;
            font-size: 1.3rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo {
            color: white;
            font-size: 1.4rem;
            font-weight: 900;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        /* القائمة الجانبية */
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 1999;
            display: none;
        }

        .overlay.active { display: block; }

        .sidebar {
            position: fixed;
            top: 0;
            right: -280px;
            width: 280px;
            height: 100vh;
            background: white;
            z-index: 2000;
            transition: right 0.3s;
            box-shadow: -5px 0 15px rgba(0,0,0,0.1);
        }

        .sidebar.active { right: 0; }

        .sidebar-header {
            background: linear-gradient(135deg, var(--primary), #FF9800);
            color: white;
            padding: 30px 20px;
        }

        .sidebar-close {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(255,255,255,0.2);
            border: none;
            width: 35px;
            height: 35px;
            border-radius: 50%;
            color: white;
        }

        .user-avatar {
            width: 60px;
            height: 60px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            margin: 0 auto 10px;
        }

        .menu-item {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            color: var(--dark);
            text-decoration: none;
            border-bottom: 1px solid var(--gray-light);
        }

        .menu-item i {
            width: 30px;
            color: var(--primary);
        }

        /* المحتوى الرئيسي */
        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 16px;
        }

        /* التبويبات */
        .tabs {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
            background: white;
            padding: 8px;
            border-radius: 50px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .tab {
            flex: 1;
            padding: 12px;
            border: none;
            border-radius: 40px;
            background: transparent;
            color: var(--gray);
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }

        .tab.active {
            background: var(--primary);
            color: white;
        }

        /* قائمة التذاكر */
        .tickets-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .ticket-item {
            background: white;
            border-radius: 15px;
            padding: 16px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            cursor: pointer;
            border-right: 4px solid transparent;
        }

        .ticket-item.unread {
            border-right-color: var(--primary);
            background: var(--primary-soft);
        }

        .ticket-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
        }

        .ticket-number {
            font-weight: 700;
            color: var(--primary);
        }

        .ticket-status {
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .status-open { background: #E3F2FD; color: #1976D2; }
        .status-in_progress { background: #FFF3E0; color: #F57C00; }
        .status-closed { background: #E8F5E9; color: #388E3C; }

        .ticket-subject {
            font-weight: 700;
            margin-bottom: 8px;
        }

        .ticket-footer {
            display: flex;
            justify-content: space-between;
            font-size: 0.75rem;
            color: var(--gray);
        }

        .unread-badge {
            background: var(--primary);
            color: white;
            padding: 2px 8px;
            border-radius: 20px;
        }

        /* نافذة المحادثة */
        .chat-window {
            background: white;
            border-radius: 20px;
            height: calc(100vh - var(--header-height) - 40px);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            background: linear-gradient(135deg, var(--primary), #FF9800);
            color: white;
            padding: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .back-btn {
            background: rgba(255,255,255,0.2);
            border: none;
            width: 35px;
            height: 35px;
            border-radius: 50%;
            color: white;
        }

        .messages-area {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
            background: #f5f5f5;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .message {
            display: flex;
            max-width: 85%;
        }

        .message.customer { align-self: flex-start; }
        .message.admin { align-self: flex-end; }

        .message-bubble {
            padding: 10px 15px;
            border-radius: 18px;
            word-wrap: break-word;
        }

        .message.customer .message-bubble {
            background: white;
            border: 1px solid var(--primary-light);
        }

        .message.admin .message-bubble {
            background: linear-gradient(135deg, var(--primary), #FF9800);
            color: white;
        }

        .message-image {
            max-width: 200px;
            margin-top: 5px;
            border-radius: 10px;
            cursor: pointer;
        }

        .message-time {
            font-size: 0.6rem;
            color: var(--gray);
            margin-top: 3px;
        }

        /* منطقة الإدخال */
        .input-area {
            padding: 10px;
            border-top: 1px solid var(--gray-light);
        }

        .message-form {
            display: flex;
            gap: 8px;
            align-items: flex-end;
        }

        .input-wrapper {
            flex: 1;
            background: var(--gray-light);
            border-radius: 25px;
            padding: 0 10px;
            display: flex;
            align-items: center;
        }

        .message-input {
            flex: 1;
            border: none;
            background: transparent;
            padding: 12px 10px;
            outline: none;
            resize: none;
            max-height: 100px;
        }

        .attach-btn {
            background: transparent;
            border: none;
            color: var(--primary);
            font-size: 1.2rem;
            cursor: pointer;
            padding: 5px;
        }

        .send-btn {
            background: linear-gradient(135deg, var(--primary), #FF9800);
            border: none;
            width: 45px;
            height: 45px;
            border-radius: 50%;
            color: white;
            font-size: 1.2rem;
            cursor: pointer;
        }

        /* نافذة منبثقة */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 3000;
            display: none;
            align-items: center;
            justify-content: center;
            padding: 16px;
        }

        .modal.active { display: flex; }

        .modal-content {
            background: white;
            border-radius: 20px;
            max-width: 500px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
            padding: 20px;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }

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

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
        }

        .form-control, .form-select {
            width: 100%;
            padding: 12px;
            border: 2px solid var(--gray-light);
            border-radius: 10px;
            font-family: 'Tajawal', sans-serif;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
        }

        .btn {
            width: 100%;
            padding: 14px;
            border: none;
            border-radius: 30px;
            background: linear-gradient(135deg, var(--primary), #FF9800);
            color: white;
            font-weight: 700;
            cursor: pointer;
        }

        .file-name {
            font-size: 0.8rem;
            color: var(--primary);
            margin-top: 5px;
        }

        /* معاينة الصورة */
        .image-preview-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.9);
            z-index: 4000;
            display: none;
            align-items: center;
            justify-content: center;
        }

        .image-preview-modal.active { display: flex; }

        .preview-content {
            max-width: 90%;
            max-height: 90%;
        }

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

        .close-preview {
            position: absolute;
            top: 20px;
            left: 20px;
            background: rgba(255,255,255,0.2);
            border: none;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            color: white;
            font-size: 2rem;
        }

        /* حالة فارغة */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            background: white;
            border-radius: 15px;
        }

        .empty-state i {
            font-size: 3rem;
            color: var(--gray-light);
            margin-bottom: 10px;
        }

        .empty-state h3 {
            color: var(--dark);
            margin-bottom: 5px;
        }

        /* التنبيهات */
        .toast {
            position: fixed;
            top: 80px;
            left: 16px;
            right: 16px;
            background: white;
            border-radius: 10px;
            padding: 12px 16px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            display: flex;
            align-items: center;
            gap: 10px;
            border-right: 4px solid var(--success);
            z-index: 5000;
            max-width: 400px;
            margin: 0 auto;
        }

        .toast.error { border-right-color: var(--danger); }
        .toast.success { border-right-color: var(--success); }

        .date-separator {
            text-align: center;
            margin: 15px 0;
        }

        .date-separator span {
            background: #e0e0e0;
            padding: 3px 12px;
            border-radius: 15px;
            font-size: 0.7rem;
        }

        .loading {
            text-align: center;
            padding: 30px;
            color: var(--gray);
        }
    </style>
</head>
<body>
    <!-- الهيدر -->
    <header class="main-header">
        <div class="header-content">
            <button class="menu-btn" onclick="toggleSidebar()">
                <i class="bi bi-list"></i>
            </button>
            <div class="logo">
                <i class="bi bi-headset"></i>
                <span>الدعم الفني</span>
            </div>
            <button class="action-btn" onclick="refreshTickets()">
                <i class="bi bi-arrow-repeat"></i>
            </button>
        </div>
    </header>

    <!-- القائمة الجانبية -->
    <div class="overlay" id="overlay" onclick="closeSidebar()"></div>
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <button class="sidebar-close" onclick="closeSidebar()">
                <i class="bi bi-x"></i>
            </button>
            <div class="user-avatar">
                <i class="bi bi-person-circle"></i>
            </div>
            <div class="user-name"><?= htmlspecialchars($_SESSION['customer_name'] ?? 'زائر') ?></div>
        </div>
        <div class="sidebar-menu">
            <a href="home.php" class="menu-item">
                <i class="bi bi-house-door"></i>
                <span>الرئيسية</span>
            </a>
            <a href="cart.php" class="menu-item">
                <i class="bi bi-cart3"></i>
                <span>السلة</span>
            </a>
            <a href="orders.php" class="menu-item">
                <i class="bi bi-receipt"></i>
                <span>طلباتي</span>
            </a>
            <a href="profile.php" class="menu-item">
                <i class="bi bi-person"></i>
                <span>حسابي</span>
            </a>
            <a href="support.php" class="menu-item">
                <i class="bi bi-headset"></i>
                <span>الدعم</span>
            </a>
            <a href="logout.php" class="menu-item">
                <i class="bi bi-box-arrow-left"></i>
                <span>تسجيل الخروج</span>
            </a>
        </div>
    </div>

    <!-- نافذة تذكرة جديدة -->
    <div class="modal" id="newTicketModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>تذكرة جديدة</h3>
                <button class="btn-close" onclick="closeNewTicketModal()">×</button>
            </div>
            <form id="newTicketForm" enctype="multipart/form-data">
                <div class="form-group">
                    <label>الموضوع</label>
                    <input type="text" class="form-control" name="subject" required>
                </div>
                
                <div class="form-group">
                    <label>الطلب (اختياري)</label>
                    <select class="form-select" name="order_id">
                        <option value="">-- اختر طلباً --</option>
                        <?php while($order = $orders_result->fetch_assoc()): ?>
                        <option value="<?= $order['id'] ?>">
                            طلب #<?= $order['id'] ?> - <?= number_format($order['total']) ?> ريال
                        </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>الرسالة</label>
                    <textarea class="form-control" name="message" rows="4" required></textarea>
                </div>
                
                <div class="form-group">
                    <label>صورة (اختياري)</label>
                    <input type="file" class="form-control" name="image" accept="image/*" onchange="updateFileName(this)">
                    <div class="file-name" id="fileName"></div>
                </div>
                
                <button type="submit" class="btn" id="submitBtn">
                    <i class="bi bi-send"></i> إرسال
                </button>
            </form>
        </div>
    </div>

    <!-- معاينة الصورة -->
    <div class="image-preview-modal" id="imagePreview" onclick="closeImagePreview()">
        <button class="close-preview"><i class="bi bi-x"></i></button>
        <div class="preview-content">
            <img id="previewImage" src="" alt="معاينة">
        </div>
    </div>

    <!-- المحتوى الرئيسي -->
    <div class="container">
        <div class="tabs">
            <button class="tab active" id="ticketsTab" onclick="showTicketsView()">
                <i class="bi bi-list-ul"></i>
                <span>تذاكري</span>
            </button>
            <button class="tab" id="newTab" onclick="openNewTicketModal()">
                <i class="bi bi-plus-circle"></i>
                <span>جديدة</span>
            </button>
        </div>

        <div id="ticketsList" class="tickets-list">
            <div class="loading">جاري تحميل التذاكر...</div>
        </div>

        <div class="chat-window" id="chatWindow" style="display: none;">
            <div class="chat-header">
                <button class="back-btn" onclick="backToTickets()">
                    <i class="bi bi-arrow-right"></i>
                </button>
                <div class="chat-info">
                    <h3 id="currentTicketSubject"></h3>
                    <p id="currentTicketStatus"></p>
                </div>
            </div>
            
            <div class="messages-area" id="messagesArea">
                <div class="loading">جاري تحميل المحادثة...</div>
            </div>
            
            <div class="input-area">
                <form class="message-form" id="messageForm" enctype="multipart/form-data">
                    <input type="hidden" id="currentTicketId">
                    <div class="input-wrapper">
                        <textarea class="message-input" id="messageText" placeholder="اكتب رسالتك..." rows="1"></textarea>
                        <input type="file" id="messageImage" accept="image/*" style="display: none;" onchange="updateMessageFile(this)">
                        <button type="button" class="attach-btn" onclick="document.getElementById('messageImage').click()">
                            <i class="bi bi-paperclip"></i>
                        </button>
                    </div>
                    <button type="submit" class="send-btn">
                        <i class="bi bi-send"></i>
                    </button>
                </form>
                <div class="file-name" id="messageFileName"></div>
            </div>
        </div>
    </div>

    <div id="toastContainer"></div>

    <script>
    // المتغيرات العامة
    let currentTicketId = null;
    let refreshInterval = null;
    let isChatOpen = false;

    // ===== وظائف القائمة الجانبية =====
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');
        sidebar.classList.toggle('active');
        overlay.classList.toggle('active');
    }

    function closeSidebar() {
        document.getElementById('sidebar').classList.remove('active');
        document.getElementById('overlay').classList.remove('active');
    }

    // ===== وظائف التذاكر =====
    function showTicketsView() {
        document.getElementById('ticketsTab').classList.add('active');
        document.getElementById('newTab').classList.remove('active');
        document.getElementById('chatWindow').style.display = 'none';
        document.getElementById('ticketsList').style.display = 'block';
        isChatOpen = false;
        
        if (refreshInterval) {
            clearInterval(refreshInterval);
            refreshInterval = null;
        }
        
        loadTickets();
    }

    function backToTickets() {
        showTicketsView();
    }

    function refreshTickets() {
        if (!isChatOpen) {
            loadTickets();
        }
    }

    // تحميل التذاكر
    function loadTickets() {
        const container = document.getElementById('ticketsList');
        container.innerHTML = '<div class="loading">جاري التحميل...</div>';
        
        fetch('support.php?action=get_tickets', {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                renderTickets(data.tickets);
            } else {
                showError('حدث خطأ في تحميل التذاكر');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('حدث خطأ في الاتصال بالخادم');
            container.innerHTML = `
                <div class="empty-state">
                    <i class="bi bi-exclamation-triangle" style="color: #F44336;"></i>
                    <h3>خطأ في الاتصال</h3>
                    <p>يرجى التحقق من اتصالك بالإنترنت والمحاولة مرة أخرى</p>
                    <button class="btn" onclick="loadTickets()" style="width: auto; padding: 10px 20px;">
                        <i class="bi bi-arrow-repeat"></i> إعادة المحاولة
                    </button>
                </div>
            `;
        });
    }

    // عرض التذاكر
    function renderTickets(tickets) {
        const container = document.getElementById('ticketsList');
        
        if (!tickets || tickets.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <i class="bi bi-inbox"></i>
                    <h3>لا توجد تذاكر</h3>
                    <p>لم تقم بإنشاء أي تذاكر دعم بعد</p>
                    <button class="btn" onclick="openNewTicketModal()" style="width: auto; padding: 10px 30px;">
                        <i class="bi bi-plus-circle"></i> إنشاء تذكرة
                    </button>
                </div>
            `;
            return;
        }
        
        let html = '';
        
        tickets.forEach(ticket => {
            const statusText = {
                'open': 'مفتوحة',
                'in_progress': 'قيد المعالجة',
                'closed': 'مغلقة'
            }[ticket.status] || ticket.status;
            
            const statusClass = {
                'open': 'status-open',
                'in_progress': 'status-in_progress',
                'closed': 'status-closed'
            }[ticket.status] || 'status-open';
            
            const lastMsg = ticket.last_message || 'لا توجد رسائل';
            const lastTime = formatTime(ticket.last_message_time || ticket.created_at);
            
            html += `
                <div class="ticket-item ${ticket.unread_count > 0 ? 'unread' : ''}" onclick="openChat(${ticket.id}, '${escapeHtml(ticket.subject)}', '${statusText}')">
                    <div class="ticket-header">
                        <span class="ticket-number">#${ticket.id}</span>
                        <span class="ticket-status ${statusClass}">${statusText}</span>
                    </div>
                    <div class="ticket-subject">${escapeHtml(ticket.subject)}</div>
                    <div class="ticket-footer">
                        <span><i class="bi bi-clock"></i> ${lastTime}</span>
                        ${ticket.unread_count > 0 ? `<span class="unread-badge">${ticket.unread_count} جديد</span>` : ''}
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = html;
    }

    // فتح المحادثة
    function openChat(ticketId, subject, status) {
        currentTicketId = ticketId;
        document.getElementById('currentTicketId').value = ticketId;
        document.getElementById('currentTicketSubject').textContent = subject;
        document.getElementById('currentTicketStatus').textContent = status;
        
        document.getElementById('ticketsList').style.display = 'none';
        document.getElementById('chatWindow').style.display = 'flex';
        isChatOpen = true;
        
        loadMessages(ticketId);
        
        // بدء التحديث التلقائي
        if (refreshInterval) {
            clearInterval(refreshInterval);
        }
        refreshInterval = setInterval(() => {
            if (isChatOpen && currentTicketId) {
                loadMessages(currentTicketId, true);
            }
        }, 5000);
    }

    // تحميل الرسائل
    function loadMessages(ticketId, isAuto = false) {
        const container = document.getElementById('messagesArea');
        
        fetch('support.php?action=get_messages&ticket_id=' + ticketId, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderMessages(data.messages);
                if (!isAuto) {
                    setTimeout(scrollToBottom, 100);
                }
            }
        })
        .catch(error => {
            console.error('Error loading messages:', error);
            if (!isAuto) {
                showError('حدث خطأ في تحميل الرسائل');
            }
        });
    }

    // عرض الرسائل
    function renderMessages(messages) {
        const container = document.getElementById('messagesArea');
        
        if (!messages || messages.length === 0) {
            container.innerHTML = '<div class="empty-state" style="padding: 20px;"><p>لا توجد رسائل، ابدأ المحادثة</p></div>';
            return;
        }
        
        let html = '';
        let currentDate = '';
        
        messages.forEach(msg => {
            if (msg.date_formatted !== currentDate) {
                currentDate = msg.date_formatted;
                const displayDate = formatDisplayDate(currentDate);
                html += `<div class="date-separator"><span>${displayDate}</span></div>`;
            }
            
            html += `
                <div class="message ${msg.sender_type}">
                    <div class="message-bubble">
                        ${escapeHtml(msg.message || '').replace(/\n/g, '<br>')}
                        ${msg.image ? `
                            <div class="message-image" onclick="previewImage('${msg.image}')">
                                <img src="../admin/uploads/tickets/${msg.image}" alt="صورة">
                            </div>
                        ` : ''}
                        <div class="message-time">${msg.time_formatted}</div>
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = html;
    }

    // إرسال رسالة
    document.getElementById('messageForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const message = document.getElementById('messageText').value.trim();
        const imageFile = document.getElementById('messageImage').files[0];
        
        if (!message && !imageFile) {
            showError('الرجاء كتابة رسالة أو إرفاق صورة');
            return;
        }
        
        const formData = new FormData();
        formData.append('action', 'send_message');
        formData.append('ticket_id', currentTicketId);
        formData.append('message', message);
        
        if (imageFile) {
            formData.append('image', imageFile);
        }
        
        const sendBtn = document.querySelector('.send-btn');
        sendBtn.disabled = true;
        sendBtn.innerHTML = '<i class="bi bi-hourglass"></i>';
        
        // إظهار رسالة مؤقتة
        const tempMessage = {
            sender_type: 'customer',
            message: message || '📷 صورة',
            time_formatted: new Date().toLocaleTimeString('ar-EG', { hour: '2-digit', minute: '2-digit' })
        };
        
        const tempHtml = `
            <div class="message customer temp-message">
                <div class="message-bubble">
                    ${escapeHtml(message) || '📷 صورة'}
                    <div class="message-time">الآن</div>
                </div>
            </div>
        `;
        
        document.getElementById('messagesArea').insertAdjacentHTML('beforeend', tempHtml);
        scrollToBottom();
        
        // تفريغ الحقول
        document.getElementById('messageText').value = '';
        document.getElementById('messageImage').value = '';
        document.getElementById('messageFileName').innerHTML = '';
        
        fetch('support.php', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            document.querySelector('.temp-message')?.remove();
            
            if (data.success) {
                loadMessages(currentTicketId);
                showSuccess('تم إرسال الرسالة');
            } else {
                showError(data.message || 'حدث خطأ في إرسال الرسالة');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.querySelector('.temp-message')?.remove();
            showError('حدث خطأ في الاتصال');
        })
        .finally(() => {
            sendBtn.disabled = false;
            sendBtn.innerHTML = '<i class="bi bi-send"></i>';
        });
    });

    // إنشاء تذكرة جديدة
    document.getElementById('newTicketForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const subject = document.querySelector('[name="subject"]').value.trim();
        const message = document.querySelector('[name="message"]').value.trim();
        
        if (subject.length < 3) {
            showError('الموضوع قصير جداً');
            return;
        }
        
        if (message.length < 5) {
            showError('الرسالة قصيرة جداً');
            return;
        }
        
        const formData = new FormData(this);
        formData.append('action', 'create_ticket');
        
        const submitBtn = document.getElementById('submitBtn');
        const originalText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="bi bi-hourglass"></i> جاري الإرسال...';
        
        fetch('support.php', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showSuccess('تم إنشاء التذكرة بنجاح');
                closeNewTicketModal();
                showTicketsView();
            } else {
                showError(data.message || 'حدث خطأ');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('حدث خطأ في الاتصال');
        })
        .finally(() => {
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        });
    });

    // ===== وظائف مساعدة =====
    function openNewTicketModal() {
        document.getElementById('newTicketModal').classList.add('active');
    }

    function closeNewTicketModal() {
        document.getElementById('newTicketModal').classList.remove('active');
        document.getElementById('newTicketForm').reset();
        document.getElementById('fileName').innerHTML = '';
    }

    function updateFileName(input) {
        const fileName = document.getElementById('fileName');
        if (input.files && input.files[0]) {
            fileName.innerHTML = '📷 ' + input.files[0].name;
        } else {
            fileName.innerHTML = '';
        }
    }

    function updateMessageFile(input) {
        const fileName = document.getElementById('messageFileName');
        if (input.files && input.files[0]) {
            fileName.innerHTML = '📷 ' + input.files[0].name;
        } else {
            fileName.innerHTML = '';
        }
    }

    function previewImage(imageName) {
        document.getElementById('previewImage').src = '../admin/uploads/tickets/' + imageName;
        document.getElementById('imagePreview').classList.add('active');
    }

    function closeImagePreview() {
        document.getElementById('imagePreview').classList.remove('active');
    }

    function scrollToBottom() {
        const area = document.getElementById('messagesArea');
        area.scrollTop = area.scrollHeight;
    }

    function formatTime(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        const now = new Date();
        const diff = Math.floor((now - date) / 1000 / 60);
        
        if (diff < 1) return 'الآن';
        if (diff < 60) return `منذ ${diff} دقيقة`;
        if (diff < 1440) return `منذ ${Math.floor(diff / 60)} ساعة`;
        return date.toLocaleDateString('ar-EG');
    }

    function formatDisplayDate(dateStr) {
        const today = new Date().toISOString().split('T')[0];
        const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0];
        
        if (dateStr === today) return 'اليوم';
        if (dateStr === yesterday) return 'أمس';
        
        const date = new Date(dateStr);
        return date.toLocaleDateString('ar-EG', { year: 'numeric', month: 'short', day: 'numeric' });
    }

    function escapeHtml(unsafe) {
        if (!unsafe) return '';
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    function showSuccess(message) {
        showToast(message, 'success');
    }

    function showError(message) {
        showToast(message, 'error');
    }

    function showToast(message, type = 'success') {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        toast.innerHTML = `
            <i class="bi ${type === 'success' ? 'bi-check-circle' : 'bi-exclamation-circle'}"></i>
            <span>${message}</span>
        `;
        container.appendChild(toast);
        
        setTimeout(() => {
            toast.remove();
        }, 3000);
    }

    // تحميل البيانات عند بدء الصفحة
    document.addEventListener('DOMContentLoaded', function() {
        loadTickets();
        
        // تكبير مساحة النص تلقائياً
        document.getElementById('messageText').addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });
    });

    // إغلاق النوافذ عند الضغط على ESC
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeImagePreview();
            closeSidebar();
            closeNewTicketModal();
        }
    });

    // إغلاق النوافذ عند النقر خارجها
    document.getElementById('newTicketModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeNewTicketModal();
        }
    });

    document.getElementById('imagePreview').addEventListener('click', function(e) {
        if (e.target === this) {
            closeImagePreview();
        }
    });
    </script>
</body>
</html>