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

$tStatus = $currentTicket['status'];
$tPriority = $currentTicket['priority'];
$tDept = $currentTicket['department'];

// ترجمه دپارتمان
$depts = [
    'support' => 'پشتیبانی عمومی',
    'technical' => 'فنی و شبکه',
    'sales' => 'فروش و مالی',
    'management' => 'مدیریت و شکایات'
];
$deptName = $depts[$tDept] ?? $tDept;

// استایل وضعیت
$statusBadge = '';
switch ($tStatus) {
    case 'open': $statusBadge = '<span class="bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 px-3 py-1.5 rounded-xl text-xs font-bold shadow-sm">🟢 باز</span>'; break;
    case 'answered': $statusBadge = '<span class="bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 px-3 py-1.5 rounded-xl text-xs font-bold shadow-sm">🔵 پاسخ داده شده</span>'; break;
    case 'pending': $statusBadge = '<span class="bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400 px-3 py-1.5 rounded-xl text-xs font-bold shadow-sm">⏳ در انتظار پاسخ</span>'; break;
    case 'closed': $statusBadge = '<span class="bg-gray-100 text-gray-700 dark:bg-slate-700 dark:text-gray-400 px-3 py-1.5 rounded-xl text-xs font-bold shadow-sm">⚫ بسته شده</span>'; break;
}
?>

<div class="mb-6 flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white dark:bg-slate-800 p-6 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700">
    <div class="flex-1">
        <div class="flex items-center gap-3 mb-2">
            <h2 class="text-xl font-black text-gray-800 dark:text-white truncate max-w-xl">
                <?php echo htmlspecialchars($currentTicket['subject']); ?>
            </h2>
            <?php echo $statusBadge; ?>
        </div>
        <div class="flex items-center gap-4 text-xs font-bold text-gray-500 dark:text-gray-400">
            <span class="font-mono bg-gray-100 dark:bg-slate-700 px-2 py-1 rounded-lg">#TCK-<?php echo $currentTicket['id']; ?></span>
            <span class="text-indigo-600 dark:text-indigo-400">📁 <?php echo $deptName; ?></span>
            <span>👤 <?php echo htmlspecialchars($currentTicket['fullname'] ?: $currentTicket['username']); ?></span>
        </div>
    </div>
    
    <div class="flex gap-2 w-full md:w-auto shrink-0">
        <a href="tickets.php" class="bg-gray-100 hover:bg-gray-200 text-gray-700 dark:bg-slate-700 dark:hover:bg-slate-600 dark:text-gray-300 font-bold py-2.5 px-6 rounded-xl transition shadow-sm w-full md:w-auto text-center text-sm">
            بازگشت 🔙
        </a>
        <?php if ($isAdmin && $tStatus !== 'closed'): ?>
        <form method="POST" class="w-full md:w-auto">
            <input type="hidden" name="action" value="change_status">
            <input type="hidden" name="ticket_id" value="<?php echo $currentTicket['id']; ?>">
            <input type="hidden" name="status_val" value="closed">
            <button type="submit" onclick="return confirm('آیا از بستن این تیکت مطمئن هستید؟');" class="bg-rose-500 hover:bg-rose-600 text-white font-bold py-2.5 px-6 rounded-xl transition shadow-sm w-full text-center text-sm">
                بستن تیکت 🔒
            </button>
        </form>
        <?php endif; ?>
    </div>
</div>

