<?php
/**
 * support.php - صفحة الدعم الفني (العميل)
 */

require_once 'config.php';

// التحقق من تسجيل دخول العميل
if (!isset($_SESSION['customer_id'])) {
    header('Location: home.php');
    exit;
}

$customer_id = $_SESSION['customer_id'];
$customer_name = $_SESSION['customer_name'] ?? 'عميل';

// جلب آخر 7 طلبات للعميل
$stmt = $conn->prepare("
    SELECT id, total, DATE_FORMAT(created_at, '%Y-%m-%d') as order_date 
    FROM orders 
    WHERE customer_id = ? 
    ORDER BY created_at DESC 
    LIMIT 7
");
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$orders = $stmt->get_result();

// جلب جميع تذاكر العميل
$stmt = $conn->prepare("
    SELECT t.*, 
           (SELECT COUNT(*) FROM support_messages WHERE ticket_id = t.id AND sender_type = 'admin' AND is_read = 0) as unread,
           (SELECT message FROM support_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_message,
           (SELECT created_at FROM support_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_activity
    FROM support_tickets t
    WHERE t.customer_id = ?
    ORDER BY 
        CASE t.status
            WHEN 'pending' THEN 1
            WHEN 'in_progress' THEN 2
            WHEN 'resolved' THEN 3
        END,
        t.created_at DESC
");
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$tickets = $stmt->get_result();

// جلب عدد الرسائل غير المقروءة
$unread_tickets = 0;
$stmt = $conn->prepare("
    SELECT COUNT(*) as count
    FROM support_messages m
    JOIN support_tickets t ON m.ticket_id = t.id
    WHERE t.customer_id = ? 
    AND m.sender_type = 'admin' 
    AND m.is_read = FALSE
");
$stmt->bind_param('i', $_SESSION['customer_id']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$unread_tickets = $row['count'] ?? 0;
$stmt->close();

// جلب سلة المشتريات
$cart_count = 0;
if (isset($_SESSION['cart']) && is_array($_SESSION['cart'])) {
    foreach ($_SESSION['cart'] as $item) {
        $cart_count += $item['quantity'] ?? 0;
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes, viewport-fit=cover">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <title>ماكس بروست - الدعم الفني</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }

        :root {
            --primary: #F57C00;
            --primary-dark: #E65100;
            --primary-light: #FFB74D;
            --primary-soft: #FFF3E0;
            --accent: #FF9800;
            --success: #4CAF50;
            --danger: #F44336;
            --dark: #2E3B4E;
            --gray: #78909C;
            --gray-light: #ECEFF1;
            --white: #FFFFFF;
            --shadow-sm: 0 2px 8px rgba(0,0,0,0.05);
            --shadow-md: 0 4px 16px rgba(0,0,0,0.1);
            --radius-sm: 12px;
            --radius-md: 16px;
            --radius-lg: 24px;
            --header-height: 56px;
            --safe-area-inset-bottom: env(safe-area-inset-bottom, 0px);
        }

        body {
            font-family: 'Tajawal', sans-serif;
            background: #f8f9fa;
            padding-top: var(--header-height);
            padding-bottom: calc(20px + var(--safe-area-inset-bottom));
            min-height: 100vh;
        }

        .main-header {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: var(--header-height);
            z-index: 1000;
            display: flex;
            align-items: center;
            padding: 0 12px;
            box-shadow: var(--shadow-md);
        }

        .header-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            max-width: 600px;
            margin: 0 auto;
        }

        .header-left, .header-right {
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 70px;
        }

        .header-right {
            justify-content: flex-end;
        }

        .back-btn, .icon-btn {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            color: white;
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .back-btn:active, .icon-btn:active {
            transform: scale(0.92);
            background: rgba(255, 255, 255, 0.35);
        }

        .header-center {
            flex: 1;
            text-align: center;
        }

        .restaurant-name {
            color: white;
            font-size: 1.1rem;
            font-weight: 800;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .badge {
            position: absolute;
            top: -4px;
            right: -4px;
            background: var(--danger);
            color: white;
            font-size: 10px;
            min-width: 18px;
            height: 18px;
            border-radius: 9px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px solid white;
            font-weight: bold;
        }

        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 0 12px;
        }
        
        .card {
            background: white;
            border-radius: var(--radius-md);
            padding: 16px;
            margin-bottom: 16px;
            box-shadow: var(--shadow-sm);
            border: 1px solid rgba(245, 124, 0, 0.15);
        }
        
        .card h3 {
            color: var(--primary);
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 1.1rem;
        }
        
        .tabs {
            display: flex;
            gap: 8px;
            margin-bottom: 16px;
            background: white;
            padding: 4px;
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-sm);
        }
        
        .tab {
            flex: 1;
            padding: 12px 8px;
            border: none;
            border-radius: var(--radius-lg);
            background: transparent;
            color: #666;
            font-weight: 600;
            font-size: 0.85rem;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            font-family: 'Tajawal', sans-serif;
        }
        
        .tab.active {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .form-group {
            margin-bottom: 16px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: var(--dark);
            font-size: 0.9rem;
        }
        
        input, select, textarea {
            width: 100%;
            padding: 12px 14px;
            border: 2px solid #f0e0d0;
            border-radius: var(--radius-sm);
            font-family: 'Tajawal', sans-serif;
            font-size: 0.95rem;
            transition: all 0.2s ease;
            background: white;
        }
        
        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(245,124,0,0.1);
        }
        
        .btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border: none;
            padding: 14px 20px;
            border-radius: var(--radius-lg);
            font-weight: 700;
            font-size: 1rem;
            cursor: pointer;
            width: 100%;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .btn:active {
            transform: scale(0.97);
        }
        
        .btn:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }
        
        .file-info {
            font-size: 0.75rem;
            color: var(--primary);
            margin-top: 6px;
        }
        
        .ticket-list {
            margin-top: 16px;
        }
        
        .ticket-item {
            background: #f8f9fa;
            border-radius: var(--radius-sm);
            padding: 14px;
            margin-bottom: 12px;
            border-right: 3px solid var(--primary);
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .ticket-item:active {
            background: var(--primary-soft);
            transform: scale(0.98);
        }
        
        .ticket-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 8px;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .ticket-id {
            font-weight: 800;
            color: var(--primary);
            font-size: 0.85rem;
        }
        
        .ticket-status {
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 0.7rem;
            font-weight: 600;
        }
        
        .status-pending { background: #fff3e0; color: #f57c00; }
        .status-in_progress { background: #e3f2fd; color: #1976d2; }
        .status-resolved { background: #e8f5e9; color: #2e7d32; }
        
        .ticket-priority {
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 0.7rem;
            font-weight: 600;
        }
        
        .priority-high { background: #ffebee; color: #c62828; }
        .priority-medium { background: #fff3e0; color: #f57c00; }
        .priority-low { background: #e8f5e9; color: #2e7d32; }
        
        .ticket-subject {
            font-weight: 600;
            font-size: 0.9rem;
            margin-bottom: 8px;
            color: var(--dark);
        }
        
        .ticket-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.7rem;
            color: #999;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .unread-badge {
            background: var(--primary);
            color: white;
            padding: 2px 8px;
            border-radius: 20px;
            font-size: 0.65rem;
            font-weight: 600;
        }
        
        .ticket-last-message {
            font-size: 0.7rem;
            color: #888;
            margin-top: 10px;
            padding-top: 8px;
            border-top: 1px solid #eee;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .chat-window {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: #f8fafc;
            z-index: 2000;
            display: none;
            flex-direction: column;
            animation: slideUp 0.3s ease;
        }
        
        @keyframes slideUp {
            from { transform: translateY(100%); }
            to { transform: translateY(0); }
        }
        
        .chat-header {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            padding: 12px 16px;
            display: flex;
            align-items: center;
            gap: 12px;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        
        .chat-back-btn {
            background: rgba(255,255,255,0.2);
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            color: white;
            font-size: 1.2rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        
        .chat-back-btn:active {
            transform: scale(0.92);
        }
        
        .chat-header-info {
            flex: 1;
            min-width: 0;
        }
        
        .chat-header-info h4 {
            font-size: 1rem;
            margin: 0 0 2px 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .chat-header-info small {
            font-size: 0.7rem;
            opacity: 0.9;
        }
        
        .chat-priority {
            font-size: 0.7rem;
            padding: 4px 8px;
            border-radius: 20px;
            background: rgba(255,255,255,0.2);
            white-space: nowrap;
        }
        
        .messages {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
            background: #f8fafc;
            -webkit-overflow-scrolling: touch;
        }
        
        .message {
            margin-bottom: 16px;
            max-width: 85%;
            animation: messageFade 0.2s ease;
        }
        
        @keyframes messageFade {
            from { opacity: 0; transform: translateY(5px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .message.customer { 
            margin-left: auto; 
        }
        .message.admin { 
            margin-right: auto; 
        }
        .message.system { 
            margin: 0 auto; 
            text-align: center; 
            max-width: 90%; 
        }
        
        .message-bubble {
            padding: 10px 14px;
            border-radius: 18px;
            position: relative;
            word-break: break-word;
            font-size: 0.9rem;
            line-height: 1.45;
        }
        
        .message.customer .message-bubble {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border-top-left-radius: 4px;
        }
        
        .message.admin .message-bubble {
            background: white;
            border: 1px solid #e0e0e0;
            border-top-right-radius: 4px;
        }
        
        .message.system .message-bubble {
            background: #e9ecef;
            color: #666;
            font-size: 0.75rem;
            padding: 8px 12px;
        }
        
        .message-time {
            font-size: 0.6rem;
            color: #999;
            margin-top: 4px;
        }
        
        .message.customer .message-time {
            color: rgba(0,0,0,0.4);
            text-align: left;
        }
        
        .message-attachment {
            max-width: 180px;
            margin-top: 8px;
            border-radius: 12px;
            cursor: pointer;
            overflow: hidden;
        }
        
        .message-attachment img {
            width: 100%;
            height: auto;
            border-radius: 12px;
            display: block;
        }
        
        .chat-input {
            display: flex;
            padding: 12px;
            gap: 8px;
            background: white;
            border-top: 1px solid #eee;
            position: sticky;
            bottom: 0;
            z-index: 10;
        }
        
        .chat-input input {
            flex: 1;
            padding: 12px 14px;
            border-radius: 25px;
            font-size: 0.9rem;
            background: #f5f5f5;
            border: 1px solid #e0e0e0;
        }
        
        .chat-input input:focus {
            background: white;
        }
        
        .send-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            border: none;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            color: white;
            font-size: 1.2rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        
        .send-btn:active {
            transform: scale(0.94);
        }
        
        .attach-btn {
            background: #f0f0f0;
            color: #666;
        }
        
        .loading {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px 20px;
        }
        
        .empty-state i {
            font-size: 3rem;
            color: #ddd;
            margin-bottom: 12px;
        }
        
        .empty-state p {
            color: #999;
            font-size: 0.9rem;
        }
        
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.6);
            z-index: 3000;
            display: none;
            align-items: center;
            justify-content: center;
        }
        
        .modal-overlay.active {
            display: flex;
        }
        
        .modal-content {
            background: white;
            border-radius: var(--radius-md);
            padding: 24px;
            max-width: 300px;
            width: 85%;
            text-align: center;
            animation: modalPop 0.25s ease;
        }
        
        @keyframes modalPop {
            from { transform: scale(0.9); opacity: 0; }
            to { transform: scale(1); opacity: 1; }
        }
        
        .modal-icon {
            width: 56px;
            height: 56px;
            border-radius: 50%;
            background: var(--primary-soft);
            color: var(--primary);
            font-size: 1.8rem;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 12px;
        }
        
        .modal-title {
            font-size: 1.2rem;
            font-weight: 700;
            color: var(--primary);
            margin-bottom: 8px;
        }
        
        .modal-message {
            color: #666;
            font-size: 0.85rem;
            margin-bottom: 20px;
        }
        
        .modal-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border: none;
            padding: 10px 24px;
            border-radius: var(--radius-lg);
            font-weight: 600;
            font-size: 0.9rem;
            cursor: pointer;
        }
        
        .toast-container {
            position: fixed;
            top: calc(var(--header-height) + 8px);
            left: 12px;
            right: 12px;
            z-index: 4000;
            pointer-events: none;
        }

        .toast-message {
            background: white;
            border-radius: 12px;
            padding: 12px 16px;
            margin-bottom: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            display: flex;
            align-items: center;
            gap: 10px;
            border-right: 4px solid var(--success);
            animation: slideDown 0.25s ease;
            pointer-events: auto;
            font-size: 0.85rem;
        }

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

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

        @media (max-width: 480px) {
            .message { max-width: 90%; }
            .message-bubble { padding: 8px 12px; font-size: 0.85rem; }
            .send-btn { width: 40px; height: 40px; font-size: 1rem; }
        }
        
        @supports (padding-top: env(safe-area-inset-top)) {
            .main-header {
                padding-top: env(safe-area-inset-top);
                height: calc(var(--header-height) + env(safe-area-inset-top));
            }
            body {
                padding-top: calc(var(--header-height) + env(safe-area-inset-top));
            }
        }
    </style>
</head>
<body>
    <header class="main-header">
        <div class="header-content">
            <div class="header-left">
                <a href="home.php" class="back-btn">
                    <i class="bi bi-arrow-right"></i>
                </a>
            </div>
            <div class="header-center">
                <span class="restaurant-name">
                    <i class="bi bi-headset"></i> الدعم
                </span>
            </div>
            <div class="header-right">
                <a href="cart.php" class="icon-btn" title="السلة">
                    <i class="bi bi-cart3"></i>
                    <?php if($cart_count > 0): ?>
                    <span class="badge"><?= $cart_count > 99 ? '99+' : $cart_count ?></span>
                    <?php endif; ?>
                </a>
                <a href="support.php" class="icon-btn" title="الإشعارات">
                    <i class="bi bi-bell"></i>
                    <?php if($unread_tickets > 0): ?>
                    <span class="badge"><?= $unread_tickets > 99 ? '99+' : $unread_tickets ?></span>
                    <?php endif; ?>
                </a>
            </div>
        </div>
    </header>

    <div class="container" id="mainContainer">
        <div class="tabs">
            <button class="tab active" onclick="switchTab('tickets')">
                <i class="bi bi-list-ul"></i>
                <span>تذاكري</span>
            </button>
            <button class="tab" onclick="switchTab('new')">
                <i class="bi bi-plus-circle"></i>
                <span>جديدة</span>
            </button>
        </div>
        
        <div id="ticketsTab" class="tab-content active">
            <div class="card">
                <h3><i class="bi bi-ticket-detailed"></i> تذاكر الدعم الفني</h3>
                <div class="ticket-list" id="ticketList">
                    <?php if ($tickets->num_rows > 0): ?>
                        <?php while($ticket = $tickets->fetch_assoc()): 
                            $priority_class = 'priority-' . $ticket['priority'];
                            $priority_text = ['low' => 'منخفضة', 'medium' => 'متوسطة', 'high' => 'عالية'][$ticket['priority']];
                            $status_class = ['pending' => 'status-pending', 'in_progress' => 'status-in_progress', 'resolved' => 'status-resolved'][$ticket['status']];
                            $status_text = ['pending' => 'قيد الانتظار', 'in_progress' => 'قيد المعالجة', 'resolved' => 'تم الحل'][$ticket['status']];
                        ?>
                        <div class="ticket-item" onclick="openTicket(<?= $ticket['id'] ?>)">
                            <div class="ticket-header">
                                <span class="ticket-id">#<?= str_pad($ticket['id'], 4, '0', STR_PAD_LEFT) ?></span>
                                <div style="display: flex; gap: 6px;">
                                    <span class="ticket-status <?= $status_class ?>"><?= $status_text ?></span>
                                    <span class="ticket-priority <?= $priority_class ?>"><?= $priority_text ?></span>
                                </div>
                            </div>
                            <div class="ticket-subject"><?= htmlspecialchars($ticket['subject']) ?></div>
                            <div class="ticket-meta">
                                <span><i class="bi bi-clock"></i> <?= date('d/m/Y H:i', strtotime($ticket['created_at'])) ?></span>
                                <?php if ($ticket['unread'] > 0): ?>
                                    <span class="unread-badge"><?= $ticket['unread'] ?> جديد</span>
                                <?php endif; ?>
                            </div>
                            <?php if ($ticket['last_message']): ?>
                            <div class="ticket-last-message">
                                <i class="bi bi-chat"></i>
                                <span><?= htmlspecialchars(mb_substr($ticket['last_message'], 0, 40)) ?>...</span>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="bi bi-inbox"></i>
                            <p>لا توجد تذاكر بعد</p>
                            <button class="btn" onclick="switchTab('new')" style="width: auto; padding: 10px 20px; margin-top: 12px;">
                                <i class="bi bi-plus-circle"></i> إنشاء تذكرة
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div id="newTicketTab" class="tab-content">
            <div class="card">
                <h3><i class="bi bi-plus-circle"></i> تذكرة جديدة</h3>
                <form id="ticketForm" enctype="multipart/form-data">
                    <div class="form-group">
                        <label class="form-label">الموضوع</label>
                        <input type="text" name="subject" required maxlength="100" placeholder="مثال: مشكلة في الطلب">
                    </div>
                    <div class="form-group">
                        <label class="form-label">رقم الطلب (اختياري)</label>
                        <select name="order_id">
                            <option value="">-- اختر طلباً --</option>
                            <?php 
                            $orders->data_seek(0);
                            while($order = $orders->fetch_assoc()): 
                            ?>
                            <option value="<?= $order['id'] ?>">#<?= $order['id'] ?> - <?= $order['order_date'] ?> (<?= number_format($order['total'], 0) ?> ريال)</option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">الأولوية</label>
                        <select name="priority">
                            <option value="low">🟢 منخفضة</option>
                            <option value="medium" selected>🟠 متوسطة</option>
                            <option value="high">🔴 عالية</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">الرسالة</label>
                        <textarea name="message" rows="4" required placeholder="اشرح مشكلتك بالتفصيل..."></textarea>
                    </div>
                    <div class="form-group">
                        <label class="form-label">صورة (اختياري)</label>
                        <input type="file" name="attachment" accept="image/*" onchange="updateFileName(this)">
                        <div class="file-info" id="fileName"></div>
                    </div>
                    <button type="submit" class="btn" id="submitBtn">
                        <i class="bi bi-send"></i>
                        <span>إرسال التذكرة</span>
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="chat-window" id="chatWindow">
        <div class="chat-header">
            <button class="chat-back-btn" onclick="closeChat()"><i class="bi bi-arrow-right"></i></button>
            <div class="chat-header-info">
                <h4 id="chatSubject">تحميل...</h4>
                <small id="chatStatus"></small>
            </div>
            <div class="chat-priority" id="chatPriority"></div>
        </div>
        <div class="messages" id="messages">
            <div class="loading"><i class="bi bi-chat-dots" style="font-size: 2rem; display: block; margin-bottom: 8px;"></i>جاري تحميل المحادثة...</div>
        </div>
        <div class="chat-input" id="chatInput">
            <input type="text" id="messageInput" placeholder="اكتب رسالتك..." autocomplete="off" enterkeyhint="send">
            <button class="send-btn attach-btn" type="button" onclick="document.getElementById('chatAttachment').click()">
                <i class="bi bi-paperclip"></i>
            </button>
            <input type="file" id="chatAttachment" accept="image/*" style="display: none;">
            <button class="send-btn" type="button" onclick="sendMessage()" id="sendMsgBtn">
                <i class="bi bi-send"></i>
            </button>
        </div>
    </div>
    
    <div class="modal-overlay" id="successModal">
        <div class="modal-content">
            <div class="modal-icon"><i class="bi bi-check-lg"></i></div>
            <div class="modal-title">تم بنجاح!</div>
            <div class="modal-message" id="successMessage"></div>
            <button class="modal-btn" onclick="closeModal('successModal')">حسناً</button>
        </div>
    </div>
    
    <div class="modal-overlay" id="errorModal">
        <div class="modal-content">
            <div class="modal-icon" style="background: #ffebee; color: #c62828;"><i class="bi bi-exclamation-triangle"></i></div>
            <div class="modal-title" style="color: #c62828;">خطأ!</div>
            <div class="modal-message" id="errorMessage"></div>
            <button class="modal-btn" onclick="closeModal('errorModal')">حسناً</button>
        </div>
    </div>
    
    <div class="toast-container" id="toastContainer"></div>

    <script>
    const basePath = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1);
    const ajaxUrl = basePath + 'support_ajax_handler.php';
    
    let currentTicketId = null;
    let lastMessageId = 0;
    let refreshInterval;
    let currentTicketStatus = null;
    
    console.log('📍 المسار الأساسي:', basePath);
    console.log('📡 AJAX URL:', ajaxUrl);
    
    function showToast(message, type = 'success') {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = `toast-message ${type}`;
        let icon = type === 'success' ? 'check-circle-fill' : (type === 'error' ? 'exclamation-circle-fill' : 'exclamation-triangle-fill');
        toast.innerHTML = `<i class="bi bi-${icon}" style="font-size: 1.2rem;"></i><div style="flex:1;">${message}</div>`;
        container.appendChild(toast);
        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => toast.remove(), 250);
        }, 3500);
    }
    
    function switchTab(tab) {
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        if (tab === 'tickets') {
            document.querySelectorAll('.tab')[0].classList.add('active');
            document.getElementById('ticketsTab').classList.add('active');
        } else {
            document.querySelectorAll('.tab')[1].classList.add('active');
            document.getElementById('newTicketTab').classList.add('active');
        }
    }
    
    function showModal(modalId, message) {
        if (modalId === 'successModal') document.getElementById('successMessage').textContent = message;
        else document.getElementById('errorMessage').textContent = message;
        document.getElementById(modalId).classList.add('active');
    }
    
    function closeModal(modalId) {
        document.getElementById(modalId).classList.remove('active');
    }
    
    function updateFileName(input) {
        const fileName = document.getElementById('fileName');
        if (fileName && input.files && input.files[0]) {
            fileName.innerHTML = '📷 ' + input.files[0].name;
        }
    }
    
    document.getElementById('ticketForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        formData.append('action', 'send_ticket');
        const btn = document.getElementById('submitBtn');
        btn.disabled = true;
        btn.innerHTML = '<i class="bi bi-hourglass-split"></i> جاري الإرسال...';
        fetch(ajaxUrl, { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    showModal('successModal', 'تم إرسال التذكرة بنجاح');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showModal('errorModal', data.message);
                    btn.disabled = false;
                    btn.innerHTML = '<i class="bi bi-send"></i> إرسال التذكرة';
                }
            })
            .catch(() => {
                showModal('errorModal', 'حدث خطأ في الاتصال');
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-send"></i> إرسال التذكرة';
            });
    });
    
    function openTicket(ticketId) {
        currentTicketId = ticketId;
        lastMessageId = 0;
        document.getElementById('chatWindow').style.display = 'flex';
        document.getElementById('mainContainer').style.display = 'none';
        document.body.style.overflow = 'hidden';
        loadMessages();
        if (refreshInterval) clearInterval(refreshInterval);
        refreshInterval = setInterval(loadMessages, 5000);
    }
    
    function closeChat() {
        document.getElementById('chatWindow').style.display = 'none';
        document.getElementById('mainContainer').style.display = 'block';
        document.body.style.overflow = '';
        if (refreshInterval) clearInterval(refreshInterval);
        currentTicketId = null;
        lastMessageId = 0;
    }
    
    function loadMessages() {
        if (!currentTicketId) return;
        const formData = new FormData();
        formData.append('action', 'fetch_messages');
        formData.append('ticket_id', currentTicketId);
        formData.append('last_id', lastMessageId);
        fetch(ajaxUrl, { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    if (data.data.ticket) {
                        document.getElementById('chatSubject').textContent = data.data.ticket.subject;
                        const statusText = { 'pending': '⏳ قيد الانتظار', 'in_progress': '⚙️ قيد المعالجة', 'resolved': '✅ تم الحل' }[data.data.ticket.status];
                        document.getElementById('chatStatus').textContent = statusText;
                        currentTicketStatus = data.data.ticket.status;
                        const priorityText = { 'low': '🟢 منخفضة', 'medium': '🟠 متوسطة', 'high': '🔴 عالية' }[data.data.ticket.priority];
                        document.getElementById('chatPriority').textContent = priorityText;
                        const chatInput = document.getElementById('chatInput');
                        if (data.data.ticket.status === 'resolved') {
                            chatInput.style.display = 'none';
                        } else {
                            chatInput.style.display = 'flex';
                        }
                    }
                    if (data.data.messages && data.data.messages.length > 0) {
                        const container = document.getElementById('messages');
                        if (container.innerHTML.includes('جاري تحميل المحادثة')) container.innerHTML = '';
                        data.data.messages.forEach(msg => {
                            if (msg.id > lastMessageId) {
                                const msgDiv = document.createElement('div');
                                msgDiv.className = `message ${msg.sender}`;
                                let html = `<div class="message-bubble">${escapeHtml(msg.message).replace(/\n/g, '<br>')}`;
                                if (msg.attachment) {
                                    html += `<div class="message-attachment" onclick="window.open('${msg.attachment}', '_blank')"><img src="${msg.attachment}" alt="مرفق"></div>`;
                                }
                                html += `</div><div class="message-time">${msg.time}</div>`;
                                msgDiv.innerHTML = html;
                                container.appendChild(msgDiv);
                            }
                        });
                        if (data.data.messages.length > 0) {
                            lastMessageId = Math.max(...data.data.messages.map(m => m.id));
                        }
                        container.scrollTop = container.scrollHeight;
                    }
                }
            })
            .catch(error => console.error('خطأ:', error));
    }
    
    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    function sendMessage() {
        const input = document.getElementById('messageInput');
        const message = input.value.trim();
        if (!message) return;
        if (currentTicketStatus === 'resolved') {
            showToast('لا يمكن إرسال رسائل لتذكرة مغلقة', 'warning');
            return;
        }
        const btn = document.getElementById('sendMsgBtn');
        btn.disabled = true;
        btn.innerHTML = '<i class="bi bi-hourglass-split"></i>';
        const formData = new FormData();
        formData.append('action', 'send_message');
        formData.append('ticket_id', currentTicketId);
        formData.append('message', message);
        const attachment = document.getElementById('chatAttachment');
        if (attachment.files && attachment.files[0]) {
            formData.append('attachment', attachment.files[0]);
        }
        fetch(ajaxUrl, { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    input.value = '';
                    attachment.value = '';
                    loadMessages();
                    showToast('تم إرسال الرسالة', 'success');
                } else {
                    showToast(data.message, 'error');
                }
            })
            .catch(() => showToast('حدث خطأ في الاتصال', 'error'))
            .finally(() => {
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-send"></i>';
            });
    }
    
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('messageInput')?.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        document.getElementById('chatWindow').style.display = 'none';
        
        fetch(ajaxUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'action=test' })
            .then(res => res.json())
            .then(data => console.log('🧪 اختبار الاتصال:', data))
            .catch(err => console.error('❌ فشل الاتصال:', err));
    });
    
    window.addEventListener('beforeunload', () => { if (refreshInterval) clearInterval(refreshInterval); });
    </script>
</body>
</html>