<?php
session_start();
require_once '../../vippanneladmin56329803/config.php';

date_default_timezone_set('Asia/Tehran');

// بررسی لاگین بودن نماینده
if (!isset($_SESSION['agent_id'])) {
    header("Location: ../agent.php");
    exit;
}

// دریافت اطلاعات نماینده
$stmt = $pdo->prepare("SELECT * FROM agents WHERE id = ?");
$stmt->execute([$_SESSION['agent_id']]);
$agent = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$agent) {
    session_destroy();
    header("Location: ../agent.php");
    exit;
}

$success = $error = '';
$active_tab = $_GET['tab'] ?? 'all';

// ایجاد جدول اگر وجود نداشته باشد
$pdo->exec("
CREATE TABLE IF NOT EXISTS `tickets` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `ticket_number` varchar(50) NOT NULL,
    `agent_id` int(11) NOT NULL,
    `agent_name` varchar(255) NOT NULL,
    `agent_token` varchar(255) NOT NULL,
    `subject` varchar(255) NOT NULL,
    `department` enum('technical','financial') NOT NULL DEFAULT 'technical',
    `priority` enum('normal','high') NOT NULL DEFAULT 'normal',
    `message` text NOT NULL,
    `admin_reply` text DEFAULT NULL,
    `admin_reply_at` timestamp NULL DEFAULT NULL,
    `status` enum('pending','answered','closed') NOT NULL DEFAULT 'pending',
    `closed_by` enum('agent','admin') DEFAULT NULL,
    `closed_at` timestamp NULL DEFAULT NULL,
    `system_active` tinyint(1) NOT NULL DEFAULT 1,
    `ticket_limit` int(11) NOT NULL DEFAULT 10,
    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `ticket_number` (`ticket_number`),
    KEY `agent_id` (`agent_id`),
    KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci;
");

// دریافت تنظیمات لیمیت از دیتابیس
$settings_row = $pdo->query("SELECT ticket_limit, system_active FROM tickets LIMIT 1")->fetch(PDO::FETCH_ASSOC);
if ($settings_row) {
    $ticket_limit = $settings_row['ticket_limit'];
    $system_active = $settings_row['system_active'];
} else {
    $ticket_limit = 10;
    $system_active = 1;
}

// دریافت تعداد تیکت‌های فعال نماینده
$active_tickets_count = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE agent_id = ? AND status != 'closed'");
$active_tickets_count->execute([$agent['id']]);
$active_tickets = $active_tickets_count->fetchColumn();

// ارسال تیکت جدید
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_ticket'])) {
    $subject = trim($_POST['subject']);
    $department = $_POST['department'];
    $priority = $_POST['priority'];
    $message = trim($_POST['message']);
    
    if ($system_active == 0) {
        $error = "سیستم تیکت در حال حاضر غیرفعال می‌باشد. لطفاً بعداً تلاش کنید.";
    } elseif (empty($subject)) {
        $error = "لطفاً موضوع تیکت را وارد کنید.";
    } elseif (empty($message)) {
        $error = "لطفاً متن تیکت را وارد کنید.";
    } elseif ($active_tickets >= $ticket_limit) {
        $error = "شما حداکثر می‌توانید {$ticket_limit} تیکت همزمان فعال داشته باشید. لطفاً برخی از تیکت‌های خود را ببندید.";
    } else {
        $ticket_number = 'TKT-' . time() . rand(100, 999);
        
        $stmt = $pdo->prepare("
            INSERT INTO tickets (ticket_number, agent_id, agent_name, agent_token, subject, department, priority, message, status) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')
        ");
        
        if ($stmt->execute([$ticket_number, $agent['id'], $agent['name'], $agent['token'], $subject, $department, $priority, $message])) {
            $success = "تیکت شما با موفقیت ثبت شد. شماره پیگیری: " . $ticket_number;
            $_POST = [];
        } else {
            $error = "خطا در ثبت تیکت. لطفاً مجدداً تلاش کنید.";
        }
    }
}

// بستن تیکت توسط کاربر
if (isset($_GET['close'])) {
    $ticket_id = intval($_GET['close']);
    $stmt = $pdo->prepare("UPDATE tickets SET status = 'closed', closed_by = 'agent', closed_at = NOW(), updated_at = NOW() WHERE id = ? AND agent_id = ? AND status != 'closed'");
    if ($stmt->execute([$ticket_id, $agent['id']])) {
        $success = "تیکت با موفقیت بسته شد.";
    }
}

// دریافت تیکت‌ها بر اساس تب
$tickets = [];
if ($active_tab == 'all') {
    $stmt = $pdo->prepare("SELECT * FROM tickets WHERE agent_id = ? ORDER BY created_at DESC");
    $stmt->execute([$agent['id']]);
    $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
} elseif ($active_tab == 'pending') {
    $stmt = $pdo->prepare("SELECT * FROM tickets WHERE agent_id = ? AND status = 'pending' ORDER BY created_at DESC");
    $stmt->execute([$agent['id']]);
    $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
} elseif ($active_tab == 'answered') {
    $stmt = $pdo->prepare("SELECT * FROM tickets WHERE agent_id = ? AND status = 'answered' ORDER BY created_at DESC");
    $stmt->execute([$agent['id']]);
    $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
} elseif ($active_tab == 'closed') {
    $stmt = $pdo->prepare("SELECT * FROM tickets WHERE agent_id = ? AND status = 'closed' ORDER BY created_at DESC");
    $stmt->execute([$agent['id']]);
    $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// آمار
$count_all = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE agent_id = ?");
$count_all->execute([$agent['id']]);
$count_pending = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE agent_id = ? AND status = 'pending'");
$count_pending->execute([$agent['id']]);
$count_answered = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE agent_id = ? AND status = 'answered'");
$count_answered->execute([$agent['id']]);
$count_closed = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE agent_id = ? AND status = 'closed'");
$count_closed->execute([$agent['id']]);
?>
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>سیستم پشتیبانی | نمایندگی</title>
    <link rel="stylesheet" href="../style.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            background: #f0f2f5;
            font-family: 'Tahoma', 'Segoe UI', sans-serif;
        }
        
        .tickets-container {
            max-width: 1300px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .tickets-header {
            background: white;
            border-radius: 20px;
            padding: 20px 25px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .header-title h1 {
            font-size: 22px;
            color: #1e293b;
            margin-bottom: 5px;
        }
        
        .header-title p {
            font-size: 13px;
            color: #64748b;
        }
        
        .header-stats {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .stat-badge {
            background: #f1f5f9;
            padding: 8px 16px;
            border-radius: 30px;
            font-size: 13px;
            color: #1e293b;
        }
        
        .stat-badge span {
            font-weight: bold;
            color: #3b82f6;
        }
        
        .new-ticket-btn {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: transform 0.2s;
        }
        
        .new-ticket-btn:hover {
            transform: translateY(-2px);
        }
        
        .tabs {
            display: flex;
            gap: 8px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }
        
        .tab-link {
            background: white;
            border: none;
            padding: 10px 24px;
            border-radius: 30px;
            font-size: 14px;
            cursor: pointer;
            color: #64748b;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-block;
        }
        
        .tab-link:hover {
            background: #e2e8f0;
        }
        
        .tab-link.active {
            background: #3b82f6;
            color: white;
        }
        
        .tab-count {
            background: rgba(0,0,0,0.1);
            padding: 2px 8px;
            border-radius: 20px;
            font-size: 11px;
            margin-right: 8px;
        }
        
        .tab-link.active .tab-count {
            background: rgba(255,255,255,0.2);
        }
        
        .tickets-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .ticket-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            transition: all 0.3s;
            border-right: 4px solid;
        }
        
        .ticket-card.pending { border-right-color: #f59e0b; }
        .ticket-card.answered { border-right-color: #10b981; }
        .ticket-card.closed { border-right-color: #94a3b8; }
        
        .ticket-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .ticket-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            flex-wrap: wrap;
            margin-bottom: 12px;
        }
        
        .ticket-info {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .ticket-number {
            font-family: monospace;
            font-size: 13px;
            color: #3b82f6;
            font-weight: bold;
        }
        
        .ticket-subject {
            font-size: 16px;
            font-weight: bold;
            color: #1e293b;
        }
        
        .ticket-badges {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 500;
        }
        
        .badge-technical { background: #dbeafe; color: #2563eb; }
        .badge-financial { background: #dcfce7; color: #16a34a; }
        .badge-normal { background: #e2e8f0; color: #475569; }
        .badge-high { background: #fee2e2; color: #dc2626; }
        .badge-pending { background: #fef3c7; color: #d97706; }
        .badge-answered { background: #d1fae5; color: #059669; }
        .badge-closed { background: #f1f5f9; color: #64748b; }
        
        .ticket-date {
            font-size: 12px;
            color: #94a3b8;
        }
        
        .ticket-message {
            color: #475569;
            font-size: 13px;
            margin: 12px 0;
            padding: 10px;
            background: #f8fafc;
            border-radius: 12px;
            line-height: 1.5;
        }
        
        .ticket-reply {
            background: #f0fdf4;
            border-right: 3px solid #10b981;
            padding: 10px;
            border-radius: 12px;
            margin: 10px 0;
            font-size: 13px;
        }
        
        .ticket-reply strong {
            color: #059669;
        }
        
        .ticket-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
            flex-wrap: wrap;
        }
        
        .btn-view {
            background: #64748b;
            color: white;
            border: none;
            padding: 8px 18px;
            border-radius: 10px;
            font-size: 12px;
            cursor: pointer;
        }
        
        .btn-close {
            background: #ef4444;
            color: white;
            border: none;
            padding: 8px 18px;
            border-radius: 10px;
            font-size: 12px;
            cursor: pointer;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-content {
            background: white;
            border-radius: 24px;
            max-width: 550px;
            width: 90%;
            max-height: 85vh;
            overflow-y: auto;
            padding: 25px;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .modal-header h3 {
            font-size: 20px;
            color: #1e293b;
        }
        
        .close-modal {
            cursor: pointer;
            font-size: 24px;
            color: #94a3b8;
        }
        
        .form-group {
            margin-bottom: 18px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            font-size: 13px;
            color: #1e293b;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            font-size: 14px;
            font-family: inherit;
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 120px;
        }
        
        .submit-btn {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            width: 100%;
        }
        
        .alert {
            padding: 12px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            font-size: 13px;
        }
        
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-right: 3px solid #10b981;
        }
        
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-right: 3px solid #ef4444;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: 20px;
            color: #94a3b8;
        }
        
        .limit-warning {
            background: #fef3c7;
            color: #d97706;
            padding: 10px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .detail-row {
            display: flex;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .detail-label {
            width: 120px;
            font-weight: 600;
            color: #64748b;
        }
        
        .detail-value {
            flex: 1;
            color: #1e293b;
        }
        
        @media (max-width: 768px) {
            .tickets-container {
                padding: 12px;
            }
            .ticket-header {
                flex-direction: column;
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="tickets-container">
        <div class="tickets-header">
            <div class="header-title">
                <h1>سیستم پشتیبانی</h1>
                <p>مدیریت تیکت‌های پشتیبانی فنی و مالی</p>
            </div>
            <div class="header-stats">
                <div class="stat-badge">تیکت فعال: <span><?= $active_tickets ?></span> / <?= $ticket_limit ?></div>
                <button class="new-ticket-btn" onclick="openNewTicketModal()">+ تیکت جدید</button>
            </div>
        </div>
        
        <?php if ($system_active == 0): ?>
            <div class="limit-warning" style="background: #fee2e2; color: #dc2626;">
                سیستم تیکت در حال حاضر غیرفعال می‌باشد. امکان ثبت تیکت جدید وجود ندارد.
            </div>
        <?php endif; ?>
        
        <?php if ($active_tickets >= $ticket_limit - 2 && $active_tickets < $ticket_limit && $system_active == 1): ?>
            <div class="limit-warning">
                شما <?= $active_tickets ?> تیکت فعال دارید. حداکثر مجاز <?= $ticket_limit ?> تیکت همزمان است.
            </div>
        <?php endif; ?>
        
        <?php if ($active_tickets >= $ticket_limit && $system_active == 1): ?>
            <div class="limit-warning" style="background: #fee2e2; color: #dc2626;">
                شما به حداکثر تعداد تیکت همزمان (<?= $ticket_limit ?> عدد) رسیده‌اید. لطفاً برخی از تیکت‌های خود را ببندید.
            </div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        
        <div class="tabs">
            <a href="?tab=all" class="tab-link <?= $active_tab == 'all' ? 'active' : '' ?>">همه تیکت‌ها <span class="tab-count"><?= $count_all->fetchColumn() ?></span></a>
            <a href="?tab=pending" class="tab-link <?= $active_tab == 'pending' ? 'active' : '' ?>">در انتظار پاسخ <span class="tab-count"><?= $count_pending->fetchColumn() ?></span></a>
            <a href="?tab=answered" class="tab-link <?= $active_tab == 'answered' ? 'active' : '' ?>">پاسخ داده شده <span class="tab-count"><?= $count_answered->fetchColumn() ?></span></a>
            <a href="?tab=closed" class="tab-link <?= $active_tab == 'closed' ? 'active' : '' ?>">بسته شده <span class="tab-count"><?= $count_closed->fetchColumn() ?></span></a>
        </div>
        
        <div class="tickets-list">
            <?php if (count($tickets) > 0): ?>
                <?php foreach ($tickets as $ticket): ?>
                    <div class="ticket-card <?= $ticket['status'] ?>">
                        <div class="ticket-header">
                            <div class="ticket-info">
                                <span class="ticket-number"><?= htmlspecialchars($ticket['ticket_number']) ?></span>
                                <span class="ticket-subject"><?= htmlspecialchars($ticket['subject']) ?></span>
                                <div class="ticket-badges">
                                    <span class="badge badge-<?= $ticket['department'] ?>"><?= $ticket['department'] == 'technical' ? 'پشتیبانی فنی' : 'پشتیبانی مالی' ?></span>
                                    <span class="badge badge-<?= $ticket['priority'] ?>"><?= $ticket['priority'] == 'high' ? 'در اولویت' : 'نرمال' ?></span>
                                    <span class="badge badge-<?= $ticket['status'] ?>"><?= $ticket['status'] == 'pending' ? 'در انتظار پاسخ' : ($ticket['status'] == 'answered' ? 'پاسخ داده شده' : 'بسته شده') ?></span>
                                </div>
                            </div>
                            <div class="ticket-date">ارسال: <?= date('Y/m/d H:i', strtotime($ticket['created_at'])) ?></div>
                        </div>
                        
                        <div class="ticket-message"><?= nl2br(htmlspecialchars(mb_substr($ticket['message'], 0, 150))) ?><?= mb_strlen($ticket['message']) > 150 ? '...' : '' ?></div>
                        
                        <?php if ($ticket['admin_reply']): ?>
                            <div class="ticket-reply">
                                <strong>پاسخ پشتیبانی:</strong><br>
                                <?= nl2br(htmlspecialchars(mb_substr($ticket['admin_reply'], 0, 100))) ?>
                                <?= mb_strlen($ticket['admin_reply']) > 100 ? '...' : '' ?>
                                <div style="font-size: 11px; margin-top: 5px;"><?= date('Y/m/d H:i', strtotime($ticket['admin_reply_at'])) ?></div>
                            </div>
                        <?php endif; ?>
                        
                        <div class="ticket-actions">
                            <button class="btn-view" onclick='viewTicket(<?= json_encode($ticket) ?>)'>مشاهده جزئیات</button>
                            <?php if ($ticket['status'] != 'closed'): ?>
                                <button class="btn-close" onclick="closeTicket(<?= $ticket['id'] ?>)">بستن تیکت</button>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty-state">هیچ تیکتی در این بخش وجود ندارد</div>
            <?php endif; ?>
        </div>
    </div>
    
    <div id="newTicketModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>تیکت جدید</h3>
                <span class="close-modal" onclick="closeNewTicketModal()">&times;</span>
            </div>
            <form method="POST">
                <div class="form-group">
                    <label>موضوع</label>
                    <input type="text" name="subject" placeholder="موضوع تیکت را وارد کنید" required>
                </div>
                <div class="form-group">
                    <label>نوع پشتیبانی</label>
                    <select name="department">
                        <option value="technical">پشتیبانی فنی</option>
                        <option value="financial">پشتیبانی مالی</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>اولویت</label>
                    <select name="priority">
                        <option value="normal">نرمال</option>
                        <option value="high">در اولویت (نیاز به پاسخ سریع)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>متن تیکت</label>
                    <textarea name="message" placeholder="توضیحات خود را وارد کنید..." required rows="5"></textarea>
                </div>
                <button type="submit" name="submit_ticket" class="submit-btn">ارسال تیکت</button>
            </form>
        </div>
    </div>
    
    <div id="viewModal" class="modal">
        <div class="modal-content" style="max-width: 650px;">
            <div class="modal-header">
                <h3>جزئیات تیکت <span id="viewTicketNumber"></span></h3>
                <span class="close-modal" onclick="closeViewModal()">&times;</span>
            </div>
            <div id="viewContent"></div>
        </div>
    </div>
    
    <div id="closeModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>بستن تیکت</h3>
                <span class="close-modal" onclick="closeCloseModal()">&times;</span>
            </div>
            <p style="margin-bottom: 20px;">آیا از بستن این تیکت اطمینان دارید؟ پس از بسته شدن، نمی‌توانید پاسخ جدیدی ارسال کنید.</p>
            <a href="#" id="closeLink" class="submit-btn" style="text-align: center; text-decoration: none;">بله، تیکت را ببند</a>
        </div>
    </div>
    
    <script>
        function openNewTicketModal() {
            document.getElementById('newTicketModal').classList.add('active');
        }
        function closeNewTicketModal() {
            document.getElementById('newTicketModal').classList.remove('active');
        }
        function closeTicket(ticketId) {
            document.getElementById('closeLink').href = '?close=' + ticketId;
            document.getElementById('closeModal').classList.add('active');
        }
        function closeCloseModal() {
            document.getElementById('closeModal').classList.remove('active');
        }
        function closeViewModal() {
            document.getElementById('viewModal').classList.remove('active');
        }
        
        function viewTicket(ticket) {
            let statusText = ticket.status === 'pending' ? 'در انتظار پاسخ' : (ticket.status === 'answered' ? 'پاسخ داده شده' : 'بسته شده');
            let deptText = ticket.department === 'technical' ? 'پشتیبانی فنی' : 'پشتیبانی مالی';
            let priorityText = ticket.priority === 'high' ? 'در اولویت' : 'نرمال';
            
            let html = `
                <div style="margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #e2e8f0;">
                    <div class="detail-row"><div class="detail-label">شماره تیکت:</div><div class="detail-value">${escapeHtml(ticket.ticket_number)}</div></div>
                    <div class="detail-row"><div class="detail-label">موضوع:</div><div class="detail-value">${escapeHtml(ticket.subject)}</div></div>
                    <div class="detail-row"><div class="detail-label">نوع پشتیبانی:</div><div class="detail-value">${deptText}</div></div>
                    <div class="detail-row"><div class="detail-label">اولویت:</div><div class="detail-value">${priorityText}</div></div>
                    <div class="detail-row"><div class="detail-label">وضعیت:</div><div class="detail-value">${statusText}</div></div>
                    <div class="detail-row"><div class="detail-label">زمان ارسال:</div><div class="detail-value">${escapeHtml(ticket.created_at)}</div></div>
                </div>
                <div style="margin-bottom: 20px;">
                    <div style="font-weight: bold; margin-bottom: 8px;">متن تیکت:</div>
                    <div style="background: #f8fafc; padding: 15px; border-radius: 12px;">${nl2br(escapeHtml(ticket.message))}</div>
                </div>
            `;
            
            if (ticket.admin_reply) {
                html += `<div><div style="font-weight: bold; margin-bottom: 8px; color: #059669;">پاسخ پشتیبانی:</div><div style="background: #f0fdf4; padding: 15px; border-radius: 12px;">${nl2br(escapeHtml(ticket.admin_reply))}<div style="font-size: 11px; margin-top: 8px;">${escapeHtml(ticket.admin_reply_at)}</div></div></div>`;
            }
            
            if (ticket.closed_by && ticket.status == 'closed') {
                let closedByText = ticket.closed_by === 'agent' ? 'توسط شما' : 'توسط پشتیبانی';
                html += `<div style="margin-top: 15px; padding: 10px; background: #f1f5f9; border-radius: 10px; font-size: 12px;">این تیکت ${closedByText} در تاریخ ${escapeHtml(ticket.closed_at)} بسته شده است.</div>`;
            }
            
            document.getElementById('viewTicketNumber').innerHTML = ticket.ticket_number;
            document.getElementById('viewContent').innerHTML = html;
            document.getElementById('viewModal').classList.add('active');
        }
        
        function escapeHtml(str) { if (!str) return ''; return str.replace(/[&<>]/g, function(m) { if (m === '&') return '&amp;'; if (m === '<') return '&lt;'; if (m === '>') return '&gt;'; return m; }); }
        function nl2br(str) { if (!str) return ''; return str.replace(/\n/g, '<br>'); }
        window.onclick = function(event) { if (event.target.classList.contains('modal')) event.target.classList.remove('active'); }
    </script>
</body>
</html>