<?php
// modules/tickets/widgets/list_tickets.php
if (basename($_SERVER['PHP_SELF']) == 'list_tickets.php') { die('Access Denied'); }

// توابع کمکی برای ظاهر جدول و ترجمه وضعیت‌ها
if (!function_exists('getStatusBadge')) {
    function getStatusBadge($status) {
        switch ($status) {
            case 'open': return '<span class="bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 px-3 py-1 rounded-lg text-xs font-bold shadow-sm">🟢 باز (جدید)</span>';
            case 'answered': return '<span class="bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 px-3 py-1 rounded-lg text-xs font-bold shadow-sm">🔵 پاسخ داده شده</span>';
            case 'pending': return '<span class="bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400 px-3 py-1 rounded-lg text-xs font-bold shadow-sm">⏳ در انتظار پاسخ شما</span>';
            case 'closed': return '<span class="bg-gray-100 text-gray-700 dark:bg-slate-700 dark:text-gray-400 px-3 py-1 rounded-lg text-xs font-bold shadow-sm">⚫ بسته شده</span>';
            default: return '<span class="bg-gray-100 text-gray-700 px-3 py-1 rounded-lg text-xs font-bold">ناشناخته</span>';
        }
    }
}

if (!function_exists('getPriorityBadge')) {
    function getPriorityBadge($priority) {
        switch ($priority) {
            case 'high': return '<span class="text-rose-600 dark:text-rose-400 font-black text-xs">🔴 زیاد</span>';
            case 'medium': return '<span class="text-amber-600 dark:text-amber-400 font-bold text-xs">🟠 متوسط</span>';
            case 'low': return '<span class="text-emerald-600 dark:text-emerald-400 font-bold text-xs">🟢 کم</span>';
            default: return $priority;
        }
    }
}

if (!function_exists('getDepartmentName')) {
    function getDepartmentName($dept) {
        $depts = [
            'support' => 'پشتیبانی عمومی',
            'technical' => 'فنی و شبکه',
            'sales' => 'فروش و مالی',
            'management' => 'مدیریت و شکایات'
        ];
        return $depts[$dept] ?? $dept;
    }
}
?>

<?php if ($isAdmin): ?>
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
    <div class="bg-white dark:bg-slate-800 p-5 rounded-3xl shadow-sm border border-emerald-100 dark:border-emerald-900/30 border-r-4 border-r-emerald-500 transition hover:-translate-y-1 hover:shadow-md">
        <div class="text-xs text-gray-500 dark:text-gray-400 font-bold mb-1">تیکت‌های باز (جدید)</div>
        <div class="text-3xl font-black text-emerald-600 dark:text-emerald-400"><?php echo isset($adminStats['open']) ? $adminStats['open'] : 0; ?></div>
    </div>
    <div class="bg-white dark:bg-slate-800 p-5 rounded-3xl shadow-sm border border-amber-100 dark:border-amber-900/30 border-r-4 border-r-amber-500 transition hover:-translate-y-1 hover:shadow-md">
        <div class="text-xs text-gray-500 dark:text-gray-400 font-bold mb-1">در انتظار پاسخ کاربر</div>
        <div class="text-3xl font-black text-amber-600 dark:text-amber-400"><?php echo isset($adminStats['pending']) ? $adminStats['pending'] : 0; ?></div>
    </div>
    <div class="bg-white dark:bg-slate-800 p-5 rounded-3xl shadow-sm border border-blue-100 dark:border-blue-900/30 border-r-4 border-r-blue-500 transition hover:-translate-y-1 hover:shadow-md">
        <div class="text-xs text-gray-500 dark:text-gray-400 font-bold mb-1">پاسخ داده شده</div>
        <div class="text-3xl font-black text-blue-600 dark:text-blue-400"><?php echo isset($adminStats['answered']) ? $adminStats['answered'] : 0; ?></div>
    </div>
    <div class="bg-white dark:bg-slate-800 p-5 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 border-r-4 border-r-gray-500 transition hover:-translate-y-1 hover:shadow-md">
        <div class="text-xs text-gray-500 dark:text-gray-400 font-bold mb-1">تیکت‌های بسته شده</div>
        <div class="text-3xl font-black text-gray-600 dark:text-gray-300"><?php echo isset($adminStats['closed']) ? $adminStats['closed'] : 0; ?></div>
    </div>