<div class="bg-[#f0f2f5] dark:bg-[#0f172a] rounded-3xl shadow-inner border border-gray-200 dark:border-slate-700 p-4 md:p-8 mb-6 h-[500px] md:h-[600px] overflow-y-auto custom-scrollbar flex flex-col space-y-6" id="chatContainer">
    
    <div class="text-center">
        <span class="bg-gray-200 dark:bg-slate-700/50 text-gray-500 dark:text-gray-400 text-[10px] font-bold px-4 py-1.5 rounded-full">
            شروع گفتگو - <?php echo format_shamsi($currentTicket['created_at']); ?>
        </span>
    </div>

    <?php foreach($ticketMessages as $msg): 
        $isMe = ($msg['user_id'] == $userId);
        $isAdminMsg = ($msg['role'] == 'admin');
        $senderName = !empty($msg['fullname']) ? htmlspecialchars($msg['fullname']) : htmlspecialchars($msg['username']);
        
        // استایل حباب چت بر اساس فرستنده
        if ($isMe) {
            $bubbleClass = "bg-blue-600 text-white rounded-2xl rounded-tl-sm shadow-md";
            $alignClass = "self-start flex-row";
            $nameColor = "text-blue-100";
            $timeColor = "text-blue-200";
        } else {
            if ($isAdminMsg) {
                $bubbleClass = "bg-white dark:bg-slate-800 text-gray-800 dark:text-gray-200 border border-emerald-100 dark:border-emerald-900/50 rounded-2xl rounded-tr-sm shadow-md";
                $alignClass = "self-end flex-row-reverse";
                $nameColor = "text-emerald-600 dark:text-emerald-400";
            } else {
                $bubbleClass = "bg-white dark:bg-slate-800 text-gray-800 dark:text-gray-200 border border-gray-100 dark:border-slate-700 rounded-2xl rounded-tr-sm shadow-md";
                $alignClass = "self-end flex-row-reverse";
                $nameColor = "text-gray-500 dark:text-gray-400";
            }
            $timeColor = "text-gray-400 dark:text-gray-500";
        }
    ?>
    
    <div class="flex <?php echo $alignClass; ?> w-full max-w-[90%] md:max-w-[75%]">
        <div class="shrink-0 mx-3">
            <div class="w-10 h-10 rounded-full flex items-center justify-center font-black text-lg shadow-sm <?php echo $isMe ? 'bg-blue-500 text-white' : ($isAdminMsg ? 'bg-emerald-500 text-white' : 'bg-gray-300 dark:bg-slate-600 text-gray-600 dark:text-gray-300'); ?>">
                <?php echo mb_substr($senderName, 0, 1, "UTF-8"); ?>
            </div>
        </div>
        
        <div class="<?php echo $bubbleClass; ?> p-4 md:p-5 flex flex-col relative">
            <div class="flex justify-between items-center mb-3 border-b <?php echo $isMe ? 'border-blue-500/50' : 'border-gray-100 dark:border-slate-700'; ?> pb-2 gap-8">
                <span class="font-black text-sm <?php echo $nameColor; ?>">
                    <?php echo $senderName; ?> <?php if($isAdminMsg && !$isMe) echo '<span class="bg-emerald-100 text-emerald-700 dark:bg-emerald-900/50 dark:text-emerald-400 px-2 py-0.5 rounded text-[9px] mr-1">پشتیبانی</span>'; ?>
                </span>
                <span class="text-[10px] font-mono <?php echo $timeColor; ?>" dir="ltr">
                    <?php echo format_shamsi($msg['created_at']); ?>
                </span>
            </div>
            
            <div class="text-sm leading-loose whitespace-pre-wrap font-medium <?php echo $isMe ? 'text-white' : 'text-gray-700 dark:text-gray-300'; ?>"><?php echo htmlspecialchars($msg['message']); ?></div>
            
            <?php if (!empty($msg['attachment'])): ?>
            <div class="mt-4 pt-3 border-t <?php echo $isMe ? 'border-blue-500/50' : 'border-gray-100 dark:border-slate-700'; ?>">
                <a href="../../uploads/tickets/<?php echo $msg['attachment']; ?>" target="_blank" class="flex items-center gap-2 text-xs font-bold <?php echo $isMe ? 'text-blue-100 hover:text-white' : 'text-blue-600 dark:text-blue-400 hover:underline'; ?>">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"></path></svg>
                    دانلود پیوست
                </a>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    
</div>

<?php if($tStatus !== 'closed'): ?>
<div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-5 md:p-6 relative">
    <form method="POST" enctype="multipart/form-data" class="flex flex-col md:flex-row gap-4">
        <input type="hidden" name="action" value="reply_ticket">
        <input type="hidden" name="ticket_id" value="<?php echo $currentTicket['id']; ?>">
        
        <div class="flex-1 relative">
            <textarea name="message" required rows="2" placeholder="پاسخ خود را اینجا بنویسید..." class="w-full border-2 border-gray-200 dark:border-slate-600 p-4 pl-12 rounded-2xl focus:border-blue-500 outline-none text-sm bg-gray-50 dark:bg-slate-900 dark:text-white resize-none custom-scrollbar shadow-inner"></textarea>
            
            <label class="absolute left-3 bottom-3 cursor-pointer bg-gray-200 hover:bg-gray-300 dark:bg-slate-700 dark:hover:bg-slate-600 text-gray-600 dark:text-gray-300 p-2 rounded-xl transition shadow-sm" title="پیوست فایل">
                <svg class="w-5 h-5 transform -rotate-45" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"></path></svg>
                <input type="file" name="attachment" accept=".jpg,.png,.pdf,.zip,.rar" class="hidden">
            </label>
        </div>
        
        <div class="shrink-0 flex items-end">
            <button type="submit" class="w-full md:w-auto h-14 bg-blue-600 hover:bg-blue-700 text-white font-black px-8 rounded-2xl shadow-lg transition flex items-center justify-center gap-2">
                ارسال
                <svg class="w-5 h-5 transform rotate-90" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path></svg>
            </button>
        </div>
    </form>
    <div id="fileNameDisplay" class="text-xs text-blue-600 dark:text-blue-400 font-bold mt-2 ml-2 hidden"></div>
</div>

<script>
// اسکرول خودکار به انتهای چت هنگام لود صفحه
document.addEventListener("DOMContentLoaded", function() {
    const chatContainer = document.getElementById("chatContainer");
    chatContainer.scrollTop = chatContainer.scrollHeight;
    
    // نمایش نام فایل پیوست
    const fileInput = document.querySelector('input[type="file"]');
    const fileDisplay = document.getElementById('fileNameDisplay');
    
    fileInput.addEventListener('change', function() {
        if(this.files && this.files.length > 0) {
            fileDisplay.textContent = '📎 فایل انتخاب شد: ' + this.files[0].name;
            fileDisplay.classList.remove('hidden');
        } else {
            fileDisplay.classList.add('hidden');
        }
    });
});
</script>

<?php else: ?>
<div class="bg-gray-100 dark:bg-slate-800/50 border border-gray-200 dark:border-slate-700 rounded-3xl p-6 text-center shadow-inner">
    <div class="text-4xl mb-3 opacity-50">🔒</div>
    <h3 class="text-gray-700 dark:text-gray-300 font-black mb-1">این تیکت بسته شده است</h3>
    <p class="text-gray-500 dark:text-gray-400 text-xs font-bold">امکان ارسال پاسخ جدید در این تیکت وجود ندارد. در صورت نیاز، تیکت جدیدی ایجاد کنید.</p>
</div>
<?php endif; ?>