<?php
/**
 * support.php - نظام الدعم الفني للمسؤولين
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once 'config.php';

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

// ==========================================
// إنشاء الجداول إذا لم تكن موجودة
// ==========================================

$conn->query("
CREATE TABLE IF NOT EXISTS `support_tickets` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `customer_id` int(11) DEFAULT NULL,
    `customer_name` varchar(100) DEFAULT NULL,
    `customer_phone` varchar(20) DEFAULT NULL,
    `order_id` int(11) DEFAULT NULL,
    `subject` varchar(255) NOT NULL,
    `priority` enum('low','medium','high') DEFAULT 'medium',
    `status` enum('pending','in_progress','resolved') DEFAULT 'pending',
    `created_at` timestamp NULL DEFAULT current_timestamp(),
    `updated_at` timestamp NULL DEFAULT NULL ON UPDATE current_timestamp(),
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");

$conn->query("
CREATE TABLE IF NOT EXISTS `support_messages` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `ticket_id` int(11) NOT NULL,
    `sender_type` enum('customer','admin','system') NOT NULL,
    `message` text,
    `image` varchar(255) DEFAULT NULL,
    `is_read` tinyint(1) DEFAULT 0,
    `created_at` timestamp NULL DEFAULT current_timestamp(),
    PRIMARY KEY (`id`),
    KEY `ticket_id` (`ticket_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");

// ==========================================
// معالجة الفلاتر
// ==========================================
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$priority_filter = isset($_GET['priority']) ? $_GET['priority'] : 'all';
$search_filter = isset($_GET['search']) ? trim($_GET['search']) : '';

// ==========================================
// معالجة الإجراءات (AJAX)
// ==========================================

// جلب رسائل التذكرة
if (isset($_POST['action']) && $_POST['action'] == 'fetch_messages') {
    $ticket_id = (int)$_POST['ticket_id'];
    
    // تحديث حالة القراءة
    $conn->query("UPDATE support_messages SET is_read = 1 WHERE ticket_id = $ticket_id AND sender_type = 'customer'");
    
    // جلب الرسائل
    $result = $conn->query("
        SELECT id, sender_type as sender, message, image,
               DATE_FORMAT(created_at, '%H:%i') as time
        FROM support_messages 
        WHERE ticket_id = $ticket_id 
        ORDER BY created_at ASC
    ");
    
    $messages = [];
    while ($row = $result->fetch_assoc()) {
        if (!empty($row['image'])) {
            $row['image'] = '../uploads/tickets/' . $row['image'];
        }
        $messages[] = $row;
    }
    
    // جلب معلومات التذكرة
    $ticket = $conn->query("SELECT id, subject, status, priority FROM support_tickets WHERE id = $ticket_id")->fetch_assoc();
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'messages' => $messages,
        'ticket' => $ticket
    ]);
    exit;
}

// تحديث حالة التذكرة
if (isset($_POST['action']) && $_POST['action'] == 'update_status') {
    $ticket_id = (int)$_POST['ticket_id'];
    $status = $_POST['status'];
    
    if (in_array($status, ['pending', 'in_progress', 'resolved'])) {
        $stmt = $conn->prepare("UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->bind_param("si", $status, $ticket_id);
        $stmt->execute();
        $stmt->close();
        
        if ($status === 'resolved') {
            $message = "تم إغلاق التذكرة. شكراً لتواصلك مع ماكس بروست.";
            $stmt = $conn->prepare("INSERT INTO support_messages (ticket_id, sender_type, message, is_read, created_at) VALUES (?, 'system', ?, 1, NOW())");
            $stmt->bind_param("is", $ticket_id, $message);
            $stmt->execute();
            $stmt->close();
        }
        
        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'message' => 'تم تحديث الحالة']);
    } else {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'حالة غير صالحة']);
    }
    exit;
}

// إرسال رد
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_reply'])) {
    $ticket_id = (int)$_POST['ticket_id'];
    $message = trim($_POST['message']);
    
    if (!empty($message)) {
        $stmt = $conn->prepare("INSERT INTO support_messages (ticket_id, sender_type, message, is_read, created_at) VALUES (?, 'admin', ?, 0, NOW())");
        $stmt->bind_param("is", $ticket_id, $message);
        $stmt->execute();
        $stmt->close();
        
        $stmt = $conn->prepare("UPDATE support_tickets SET status = 'in_progress', updated_at = NOW() WHERE id = ?");
        $stmt->bind_param("i", $ticket_id);
        $stmt->execute();
        $stmt->close();
    }
    
    header("Location: support.php?ticket_id=$ticket_id&status=$status_filter&priority=$priority_filter&search=" . urlencode($search_filter));
    exit;
}

// ==========================================
// جلب الإحصائيات
// ==========================================

$total = $conn->query("SELECT COUNT(*) as c FROM support_tickets")->fetch_assoc()['c'];
$pending = $conn->query("SELECT COUNT(*) as c FROM support_tickets WHERE status = 'pending'")->fetch_assoc()['c'];
$in_progress = $conn->query("SELECT COUNT(*) as c FROM support_tickets WHERE status = 'in_progress'")->fetch_assoc()['c'];
$resolved = $conn->query("SELECT COUNT(*) as c FROM support_tickets WHERE status = 'resolved'")->fetch_assoc()['c'];
$high_priority = $conn->query("SELECT COUNT(*) as c FROM support_tickets WHERE priority = 'high'")->fetch_assoc()['c'];

// ==========================================
// جلب قائمة التذاكر
// ==========================================
$where = "1=1";
if ($status_filter != 'all') {
    $where .= " AND status = '" . $conn->real_escape_string($status_filter) . "'";
}
if ($priority_filter != 'all') {
    $where .= " AND priority = '" . $conn->real_escape_string($priority_filter) . "'";
}
if (!empty($search_filter)) {
    $search = $conn->real_escape_string($search_filter);
    $where .= " AND (subject LIKE '%$search%' OR customer_name LIKE '%$search%' OR customer_phone LIKE '%$search%')";
}

$tickets_result = $conn->query("
    SELECT t.*,
        (SELECT COUNT(*) FROM support_messages WHERE ticket_id = t.id AND is_read = 0 AND sender_type = 'customer') as unread,
        (SELECT message FROM support_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_message
    FROM support_tickets t
    WHERE $where
    ORDER BY 
        CASE t.status WHEN 'pending' THEN 1 WHEN 'in_progress' THEN 2 WHEN 'resolved' THEN 3 END,
        CASE t.priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 END,
        t.created_at DESC
    LIMIT 100
");

// ==========================================
// جلب تفاصيل التذكرة المحددة
// ==========================================
$current_ticket = null;
$messages = null;
$selected_ticket_id = isset($_GET['ticket_id']) ? (int)$_GET['ticket_id'] : null;

if ($selected_ticket_id) {
    $current_ticket = $conn->query("SELECT * FROM support_tickets WHERE id = $selected_ticket_id")->fetch_assoc();
    
    if ($current_ticket) {
        $conn->query("UPDATE support_messages SET is_read = 1 WHERE ticket_id = $selected_ticket_id AND sender_type = 'customer'");
        $messages = $conn->query("
            SELECT id, sender_type as sender, message, image,
                   DATE_FORMAT(created_at, '%H:%i') as time
            FROM support_messages 
            WHERE ticket_id = $selected_ticket_id 
            ORDER BY created_at ASC
        ");
    }
}
?>
<!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">
    <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;
        }
        body {
            font-family: 'Tajawal', sans-serif;
            background: #f8f9fa;
            padding: 15px;
        }
        :root {
            --primary: #F57C00;
            --primary-dark: #E65100;
            --primary-light: #FFB74D;
            --primary-soft: #FFF3E0;
            --success: #4CAF50;
            --danger: #F44336;
            --gray: #78909C;
            --shadow: 0 2px 8px rgba(0,0,0,0.05);
            --radius: 12px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        /* بطاقات الإحصائيات */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            padding: 15px;
            border-radius: var(--radius);
            display: flex;
            align-items: center;
            gap: 12px;
            box-shadow: var(--shadow);
            text-decoration: none;
            color: inherit;
            border: 2px solid transparent;
            transition: all 0.2s;
        }
        .stat-card.active {
            background: var(--primary-soft);
            border-color: var(--primary);
        }
        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }
        .stat-icon.total { background: #e3f2fd; color: #1976d2; }
        .stat-icon.pending { background: #fff3e0; color: #f57c00; }
        .stat-icon.progress { background: #e0f2fe; color: #0284c7; }
        .stat-icon.done { background: #d1fae5; color: #059669; }
        .stat-icon.high { background: #fee2e2; color: #dc2626; }
        .stat-content h3 {
            font-size: 22px;
            font-weight: 700;
        }
        .stat-content p {
            font-size: 11px;
            color: var(--gray);
        }
        
        /* الفلاتر */
        .filters-bar {
            background: white;
            border-radius: var(--radius);
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: var(--shadow);
        }
        .filters-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
            gap: 12px;
            align-items: end;
        }
        .filter-group label {
            font-size: 12px;
            font-weight: 600;
            color: var(--gray);
            display: block;
            margin-bottom: 5px;
        }
        .filter-group select,
        .filter-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-family: inherit;
        }
        .apply-btn {
            background: var(--primary);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 10px;
            cursor: pointer;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 5px;
            justify-content: center;
            width: 100%;
        }
        .reset-btn {
            background: #f0f0f0;
            padding: 8px 15px;
            border-radius: 20px;
            text-decoration: none;
            color: #666;
            font-size: 12px;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            margin-top: 10px;
        }
        
        /* قائمة التذاكر */
        .ticket-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        .ticket-item {
            background: white;
            border-radius: var(--radius);
            padding: 15px;
            box-shadow: var(--shadow);
            border-right: 4px solid var(--primary);
            cursor: pointer;
            transition: all 0.2s;
        }
        .ticket-item:active {
            transform: scale(0.98);
        }
        .ticket-item.active {
            background: var(--primary-soft);
        }
        .ticket-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            flex-wrap: wrap;
            gap: 8px;
        }
        .ticket-id {
            font-weight: 800;
            color: var(--primary);
            background: rgba(245,124,0,0.1);
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
        }
        .badge {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 10px;
            font-weight: 600;
        }
        .badge.status-pending { background: #fff3e0; color: #f57c00; }
        .badge.status-in_progress { background: #e3f2fd; color: #1976d2; }
        .badge.status-resolved { background: #e8f5e9; color: #2e7d32; }
        .badge.priority-high { background: #ffebee; color: #c62828; }
        .badge.priority-medium { background: #fff3e0; color: #f57c00; }
        .badge.priority-low { background: #e8f5e9; color: #2e7d32; }
        .ticket-subject {
            font-weight: 600;
            font-size: 14px;
            margin-bottom: 8px;
        }
        .ticket-meta {
            display: flex;
            gap: 12px;
            font-size: 11px;
            color: var(--gray);
            flex-wrap: wrap;
        }
        .ticket-meta span {
            display: flex;
            align-items: center;
            gap: 3px;
        }
        .unread-badge {
            background: var(--primary);
            color: white;
            padding: 2px 8px;
            border-radius: 20px;
            font-size: 10px;
        }
        
        /* المودال */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            display: none;
            align-items: center;
            justify-content: center;
            backdrop-filter: blur(3px);
        }
        .modal.active {
            display: flex;
        }
        .modal-content {
            background: white;
            border-radius: 20px;
            width: 90%;
            max-width: 500px;
            max-height: 90vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        .modal-header {
            background: linear-gradient(135deg, var(--primary), #FF9800);
            color: white;
            padding: 15px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .modal-header h3 {
            flex: 1;
            font-size: 16px;
            margin: 0;
        }
        .close-modal {
            background: rgba(255,255,255,0.2);
            border: none;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            color: white;
            font-size: 1.2rem;
            cursor: pointer;
        }
        .modal-messages {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
            background: #f8fafc;
            max-height: 50vh;
        }
        .msg {
            margin-bottom: 15px;
            max-width: 85%;
        }
        .msg.customer {
            margin-left: auto;
        }
        .msg.admin {
            margin-right: auto;
        }
        .msg.system {
            margin: 0 auto;
            text-align: center;
            max-width: 90%;
        }
        .msg-bubble {
            padding: 10px 14px;
            border-radius: 18px;
            font-size: 13px;
            line-height: 1.45;
            word-break: break-word;
        }
        .msg.customer .msg-bubble {
            background: linear-gradient(135deg, var(--primary), #FF9800);
            color: white;
            border-top-left-radius: 4px;
        }
        .msg.admin .msg-bubble {
            background: white;
            border: 1px solid #ddd;
            border-top-right-radius: 4px;
        }
        .msg.system .msg-bubble {
            background: #e9ecef;
            color: #666;
            font-size: 11px;
        }
        .msg-attachment {
            max-width: 150px;
            margin-top: 6px;
            border-radius: 8px;
            cursor: pointer;
            overflow: hidden;
        }
        .msg-attachment img {
            width: 100%;
            border-radius: 8px;
        }
        .msg-time {
            font-size: 9px;
            color: #999;
            margin-top: 3px;
        }
        .modal-footer {
            padding: 15px;
            border-top: 1px solid #eee;
            background: white;
        }
        .reply-form {
            display: flex;
            gap: 10px;
        }
        .reply-input {
            flex: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 24px;
            resize: none;
            font-family: inherit;
            font-size: 13px;
            min-height: 45px;
        }
        .send-btn {
            width: 45px;
            height: 45px;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            font-size: 1.2rem;
        }
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        
        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            .filters-grid {
                grid-template-columns: 1fr;
            }
            .msg {
                max-width: 90%;
            }
        }
        @media (max-width: 576px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }
            .ticket-header {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <!-- إحصائيات -->
    <div class="stats-grid">
        <a href="?status=all<?php echo $selected_ticket_id ? '&ticket_id='.$selected_ticket_id : ''; ?>" class="stat-card <?php echo $status_filter == 'all' ? 'active' : ''; ?>">
            <div class="stat-icon total"><i class="bi bi-ticket-detailed"></i></div>
            <div class="stat-content"><h3><?php echo $total; ?></h3><p>إجمالي التذاكر</p></div>
        </a>
        <a href="?status=pending<?php echo $selected_ticket_id ? '&ticket_id='.$selected_ticket_id : ''; ?>" class="stat-card <?php echo $status_filter == 'pending' ? 'active' : ''; ?>">
            <div class="stat-icon pending"><i class="bi bi-hourglass-split"></i></div>
            <div class="stat-content"><h3><?php echo $pending; ?></h3><p>في الانتظار</p></div>
        </a>
        <a href="?status=in_progress<?php echo $selected_ticket_id ? '&ticket_id='.$selected_ticket_id : ''; ?>" class="stat-card <?php echo $status_filter == 'in_progress' ? 'active' : ''; ?>">
            <div class="stat-icon progress"><i class="bi bi-gear"></i></div>
            <div class="stat-content"><h3><?php echo $in_progress; ?></h3><p>قيد المعالجة</p></div>
        </a>
        <a href="?status=resolved<?php echo $selected_ticket_id ? '&ticket_id='.$selected_ticket_id : ''; ?>" class="stat-card <?php echo $status_filter == 'resolved' ? 'active' : ''; ?>">
            <div class="stat-icon done"><i class="bi bi-check-circle"></i></div>
            <div class="stat-content"><h3><?php echo $resolved; ?></h3><p>تم الحل</p></div>
        </a>
        <a href="?priority=high<?php echo $selected_ticket_id ? '&ticket_id='.$selected_ticket_id : ''; ?>" class="stat-card <?php echo $priority_filter == 'high' ? 'active' : ''; ?>">
            <div class="stat-icon high"><i class="bi bi-exclamation-triangle"></i></div>
            <div class="stat-content"><h3><?php echo $high_priority; ?></h3><p>أولوية عالية</p></div>
        </a>
    </div>
    
    <!-- فلتر -->
    <div class="filters-bar">
        <form method="GET" class="filters-grid">
            <?php if ($selected_ticket_id): ?>
                <input type="hidden" name="ticket_id" value="<?php echo $selected_ticket_id; ?>">
            <?php endif; ?>
            <div class="filter-group">
                <label>الحالة</label>
                <select name="status">
                    <option value="all" <?php echo $status_filter == 'all' ? 'selected' : ''; ?>>الكل</option>
                    <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>قيد الانتظار</option>
                    <option value="in_progress" <?php echo $status_filter == 'in_progress' ? 'selected' : ''; ?>>قيد المعالجة</option>
                    <option value="resolved" <?php echo $status_filter == 'resolved' ? 'selected' : ''; ?>>تم الحل</option>
                </select>
            </div>
            <div class="filter-group">
                <label>الأولوية</label>
                <select name="priority">
                    <option value="all" <?php echo $priority_filter == 'all' ? 'selected' : ''; ?>>الكل</option>
                    <option value="high" <?php echo $priority_filter == 'high' ? 'selected' : ''; ?>>عالية</option>
                    <option value="medium" <?php echo $priority_filter == 'medium' ? 'selected' : ''; ?>>متوسطة</option>
                    <option value="low" <?php echo $priority_filter == 'low' ? 'selected' : ''; ?>>منخفضة</option>
                </select>
            </div>
            <div class="filter-group">
                <label>بحث</label>
                <input type="text" name="search" placeholder="بحث..." value="<?php echo htmlspecialchars($search_filter); ?>">
            </div>
            <div class="filter-group">
                <button type="submit" class="apply-btn"><i class="bi bi-search"></i> بحث</button>
            </div>
        </form>
        <div style="margin-top: 10px; text-align: left;">
            <a href="?reset=1<?php echo $selected_ticket_id ? '&ticket_id='.$selected_ticket_id : ''; ?>" class="reset-btn"><i class="bi bi-arrow-repeat"></i> إعادة تعيين</a>
        </div>
    </div>
    
    <!-- قائمة التذاكر -->
    <div class="ticket-list">
        <?php if ($tickets_result && $tickets_result->num_rows > 0): ?>
            <?php while($ticket = $tickets_result->fetch_assoc()): ?>
            <div class="ticket-item <?php echo ($ticket['unread'] ?? 0) > 0 ? 'unread' : ''; ?> <?php echo $selected_ticket_id == $ticket['id'] ? 'active' : ''; ?>"
                 onclick="openTicket(<?php echo $ticket['id']; ?>)">
                <div class="ticket-header">
                    <span class="ticket-id">#<?php echo str_pad($ticket['id'], 4, '0', STR_PAD_LEFT); ?></span>
                    <div style="display: flex; gap: 6px;">
                        <span class="badge status-<?php echo $ticket['status']; ?>"><?php echo ['pending'=>'انتظار','in_progress'=>'معالجة','resolved'=>'مغلق'][$ticket['status']]; ?></span>
                        <span class="badge priority-<?php echo $ticket['priority']; ?>"><?php echo ['high'=>'عالي','medium'=>'متوسط','low'=>'منخفض'][$ticket['priority']]; ?></span>
                    </div>
                </div>
                <div class="ticket-subject"><?php echo htmlspecialchars($ticket['subject']); ?></div>
                <div class="ticket-meta">
                    <span><i class="bi bi-person"></i> <?php echo htmlspecialchars($ticket['customer_name'] ?? 'عميل'); ?></span>
                    <span><i class="bi bi-telephone"></i> <?php echo htmlspecialchars($ticket['customer_phone'] ?? '---'); ?></span>
                    <span><i class="bi bi-clock"></i> <?php echo date('d/m/Y H:i', strtotime($ticket['created_at'])); ?></span>
                    <?php if (($ticket['unread'] ?? 0) > 0): ?>
                        <span class="unread-badge"><?php echo $ticket['unread']; ?> جديد</span>
                    <?php endif; ?>
                </div>
                <?php if (!empty($ticket['last_message'])): ?>
                <div class="ticket-meta" style="margin-top: 8px; border-top: 1px dashed #eee; padding-top: 8px;">
                    <span><i class="bi bi-chat"></i> <?php echo htmlspecialchars(mb_substr($ticket['last_message'], 0, 50)); ?>...</span>
                </div>
                <?php endif; ?>
            </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="empty-state"><i class="bi bi-inbox" style="font-size: 48px;"></i><p>لا توجد تذاكر</p></div>
        <?php endif; ?>
    </div>
</div>

<!-- مودال التذكرة -->
<div class="modal" id="ticketModal">
    <div class="modal-content">
        <div class="modal-header">
            <button class="close-modal" onclick="closeModal()"><i class="bi bi-x-lg"></i></button>
            <h3 id="modalTitle">#0000</h3>
            <div id="modalStatus"></div>
        </div>
        <div class="modal-messages" id="modalMessages">
            <div class="empty-state">جاري التحميل...</div>
        </div>
        <div class="modal-footer" id="modalFooter">
            <form class="reply-form" onsubmit="sendReply(event)">
                <input type="hidden" id="replyTicketId" value="">
                <textarea class="reply-input" id="replyMessage" placeholder="اكتب ردك هنا..." required></textarea>
                <button type="submit" class="send-btn"><i class="bi bi-send-fill"></i></button>
            </form>
        </div>
    </div>
</div>

<script>
function openTicket(ticketId) {
    document.getElementById('modalTitle').innerHTML = '#' + ticketId.toString().padStart(4, '0');
    document.getElementById('replyTicketId').value = ticketId;
    document.getElementById('ticketModal').classList.add('active');
    
    var formData = new FormData();
    formData.append('action', 'fetch_messages');
    formData.append('ticket_id', ticketId);
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
        if (data.success) {
            var statusHtml = '';
            if (data.ticket.status == 'pending') statusHtml = '<span class="badge status-pending">⏳ انتظار</span>';
            else if (data.ticket.status == 'in_progress') statusHtml = '<span class="badge status-in_progress">⚙️ معالجة</span>';
            else statusHtml = '<span class="badge status-resolved">✅ مغلق</span>';
            document.getElementById('modalStatus').innerHTML = statusHtml;
            
            var container = document.getElementById('modalMessages');
            if (data.messages.length > 0) {
                container.innerHTML = '';
                for (var i = 0; i < data.messages.length; i++) {
                    var msg = data.messages[i];
                    var msgDiv = document.createElement('div');
                    msgDiv.className = 'msg ' + msg.sender;
                    var html = '<div class="msg-bubble">' + escapeHtml(msg.message).replace(/\n/g, '<br>');
                    if (msg.image) {
                        html += '<div class="msg-attachment" onclick="window.open(\'' + msg.image + '\', \'_blank\')">';
                        html += '<img src="' + msg.image + '" alt="مرفق">';
                        html += '</div>';
                    }
                    html += '</div><div class="msg-time">' + msg.time + '</div>';
                    msgDiv.innerHTML = html;
                    container.appendChild(msgDiv);
                }
                container.scrollTop = container.scrollHeight;
            } else {
                container.innerHTML = '<div class="empty-state"><i class="bi bi-chat-dots"></i><p>لا توجد رسائل بعد</p></div>';
            }
            
            var footer = document.getElementById('modalFooter');
            if (data.ticket.status == 'resolved') {
                footer.innerHTML = '<div style="text-align: center; padding: 10px; color: #999;"><i class="bi bi-check-circle"></i> هذه التذكرة مغلقة</div>';
            } else {
                footer.innerHTML = '<form class="reply-form" onsubmit="sendReply(event)"><input type="hidden" id="replyTicketId" value="' + ticketId + '"><textarea class="reply-input" id="replyMessage" placeholder="اكتب ردك هنا..." required></textarea><button type="submit" class="send-btn"><i class="bi bi-send-fill"></i></button></form>';
            }
        } else {
            document.getElementById('modalMessages').innerHTML = '<div class="empty-state">' + data.message + '</div>';
        }
    })
    .catch(function(error) {
        console.error('خطأ:', error);
        document.getElementById('modalMessages').innerHTML = '<div class="empty-state">حدث خطأ في الاتصال</div>';
    });
}

function sendReply(event) {
    event.preventDefault();
    var ticketId = document.getElementById('replyTicketId').value;
    var message = document.getElementById('replyMessage').value.trim();
    
    if (!message) return;
    
    var formData = new FormData();
    formData.append('send_reply', '1');
    formData.append('ticket_id', ticketId);
    formData.append('message', message);
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(function() {
        document.getElementById('replyMessage').value = '';
        openTicket(ticketId);
        setTimeout(function() { location.reload(); }, 500);
    })
    .catch(function(error) {
        console.error('خطأ:', error);
    });
}

function closeModal() {
    document.getElementById('ticketModal').classList.remove('active');
}

function escapeHtml(text) {
    if (!text) return '';
    var div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeModal();
});

<?php if ($selected_ticket_id): ?>
window.addEventListener('load', function() {
    openTicket(<?php echo $selected_ticket_id; ?>);
});
<?php endif; ?>
</script>
</body>
</html>