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

date_default_timezone_set('Asia/Tehran');

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

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

$success = $error = '';

// ایجاد جدول اگر وجود نداشته باشد
$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_setting = $settings_row['ticket_limit'];
    $system_active_setting = $settings_row['system_active'];
} else {
    $ticket_limit_setting = 10;
    $system_active_setting = 1;
}

// پردازش پاسخ ادمین
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_ticket'])) {
    $ticket_id = intval($_POST['ticket_id']);
    $admin_reply = trim($_POST['admin_reply']);
    
    if (empty($admin_reply)) {
        $error = "لطفاً متن پاسخ را وارد کنید.";
    } else {
        $stmt = $pdo->prepare("
            UPDATE tickets 
            SET admin_reply = ?, admin_reply_at = NOW(), status = 'answered', updated_at = NOW() 
            WHERE id = ? AND status != 'closed'
        ");
        
        if ($stmt->execute([$admin_reply, $ticket_id])) {
            $success = "پاسخ با موفقیت ثبت شد.";
        } else {
            $error = "خطا در ثبت پاسخ.";
        }
    }
}

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

// فعال/غیرفعال کردن سیستم تیکت برای همه
if (isset($_GET['toggle_system'])) {
    $new_status = $_GET['toggle_system'] == '1' ? 1 : 0;
    $pdo->prepare("UPDATE tickets SET system_active = ?")->execute([$new_status]);
    $system_active_setting = $new_status;
    $success = $new_status ? "سیستم تیکت فعال شد." : "سیستم تیکت غیرفعال شد.";
}

// تنظیم لیمیت تیکت برای همه
if (isset($_POST['update_limit'])) {
    $new_limit = intval($_POST['ticket_limit']);
    if ($new_limit > 0 && $new_limit <= 50) {
        $pdo->prepare("UPDATE tickets SET ticket_limit = ?")->execute([$new_limit]);
        $ticket_limit_setting = $new_limit;
        $success = "لیمیت تیکت با موفقیت به {$new_limit} تغییر یافت.";
    } else {
        $error = "لیمیت باید بین 1 تا 50 باشد.";
    }
}

// دریافت فیلترها
$status_filter = $_GET['status'] ?? 'all';
$department_filter = $_GET['department'] ?? 'all';
$priority_filter = $_GET['priority'] ?? 'all';
$search_filter = trim($_GET['search'] ?? '');

// ساخت کوئری با فیلترها
$query = "SELECT * FROM tickets WHERE 1=1";
$params = [];

if ($status_filter != 'all') {
    $query .= " AND status = ?";
    $params[] = $status_filter;
}

if ($department_filter != 'all') {
    $query .= " AND department = ?";
    $params[] = $department_filter;
}

if ($priority_filter != 'all') {
    $query .= " AND priority = ?";
    $params[] = $priority_filter;
}

if (!empty($search_filter)) {
    $query .= " AND (ticket_number LIKE ? OR agent_name LIKE ? OR agent_token LIKE ? OR subject LIKE ? OR message LIKE ?)";
    $search_param = "%{$search_filter}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

$query .= " ORDER BY 
    CASE 
        WHEN priority = 'high' AND status = 'pending' THEN 1
        WHEN status = 'pending' THEN 2
        WHEN status = 'answered' THEN 3
        ELSE 4
    END, 
    created_at ASC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);

