<?php
// tickets-content.php - محتوای سیستم تیکتینگ
?>

<!-- ===== پیام ===== -->
<?= $message ?>

<!-- ===== آمار تیکت‌ها ===== -->
<div class="grid grid-cols-2 md:grid-cols-5 gap-3 mb-6">
    <a href="?status=all" class="bg-white rounded-xl p-3 shadow-sm border hover:shadow-md transition text-center <?= $status_filter == 'all' ? 'border-blue-500' : '' ?>">
        <div class="text-lg font-bold text-gray-700"><?= persianNumber($ticketStats['total']) ?></div>
        <div class="text-xs text-gray-400">کل تیکت‌ها</div>
    </a>
    <a href="?status=new" class="bg-white rounded-xl p-3 shadow-sm border hover:shadow-md transition text-center <?= $status_filter == 'new' ? 'border-red-500' : '' ?>">
        <div class="text-lg font-bold text-red-600"><?= persianNumber($ticketStats['new']) ?></div>
        <div class="text-xs text-gray-400">🆕 جدید</div>
    </a>
    <a href="?status=replied" class="bg-white rounded-xl p-3 shadow-sm border hover:shadow-md transition text-center <?= $status_filter == 'replied' ? 'border-yellow-500' : '' ?>">
        <div class="text-lg font-bold text-yellow-600"><?= persianNumber($ticketStats['replied']) ?></div>
        <div class="text-xs text-gray-400">💬 پاسخ داده</div>
    </a>
    <a href="?status=closed" class="bg-white rounded-xl p-3 shadow-sm border hover:shadow-md transition text-center <?= $status_filter == 'closed' ? 'border-green-500' : '' ?>">
        <div class="text-lg font-bold text-green-600"><?= persianNumber($ticketStats['closed']) ?></div>
        <div class="text-xs text-gray-400">✅ بسته</div>
    </a>
    <a href="?status=all&priority=all" class="bg-white rounded-xl p-3 shadow-sm border hover:shadow-md transition text-center <?= $ticketStats['unread'] > 0 ? 'border-red-500' : '' ?>">
        <div class="text-lg font-bold text-blue-600"><?= persianNumber($ticketStats['unread']) ?></div>
        <div class="text-xs text-gray-400">📩 خوانده نشده</div>
    </a>
</div>

<!-- ===== نوار جستجو و فیلتر ===== -->
<div class="bg-gray-50 rounded-xl p-4 mb-6">
    <form method="GET" class="flex flex-wrap gap-3 items-end">
        <div class="flex-1 min-w-[150px]">
            <label class="block text-sm font-semibold text-gray-600 mb-1">وضعیت</label>
            <select name="status" class="w-full px-3 py-2 border rounded-lg text-sm">
                <option value="all" <?= $status_filter == 'all' ? 'selected' : '' ?>>همه</option>
                <option value="new" <?= $status_filter == 'new' ? 'selected' : '' ?>>جدید</option>
                <option value="replied" <?= $status_filter == 'replied' ? 'selected' : '' ?>>پاسخ داده</option>
                <option value="closed" <?= $status_filter == 'closed' ? 'selected' : '' ?>>بسته</option>
            </select>
        </div>
        <div class="flex-1 min-w-[150px]">
            <label class="block text-sm font-semibold text-gray-600 mb-1">اولویت</label>
            <select name="priority" class="w-full px-3 py-2 border rounded-lg text-sm">
                <option value="all" <?= $priority_filter == 'all' ? 'selected' : '' ?>>همه</option>
                <option value="low" <?= $priority_filter == 'low' ? 'selected' : '' ?>>کم</option>
                <option value="medium" <?= $priority_filter == 'medium' ? 'selected' : '' ?>>متوسط</option>
                <option value="high" <?= $priority_filter == 'high' ? 'selected' : '' ?>>بالا</option>
                <option value="critical" <?= $priority_filter == 'critical' ? 'selected' : '' ?>>بحرانی</option>
            </select>
        </div>
        <div class="flex-1 min-w-[200px]">
            <label class="block text-sm font-semibold text-gray-600 mb-1">جستجو</label>
            <input type="text" name="search" placeholder="جستجو در موضوع و متن..." 
                   value="<?= htmlspecialchars($search) ?>" 
                   class="w-full px-3 py-2 border rounded-lg text-sm">
        </div>
        <div>
            <button type="submit" class="btn btn-primary px-6 py-2">
                <i class="fas fa-search"></i> جستجو
            </button>
        </div>
        <div>
            <button type="button" onclick="document.getElementById('newTicketForm').classList.toggle('hidden')" 
                    class="btn btn-success px-6 py-2">
                <i class="fas fa-plus"></i> تیکت جدید
            </button>
        </div>
    </form>