</div>
<?php endif; ?>

<?php if (!$isAdmin): ?>
<div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6 md:p-8 border-t-8 border-t-blue-500 mb-8">
    <h2 class="text-xl font-black text-gray-800 dark:text-white mb-6 flex items-center gap-2">
        <span class="text-2xl">📝</span> ارسال تیکت پشتیبانی جدید
    </h2>
    <form method="POST" enctype="multipart/form-data" class="space-y-5">
        <input type="hidden" name="action" value="create_ticket">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
            <div class="md:col-span-2">
                <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">عنوان تیکت <span class="text-red-500">*</span></label>
                <input type="text" name="subject" required placeholder="موضوع درخواست خود را کوتاه بنویسید..." class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl focus:border-blue-500 outline-none font-bold text-gray-800 dark:text-gray-200 bg-transparent">
            </div>
            <div>
                <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">دپارتمان مربوطه <span class="text-red-500">*</span></label>
                <select name="department" required class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl focus:border-blue-500 outline-none font-bold text-sm bg-gray-50 dark:bg-slate-700 dark:text-white">
                    <option value="support">پشتیبانی عمومی</option>
                    <option value="technical">فنی و شبکه</option>
                    <option value="sales">فروش و مالی</option>
                    <option value="management">مدیریت و شکایات</option>
                </select>
            </div>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
            <div class="md:col-span-2">
                <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">متن درخواست <span class="text-red-500">*</span></label>
                <textarea name="message" required rows="4" placeholder="توضیحات کامل درخواست یا مشکل خود را با جزئیات اینجا بنویسید..." class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl focus:border-blue-500 outline-none text-sm bg-transparent dark:text-white resize-none"></textarea>
            </div>
            <div class="flex flex-col space-y-5">
                <div>
                    <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">اولویت رسیدگی</label>
                    <select name="priority" class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl focus:border-blue-500 outline-none font-bold text-sm bg-gray-50 dark:bg-slate-700 dark:text-white">
                        <option value="medium">🟠 متوسط</option>
                        <option value="high">🔴 زیاد (فقط برای قطعی سرور)</option>
                        <option value="low">🟢 کم (سوالات متداول)</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">پیوست عکس/فایل (اختیاری)</label>
                    <input type="file" name="attachment" accept=".jpg,.jpeg,.png,.pdf,.zip,.rar" class="w-full border-2 border-gray-200 dark:border-slate-600 p-2 rounded-xl bg-gray-50 dark:bg-slate-700 text-xs dark:text-white">
                </div>
            </div>
        </div>
        <div class="flex justify-end">
            <button type="submit" class="w-full md:w-auto bg-blue-600 hover:bg-blue-700 text-white font-black py-3.5 px-10 rounded-xl shadow-md transition transform hover:-translate-y-1 text-base">ثبت و ارسال تیکت 🚀</button>
        </div>
    </form>
</div>
<?php endif; ?>