// آمار
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM tickets")->fetchColumn(),
    'pending' => $pdo->query("SELECT COUNT(*) FROM tickets WHERE status = 'pending'")->fetchColumn(),
    'answered' => $pdo->query("SELECT COUNT(*) FROM tickets WHERE status = 'answered'")->fetchColumn(),
    'closed' => $pdo->query("SELECT COUNT(*) FROM tickets WHERE status = 'closed'")->fetchColumn(),
    'technical' => $pdo->query("SELECT COUNT(*) FROM tickets WHERE department = 'technical'")->fetchColumn(),
    'financial' => $pdo->query("SELECT COUNT(*) FROM tickets WHERE department = 'financial'")->fetchColumn(),
    'high_priority' => $pdo->query("SELECT COUNT(*) FROM tickets WHERE priority = 'high' AND status = 'pending'")->fetchColumn(),
];
?>
<!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;
        }
        
        .admin-tickets-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .admin-header-custom {
            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-actions {
            display: flex;
            gap: 12px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .system-toggle {
            display: flex;
            align-items: center;
            gap: 10px;
            background: #f1f5f9;
            padding: 8px 16px;
            border-radius: 30px;
        }
        
        .system-toggle span {
            font-size: 13px;
            color: #1e293b;
        }
        
        .toggle-btn {
            width: 50px;
            height: 26px;
            background: #cbd5e1;
            border-radius: 30px;
            display: inline-block;
            position: relative;
            cursor: pointer;
            transition: 0.3s;
        }
        
        .toggle-btn.active {
            background: #3b82f6;
        }
        
        .toggle-btn:after {
            content: '';
            width: 22px;
            height: 22px;
            background: white;
            border-radius: 50%;
            position: absolute;
            top: 2px;
            left: 4px;
            transition: 0.3s;
        }
        
        .toggle-btn.active:after {
            left: 24px;
        }
        
        .back-btn {
            background: #64748b;
            color: white;
            padding: 8px 16px;
            border-radius: 10px;
            text-decoration: none;
            font-size: 13px;
        }
        
        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 25px;
        }
        
        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 18px;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            border-top: 3px solid;
        }
        
        .stat-card.total { border-top-color: #3b82f6; }
        .stat-card.pending { border-top-color: #f59e0b; }
        .stat-card.answered { border-top-color: #10b981; }
        .stat-card.closed { border-top-color: #94a3b8; }
        .stat-card.technical { border-top-color: #8b5cf6; }
        .stat-card.financial { border-top-color: #ec489a; }
        .stat-card.high { border-top-color: #ef4444; }
        
        .stat-number {
            font-size: 28px;
            font-weight: bold;
            color: #1e293b;
        }
        
        .stat-label {
            font-size: 11px;
            color: #64748b;
            margin-top: 5px;
        }
        
        .filters-section {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 25px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        
        .filters-row {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: flex-end;
        }
        
        .filter-group {
            flex: 1;
            min-width: 140px;
        }
        
        .filter-group label {
            display: block;
            font-size: 12px;
            color: #64748b;
            margin-bottom: 5px;
        }
        
        .filter-group select,
        .filter-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            font-size: 13px;
            background: white;
        }
        
        .reset-btn {
            background: #f1f5f9;
            color: #64748b;
            border: none;
            padding: 10px 20px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 13px;
        }
        
        .tickets-table-wrapper {
            background: white;
            border-radius: 20px;
            overflow-x: auto;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        
        .tickets-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 800px;
        }
        
        .tickets-table th,
        .tickets-table td {
            padding: 15px 12px;
            text-align: center;
            border-bottom: 1px solid #e2e8f0;
            font-size: 13px;
        }
        
        .tickets-table th {
            background: #f8fafc;
            color: #1e293b;
            font-weight: 600;
        }
        
        .tickets-table tr:hover {
            background: #f8fafc;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 500;
        }
        
        .badge-technical { background: #dbeafe; color: #2563eb; }
        .badge-financial { background: #fce7f3; color: #db2777; }
        .badge-high { background: #fee2e2; color: #dc2626; }
        .badge-normal { background: #e2e8f0; color: #475569; }
        .badge-pending { background: #fef3c7; color: #d97706; }
        .badge-answered { background: #d1fae5; color: #059669; }
        .badge-closed { background: #f1f5f9; color: #64748b; }
        
        .action-buttons {
            display: flex;
            gap: 8px;
            justify-content: center;
            flex-wrap: wrap;
        }
        
        .btn-reply {
            background: #3b82f6;
            color: white;
            border: none;
            padding: 5px 12px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 11px;
        }
        
        .btn-view {
            background: #64748b;
            color: white;
            border: none;
            padding: 5px 12px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 11px;
        }
        
        .btn-close {
            background: #ef4444;
            color: white;
            border: none;
            padding: 5px 12px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 11px;
        }
        
        .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 textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            font-size: 14px;
            font-family: inherit;
            resize: vertical;
            min-height: 150px;
        }
        
        .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%;
        }
        
        .detail-row {
            display: flex;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .detail-label {
            width: 130px;
            font-weight: 600;
            color: #64748b;
        }
        
        .detail-value {
            flex: 1;
            color: #1e293b;
        }
        
        .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;
        }
        
        .limit-settings {
            background: #f8fafc;
            padding: 15px;
            border-radius: 12px;
            margin-top: 15px;
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .limit-settings input {
            width: 80px;
            padding: 8px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            text-align: center;
        }
        
        .empty-state {
            text-align: center;
            padding: 50px;
            color: #94a3b8;
        }
        
        @media (max-width: 768px) {
            .admin-tickets-container {
                padding: 12px;
            }
            .stats-cards {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>
<body>
    <div class="admin-tickets-container">
        <div class="admin-header-custom">
            <div class="header-title">
                <h1>مدیریت تیکت‌های پشتیبانی</h1>
                <p>مدیریت و پاسخگویی به تیکت‌های نمایندگان</p>
            </div>
            <div class="header-actions">
                <div class="system-toggle">
                    <span>وضعیت سیستم تیکت:</span>
                    <div class="toggle-btn <?= $system_active_setting ? 'active' : '' ?>" onclick="toggleSystem(<?= $system_active_setting ? 0 : 1 ?>)"></div>
                    <span style="font-size: 12px;"><?= $system_active_setting ? 'فعال' : 'غیرفعال' ?></span>
                </div>
                <a href="../admin_panel.php" class="back-btn">بازگشت به پنل</a>
            </div>
        </div>
        
        <?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="stats-cards">
            <div class="stat-card total"><div class="stat-number"><?= $stats['total'] ?></div><div class="stat-label">کل تیکت‌ها</div></div>
            <div class="stat-card pending"><div class="stat-number"><?= $stats['pending'] ?></div><div class="stat-label">در انتظار پاسخ</div></div>
            <div class="stat-card answered"><div class="stat-number"><?= $stats['answered'] ?></div><div class="stat-label">پاسخ داده شده</div></div>
            <div class="stat-card closed"><div class="stat-number"><?= $stats['closed'] ?></div><div class="stat-label">بسته شده</div></div>
            <div class="stat-card technical"><div class="stat-number"><?= $stats['technical'] ?></div><div class="stat-label">پشتیبانی فنی</div></div>
            <div class="stat-card financial"><div class="stat-number"><?= $stats['financial'] ?></div><div class="stat-label">پشتیبانی مالی</div></div>
            <div class="stat-card high"><div class="stat-number"><?= $stats['high_priority'] ?></div><div class="stat-label">در اولویت پاسخ</div></div>
        </div>
        
        <div class="filters-section">
            <form method="GET" id="filterForm">
                <div class="filters-row">
                    <div class="filter-group">
                        <label>وضعیت</label>
                        <select name="status" onchange="this.form.submit()">
                            <option value="all" <?= $status_filter == 'all' ? 'selected' : '' ?>>همه</option>
                            <option value="pending" <?= $status_filter == 'pending' ? 'selected' : '' ?>>در انتظار پاسخ</option>
                            <option value="answered" <?= $status_filter == 'answered' ? 'selected' : '' ?>>پاسخ داده شده</option>
                            <option value="closed" <?= $status_filter == 'closed' ? 'selected' : '' ?>>بسته شده</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label>نوع پشتیبانی</label>
                        <select name="department" onchange="this.form.submit()">
                            <option value="all" <?= $department_filter == 'all' ? 'selected' : '' ?>>همه</option>
                            <option value="technical" <?= $department_filter == 'technical' ? 'selected' : '' ?>>پشتیبانی فنی</option>
                            <option value="financial" <?= $department_filter == 'financial' ? 'selected' : '' ?>>پشتیبانی مالی</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label>اولویت</label>
                        <select name="priority" onchange="this.form.submit()">
                            <option value="all" <?= $priority_filter == 'all' ? 'selected' : '' ?>>همه</option>
                            <option value="normal" <?= $priority_filter == 'normal' ? 'selected' : '' ?>>نرمال</option>
                            <option value="high" <?= $priority_filter == 'high' ? 'selected' : '' ?>>در اولویت</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label>جستجو</label>
                        <input type="text" name="search" placeholder="شماره/نام/توکن/موضوع..." value="<?= htmlspecialchars($search_filter) ?>">
                    </div>
                    <div class="filter-group">
                        <label>&nbsp;</label>
                        <button type="submit" class="reset-btn" style="background: #3b82f6; color: white;">جستجو</button>
                        <a href="?status=all&department=all&priority=all" class="reset-btn" style="text-decoration: none; display: inline-block;">حذف فیلترها</a>
                    </div>
                </div>
            </form>
            
            <div class="limit-settings">
                <span style="font-size: 13px; color: #1e293b;">حداکثر تیکت همزمان برای هر نماینده:</span>
                <form method="POST" style="display: flex; gap: 10px; align-items: center;">
                    <input type="number" name="ticket_limit" value="<?= $ticket_limit_setting ?>" min="1" max="50">
                    <button type="submit" name="update_limit" class="reset-btn" style="background: #3b82f6; color: white;">اعمال</button>
                </form>
            </div>
        </div>
        
        <div class="tickets-table-wrapper">
            <table class="tickets-table">
                <thead>
                    <tr>
                        <th>شماره</th>
                        <th>نماینده</th>
                        <th>موضوع</th>
                        <th>نوع</th>
                        <th>اولویت</th>
                        <th>وضعیت</th>
                        <th>زمان ارسال</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($tickets) > 0): ?>
                        <?php foreach ($tickets as $ticket): ?>
                            <tr>
                                <td><code><?= htmlspecialchars($ticket['ticket_number']) ?></code></td>
                                <td>
                                    <?= htmlspecialchars($ticket['agent_name']) ?><br>
                                    <small style="color: #94a3b8; font-size: 10px;"><?= htmlspecialchars(substr($ticket['agent_token'], 0, 10)) ?>...</small>
                                </td>
                                <td style="text-align: right;"><?= htmlspecialchars(mb_substr($ticket['subject'], 0, 30)) ?></td>
                                <td><span class="badge badge-<?= $ticket['department'] ?>"><?= $ticket['department'] == 'technical' ? 'فنی' : 'مالی' ?></span></td>
                                <td><span class="badge <?= $ticket['priority'] == 'high' ? 'badge-high' : 'badge-normal' ?>"><?= $ticket['priority'] == 'high' ? 'در اولویت' : 'نرمال' ?></span></td>
                                <td><span class="badge badge-<?= $ticket['status'] ?>"><?= $ticket['status'] == 'pending' ? 'در انتظار' : ($ticket['status'] == 'answered' ? 'پاسخ داده شده' : 'بسته شده') ?></span></td>
                                <td style="font-size: 11px;"><?= date('Y/m/d H:i', strtotime($ticket['created_at'])) ?></td>
                                <td>
                                    <div class="action-buttons">
                                        <button class="btn-view" onclick='viewTicket(<?= json_encode($ticket) ?>)'>مشاهده</button>
                                        <?php if ($ticket['status'] != 'closed'): ?>
                                            <button class="btn-reply" onclick="openReplyModal(<?= $ticket['id'] ?>, '<?= htmlspecialchars($ticket['ticket_number']) ?>')">پاسخ</button>
                                            <button class="btn-close" onclick="closeTicket(<?= $ticket['id'] ?>)">بستن</button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="8" class="empty-state">هیچ تیکتی با این فیلترها یافت نشد.<?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <div id="replyModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>پاسخ به تیکت <span id="replyTicketNumber"></span></h3>
                <span class="close-modal" onclick="closeReplyModal()">&times;</span>
            </div>
            <form method="POST">
                <input type="hidden" name="ticket_id" id="replyTicketId">
                <div class="form-group">
                    <label>متن پاسخ</label>
                    <textarea name="admin_reply" placeholder="پاسخ خود را وارد کنید..." required rows="6"></textarea>
                </div>
                <button type="submit" name="reply_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 toggleSystem(status) {
            window.location.href = '?toggle_system=' + status;
        }
        
        function openReplyModal(ticketId, ticketNumber) {
            document.getElementById('replyTicketId').value = ticketId;
            document.getElementById('replyTicketNumber').innerHTML = ticketNumber;
            document.getElementById('replyModal').classList.add('active');
        }
        
        function closeReplyModal() {
            document.getElementById('replyModal').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.agent_name)} (${escapeHtml(ticket.agent_token)})</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>