</div>

<!-- ===== فرم ارسال تیکت جدید ===== -->
<div id="newTicketForm" class="hidden bg-white rounded-xl p-6 shadow-lg border mb-6">
    <h4 class="font-bold text-gray-800 text-lg mb-4">📝 تیکت جدید</h4>
    <form method="POST" class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <input type="hidden" name="action" value="send_ticket">
        
        <div class="md:col-span-2">
            <label class="block text-sm font-semibold text-gray-600 mb-1">موضوع <span class="text-red-500">*</span></label>
            <input type="text" name="subject" class="w-full px-4 py-2 border rounded-lg" placeholder="موضوع تیکت" required>
        </div>
        
        <div class="md:col-span-2">
            <label class="block text-sm font-semibold text-gray-600 mb-1">متن <span class="text-red-500">*</span></label>
            <textarea name="body" rows="4" class="w-full px-4 py-2 border rounded-lg" placeholder="متن تیکت..." required></textarea>
        </div>
        
        <div>
            <label class="block text-sm font-semibold text-gray-600 mb-1">ارسال به</label>
            <select name="receiver_type" id="receiverType" class="w-full px-4 py-2 border rounded-lg" onchange="toggleReceiver()">
                <option value="role">یک نقش</option>
                <option value="user">یک مدرس خاص</option>
            </select>
        </div>
        
        <div id="roleSelect">
            <label class="block text-sm font-semibold text-gray-600 mb-1">نقش گیرنده</label>
            <select name="receiver_role_id" class="w-full px-4 py-2 border rounded-lg">
                <option value="">انتخاب نقش...</option>
                <?php foreach ($roles as $role): ?>
                <option value="<?= $role['id'] ?>"><?= htmlspecialchars($role['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div id="userSelect" style="display:none;">
            <label class="block text-sm font-semibold text-gray-600 mb-1">مدرس گیرنده</label>
            <select name="receiver_id" class="w-full px-4 py-2 border rounded-lg">
                <option value="">انتخاب مدرس...</option>
                <?php foreach ($teachers as $teacher): ?>
                <option value="<?= $teacher['id'] ?>">
                    <?= htmlspecialchars($teacher['name'] . ' ' . $teacher['family']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div>
            <label class="block text-sm font-semibold text-gray-600 mb-1">اولویت</label>
            <select name="priority" class="w-full px-4 py-2 border rounded-lg">
                <option value="low">کم</option>
                <option value="medium" selected>متوسط</option>
                <option value="high">بالا</option>
                <option value="critical">بحرانی</option>
            </select>
        </div>
        
        <div class="md:col-span-2 flex gap-3">
            <button type="submit" class="btn btn-primary px-8 py-2">
                <i class="fas fa-paper-plane"></i> ارسال تیکت
            </button>
            <button type="button" onclick="document.getElementById('newTicketForm').classList.add('hidden')" 
                    class="btn bg-gray-200 hover:bg-gray-300 text-gray-700 px-6 py-2">
                انصراف
            </button>
        </div>
    </form>
</div>

<!-- ===== لیست تیکت‌ها و نمایش جزئیات ===== -->
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <!-- ===== لیست تیکت‌ها ===== -->
    <div class="lg:col-span-1">
        <div class="bg-white rounded-xl shadow-sm border h-[600px] overflow-y-auto">
            <?php if (empty($tickets)): ?>
            <div class="p-8 text-center text-gray-400">
                <i class="fas fa-inbox text-4xl block mb-2"></i>
                هیچ تیکتی وجود ندارد
            </div>
            <?php else: ?>
            <?php foreach ($tickets as $ticket): ?>
            <a href="?id=<?= $ticket['id'] ?>&status=<?= $status_filter ?>&priority=<?= $priority_filter ?>&search=<?= urlencode($search) ?>" 
               class="block p-4 border-b hover:bg-gray-50 transition <?= ($ticket_id == $ticket['id']) ? 'bg-blue-50' : '' ?>">
                <div class="flex justify-between items-start">
                    <div class="flex-1">
                        <div class="flex items-center gap-2">
                            <span class="font-medium text-gray-800 text-sm"><?= htmlspecialchars($ticket['subject']) ?></span>
                            <?php if (!$ticket['is_read'] && ($ticket['receiver_id'] == $user['id'] || $ticket['receiver_role_id'] == $user['role_id'])): ?>
                            <span class="badge-danger text-xs">جدید</span>
                            <?php endif; ?>
                        </div>
                        <div class="text-xs text-gray-500 mt-1">
                            از: <?= htmlspecialchars($ticket['sender_name'] . ' ' . $ticket['sender_family']) ?>
                        </div>
                        <div class="text-xs text-gray-400 mt-1">
                            <?= jalaliDate($ticket['created_at']) ?>
                            <span class="mx-1">|</span>
                            <?php
                            $priorityLabels = ['low' => 'کم', 'medium' => 'متوسط', 'high' => 'بالا', 'critical' => 'بحرانی'];
                            $priorityColors = ['low' => 'badge-info', 'medium' => 'badge-warning', 'high' => 'badge-danger', 'critical' => 'badge-danger'];
                            ?>
                            <span class="<?= $priorityColors[$ticket['priority']] ?? 'badge-info' ?> text-xs">
                                <?= $priorityLabels[$ticket['priority']] ?? 'متوسط' ?>
                            </span>
                        </div>
                    </div>
                    <div class="text-left">
                        <?php if ($ticket['status'] == 'new'): ?>
                        <span class="badge-danger text-xs">جدید</span>
                        <?php elseif ($ticket['status'] == 'viewed'): ?>
                        <span class="badge-info text-xs">دیده شده</span>
                        <?php elseif ($ticket['status'] == 'replied'): ?>
                        <span class="badge-warning text-xs">پاسخ</span>
                        <?php elseif ($ticket['status'] == 'closed'): ?>
                        <span class="badge-success text-xs">بسته</span>
                        <?php endif; ?>
                    </div>
                </div>
            </a>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- ===== نمایش تیکت و پاسخ‌ها ===== -->
    <div class="lg:col-span-2">
        <?php if ($selectedTicket): ?>
        <div class="bg-white rounded-xl shadow-sm border p-6">
            <!-- ===== هدر تیکت ===== -->
            <div class="flex justify-between items-start border-b pb-4 mb-4">
                <div>
                    <h3 class="text-xl font-bold text-gray-800"><?= htmlspecialchars($selectedTicket['subject']) ?></h3>
                    <div class="text-sm text-gray-500 mt-1">
                        از: <?= htmlspecialchars($selectedTicket['sender_name'] . ' ' . $selectedTicket['sender_family']) ?>
                        <span class="mx-2">|</span>
                        به: <?= htmlspecialchars($selectedTicket['receiver_name'] ?? $selectedTicket['receiver_role_name'] ?? 'همه') ?>
                        <span class="mx-2">|</span>
                        <?= jalaliDate($selectedTicket['created_at']) ?>
                    </div>
                </div>
                <div class="text-left">
                    <div class="text-sm text-gray-500">وضعیت:</div>
                    <?php if ($selectedTicket['status'] == 'new'): ?>
                    <span class="badge-danger">جدید</span>
                    <?php elseif ($selectedTicket['status'] == 'viewed'): ?>
                    <span class="badge-info">دیده شده</span>
                    <?php elseif ($selectedTicket['status'] == 'replied'): ?>
                    <span class="badge-warning">پاسخ داده</span>
                    <?php elseif ($selectedTicket['status'] == 'closed'): ?>
                    <span class="badge-success">بسته</span>
                    <?php endif; ?>
                    <div class="text-xs text-gray-400 mt-1">
                        اولویت: <?= $priorityLabels[$selectedTicket['priority']] ?? 'متوسط' ?>
                    </div>
                </div>
            </div>
            
            <!-- ===== متن تیکت ===== -->
            <div class="bg-gray-50 rounded-xl p-4 mb-4">
                <p class="text-gray-700 whitespace-pre-wrap"><?= nl2br(htmlspecialchars($selectedTicket['body'])) ?></p>
                <?php if ($selectedTicket['attachment']): ?>
                <div class="mt-3">
                    <a href="uploads/tickets/<?= $selectedTicket['attachment'] ?>" target="_blank" 
                       class="inline-flex items-center gap-2 text-blue-500 hover:text-blue-700">
                        <i class="fas fa-paperclip"></i> دانلود فایل ضمیمه
                    </a>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- ===== دکمه‌های تغییر وضعیت ===== -->
            <div class="flex flex-wrap gap-2 mb-4">
                <?php if ($selectedTicket['status'] != 'closed'): ?>
                <button onclick="changeStatus(<?= $selectedTicket['id'] ?>, 'closed')" 
                        class="btn btn-success btn-sm">
                    <i class="fas fa-check"></i> بستن تیکت
                </button>
                <?php endif; ?>
                <?php if ($selectedTicket['status'] != 'new'): ?>
                <button onclick="changeStatus(<?= $selectedTicket['id'] ?>, 'new')" 
                        class="btn btn-warning btn-sm">
                    <i class="fas fa-undo"></i> بازگشایی
                </button>
                <?php endif; ?>
                <?php if ($_SESSION['role_level'] == 1): ?>
                <button onclick="deleteTicket(<?= $selectedTicket['id'] ?>)" 
                        class="btn btn-danger btn-sm">
                    <i class="fas fa-trash"></i> حذف تیکت
                </button>
                <?php endif; ?>
            </div>
            
            <!-- ===== پاسخ‌ها ===== -->
            <div class="mt-6">
                <h5 class="font-bold text-gray-700 mb-4">📝 پاسخ‌ها (<?= count($replies) ?>)</h5>
                
                <?php if (empty($replies)): ?>
                <p class="text-gray-400 text-center py-4">هنوز پاسخی داده نشده است</p>
                <?php else: ?>
                <div class="space-y-3 max-h-[300px] overflow-y-auto">
                    <?php foreach ($replies as $reply): ?>
                    <div class="bg-gray-50 rounded-xl p-4 <?= $reply['user_id'] == $user['id'] ? 'border-r-4 border-blue-500' : 'border-r-4 border-green-500' ?>">
                        <div class="flex justify-between items-start">
                            <div>
                                <div class="font-medium text-gray-700">
                                    <?= htmlspecialchars($reply['name'] . ' ' . $reply['family']) ?>
                                    <?php if ($reply['user_id'] == $user['id']): ?>
                                    <span class="badge-info text-xs mr-2">شما</span>
                                    <?php endif; ?>
                                </div>
                                <div class="text-xs text-gray-400">
                                    <?= jalaliDate($reply['created_at']) ?>
                                </div>
                            </div>
                        </div>
                        <p class="text-gray-600 mt-2 whitespace-pre-wrap"><?= nl2br(htmlspecialchars($reply['reply_text'])) ?></p>
                        <?php if ($reply['attachment']): ?>
                        <div class="mt-2">
                            <a href="uploads/tickets/<?= $reply['attachment'] ?>" target="_blank" 
                               class="text-blue-500 text-sm hover:text-blue-700">
                                <i class="fas fa-paperclip"></i> دانلود فایل
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                
                <!-- ===== فرم ارسال پاسخ ===== -->
                <?php if ($selectedTicket['status'] != 'closed'): ?>
                <div class="bg-white border border-gray-200 rounded-xl p-4 mt-4">
                    <h6 class="font-bold text-gray-700 mb-3">✏️ ارسال پاسخ</h6>
                    <form method="POST" action="ticket-reply.php" id="replyForm" enctype="multipart/form-data">
                        <input type="hidden" name="ticket_id" value="<?= $selectedTicket['id'] ?>">
                        <div class="form-group">
                            <textarea name="reply_text" id="replyText" rows="3" placeholder="متن پاسخ..." required></textarea>
                        </div>
                        <div class="form-group">
                            <label>ضمیمه (حداکثر ۵ مگابایت)</label>
                            <input type="file" name="attachment" class="w-full">
                        </div>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-reply"></i> ارسال پاسخ
                        </button>
                    </form>
                </div>
                <?php else: ?>
                <div class="bg-gray-100 rounded-xl p-4 text-center text-gray-500">
                    <i class="fas fa-lock"></i> این تیکت بسته شده است و نمی‌توان پاسخ داد.
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php else: ?>
        <div class="bg-white rounded-xl shadow-sm border p-8 text-center text-gray-400">
            <i class="fas fa-envelope-open-text text-6xl block mb-4 opacity-30"></i>
            <p class="text-lg">یک تیکت را انتخاب کنید تا جزئیات آن را ببینید.</p>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
// =============================================
// توابع جاوااسکریپت
// =============================================

function toggleReceiver() {
    var type = document.getElementById('receiverType').value;
    document.getElementById('roleSelect').style.display = (type == 'role') ? 'block' : 'none';
    document.getElementById('userSelect').style.display = (type == 'user') ? 'block' : 'none';
}

// =============================================
// تغییر وضعیت تیکت با Ajax
// =============================================
function changeStatus(ticketId, status) {
    if (!confirm('آیا از تغییر وضعیت تیکت مطمئن هستید؟')) return;
    
    var formData = new FormData();
    formData.append('ticket_id', ticketId);
    formData.append('status', status);
    
    fetch('ticket-status.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('خطا: ' + data.message);
        }
    })
    .catch(error => {
        alert('خطا در ارتباط با سرور');
    });
}

// =============================================
// حذف تیکت با Ajax (فقط مدیر سامانه)
// =============================================
function deleteTicket(ticketId) {
    if (!confirm('آیا از حذف این تیکت مطمئن هستید؟ این عملیات قابل بازگشت نیست.')) return;
    
    var formData = new FormData();
    formData.append('ticket_id', ticketId);
    formData.append('action', 'delete');
    
    fetch('ticket-status.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('تیکت با موفقیت حذف شد.');
            location.href = 'tickets.php';
        } else {
            alert('خطا: ' + data.message);
        }
    })
    .catch(error => {
        alert('خطا در ارتباط با سرور');
    });
}

// =============================================
// ارسال پاسخ با Ajax
// =============================================
document.getElementById('replyForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    var btn = this.querySelector('button[type="submit"]');
    var originalText = btn.innerHTML;
    
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> در حال ارسال...';
    
    fetch('ticket-reply.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('خطا در ارسال پاسخ: ' + data.message);
            btn.disabled = false;
            btn.innerHTML = originalText;
        }
    })
    .catch(error => {
        alert('خطا در ارسال پاسخ');
        btn.disabled = false;
        btn.innerHTML = originalText;
    });
});
</script>