<div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6 md:p-8 border-t-8 <?php echo $isAdmin ? 'border-t-rose-500' : 'border-t-gray-400'; ?>">
    <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-bold text-gray-800 dark:text-white flex items-center gap-2">
            <svg class="w-6 h-6 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 002-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path></svg>
            <?php echo $isAdmin ? 'مدیریت کل تیکت‌های شبکه' : 'تاریخچه تیکت‌های شما'; ?>
        </h2>
    </div>

    <div class="overflow-x-auto pb-4">
        <table id="ticketsTable" class="w-full text-sm text-right text-gray-600 dark:text-gray-400">
            <thead class="bg-gray-100 dark:bg-slate-700/50 text-gray-700 dark:text-gray-300">
                <tr>
                    <th class="px-4 py-3 rounded-tr-xl">شماره</th>
                    <?php if($isAdmin): ?><th class="px-4 py-3">ارسال کننده</th><?php endif; ?>
                    <th class="px-4 py-3">عنوان تیکت</th>
                    <th class="px-4 py-3 text-center">دپارتمان</th>
                    <th class="px-4 py-3 text-center">اولویت</th>
                    <th class="px-4 py-3 text-center">وضعیت</th>
                    <th class="px-4 py-3 text-left">آخرین بروزرسانی</th>
                    <th class="px-4 py-3 text-center rounded-tl-xl">عملیات</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100 dark:divide-slate-700">
                <?php foreach($tickets as $t): 
                    $senderName = !empty($t['fullname']) ? htmlspecialchars($t['fullname']) : htmlspecialchars($t['username'] ?? 'ناشناس');
                ?>
                    <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/30 transition">
                        <td class="px-4 py-4 font-mono text-xs text-gray-400">#TCK-<?php echo $t['id']; ?></td>
                        
                        <?php if($isAdmin): ?>
                            <td class="px-4 py-4 font-bold text-gray-800 dark:text-gray-200"><?php echo $senderName; ?></td>
                        <?php endif; ?>
                        
                        <td class="px-4 py-4 font-bold text-gray-800 dark:text-gray-200 truncate max-w-[200px]" title="<?php echo htmlspecialchars($t['subject']); ?>"><?php echo htmlspecialchars($t['subject']); ?></td>
                        <td class="px-4 py-4 text-xs font-bold text-indigo-600 dark:text-indigo-400 text-center"><?php echo getDepartmentName($t['department']); ?></td>
                        <td class="px-4 py-4 text-center"><?php echo getPriorityBadge($t['priority']); ?></td>
                        <td class="px-4 py-4 text-center"><?php echo getStatusBadge($t['status']); ?></td>
                        <td class="px-4 py-4 font-mono text-xs text-gray-500 text-left" dir="ltr"><?php echo format_shamsi($t['updated_at']); ?></td>
                        <td class="px-4 py-4 text-center">
                            <a href="tickets.php?id=<?php echo $t['id']; ?>" class="inline-block bg-blue-50 text-blue-600 hover:bg-blue-600 hover:text-white dark:bg-blue-900/30 dark:text-blue-400 dark:hover:bg-blue-600 dark:hover:text-white px-4 py-2 rounded-xl text-xs font-bold transition-all shadow-sm">
                                مشاهده / چت 💬
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script src="/vpnet-panel/assets/js/jquery-3.7.0.min.js"></script>
<script src="/vpnet-panel/assets/js/jquery.dataTables.min.js"></script>

<script>
$(document).ready(function() {
    if ($('#ticketsTable').length && $('#ticketsTable tbody tr').length > 0) {
        $('#ticketsTable').DataTable({
            language: {
                "sEmptyTable": "هیچ تیکتی یافت نشد",
                "sSearch": "جستجوی تیکت:",
                "sInfo": "نمایش _START_ تا _END_ از _TOTAL_ تیکت",
                "oPaginate": { "sNext": "بعدی", "sPrevious": "قبلی" },
                "sLengthMenu": "نمایش _MENU_ سطر"
            },
            order: [], // غیرفعال کردن سورت خودکار برای حفظ ترتیب دیتابیس (بر اساس وضعیت)
            pageLength: 10,
            dom: '<"flex flex-col md:flex-row justify-between items-center mb-4 gap-4"lf>rt<"flex flex-col md:flex-row justify-between items-center mt-4 gap-4"ip>'
        });
    }
});
</script>

<style>
    .dataTables_wrapper .dataTables_filter input { border: 2px solid #e5e7eb; border-radius: 12px; padding: 8px 16px; outline: none; margin-bottom: 10px; }
    html.dark .dataTables_wrapper .dataTables_filter input { background-color: #0f172a; color: #f8fafc; border-color: #334155; }
    .dataTables_wrapper .dataTables_length select { border: 2px solid #e5e7eb; border-radius: 10px; padding: 5px; outline: none; }
    html.dark .dataTables_wrapper .dataTables_length select { background-color: #0f172a; color: #f8fafc; border-color: #334155; }
    html.dark .dataTables_wrapper .dataTables_info { color: #94a3b8 !important; }
    html.dark .dataTables_wrapper .dataTables_paginate .paginate_button { color: #94a3b8 !important; border-color: #334155 !important; }
</style>