<?php
$pageTitle = 'تیکت پشتیبانی';

if (!$adminAuth->isOwner() && !$adminAuth->hasPermission('support')) {
    http_response_code(403);
    echo 'Access Denied';
    exit;
}

global $config;

$ticketId = (int)($_GET['id'] ?? 0);
$ticket = Database::getTicket($ticketId);

if (!$ticket) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'تیکت یافت نشد.'];
    header('Location: ?page=support&tab=tickets');
    exit;
}

// ── AJAX endpoint for real-time polling ───────────────────────────
if (isset($_GET['ajax']) && $_GET['ajax'] === 'messages') {
    header('Content-Type: application/json; charset=utf-8');
    $ticket = Database::getTicket($ticketId);
    $messages = Database::getSupportMessages($ticketId);
    $out = [];
    foreach ($messages as $msg) {
        $ct = $msg['content_type'] ?? 'text';
        $fid = $msg['file_id'] ?? '';
        $fpath = $msg['file_path'] ?? null;
        // Prefer the host file_path (permanent, doesn't expire). Fall back to
        // null — the JS will show a "file unavailable" note. We do NOT call
        // Telegram's getFile here (it's slow + expires after ~1h).
        $fileUrl = null;
        if (in_array($ct, ['photo', 'video', 'audio', 'document'], true)) {
            if ($fpath !== null && $fpath !== '') {
                $fileUrl = MediaStorage::toUrlPath($fpath);
            }
        }
        $out[] = [
            'id'          => (int)$msg['id'],
            'sender_type' => $msg['sender_type'],
            'sender_name' => $msg['sender_name'] ?? '',
            'text'        => $msg['text'] ?? '',
            'content_type' => $ct,
            'file_id'     => $fid,
            'file_url'    => $fileUrl,
            'created_at'  => $msg['created_at'] ?? '',
        ];
    }
    echo json_encode([
        'status'   => $ticket['status'],
        'admin_name' => $ticket['admin_name'] ?? '',
        'open_time'  => $ticket['question_time'] ?? '',
        'user_id'    => (int)$ticket['user_id'],
        'messages' => $out,
        'count' => count($out),
    ]);
    exit;
}

// ── POST: close ticket (admin) ────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'close_ticket') {
    $confirm = trim($_POST['confirm'] ?? '');
    if ($confirm === 'yes') {
        $ticket = Database::getTicket($ticketId);
        $userId = $ticket ? (int)$ticket['user_id'] : 0;
        $openTime = $ticket ? ($ticket['question_time'] ?? '') : '';

        // Count messages before closing
        $messages = $ticket ? Database::getSupportMessages($ticketId) : [];
        $userMsgCount = 0;
        $adminMsgCount = 0;
        foreach ($messages as $m) {
            if ($m['sender_type'] === 'user') $userMsgCount++;
            else $adminMsgCount++;
        }

        // Get all messages with tg_message_id BEFORE closing (so we can edit their buttons)
        $messagesToEdit = [];
        if ($userId > 0) {
            $messagesToEdit = Database::getSupportMessagesWithTgId($ticketId, $userId);
        }

        Database::closeTicket($ticketId);
        AdminDB::logAction($currentUser['user_id'], 'close_ticket', 'ticket', (string)$ticketId);
        $closeTime = date('Y-m-d H:i:s');

        // Edit the buttons on ALL previous messages sent to the user:
        // replace reply/close/back buttons with just "back to main menu".
        // TEXT stays unchanged — only the keyboard is replaced.
        if ($userId > 0 && !empty($messagesToEdit)) {
            $bot = new TelegramBot($config['telegram_bot_token']);
            $newKeyboard = backToMainMenuKeyboard();
            foreach ($messagesToEdit as $msg) {
                try {
                    $bot->editMessageReplyMarkup((int)$msg['tg_chat_id'], (int)$msg['tg_message_id'], $newKeyboard);
                } catch (\Throwable $e) {
                    error_log("Failed to edit message buttons on close: " . $e->getMessage());
                }
                usleep(35000);
            }

            // Also send a NEW message to the user with ticket closure details
            $template = Settings::getMessage('support_closed_details', $config);
            $adminDisplayName = $currentUser['display_name'] ?? 'ادمین';
            $closeText = emoji(32) . ' ' . str_replace(
                ['%1$s', '%2$s', '%3$s', '%4$s', '%5$s'],
                [(string)$ticketId, $openTime, $closeTime, (string)$userMsgCount, (string)$adminMsgCount],
                $template
            );
            $closeText .= "\n\n بسته شده توسط: " . $adminDisplayName;
            $bot->sendMessage($userId, $closeText, backToMainMenuKeyboard());
        }

        $_SESSION['flash'] = ['type' => 'success', 'msg' => "تیکت #{$ticketId} بسته شد و دکمه‌ها به‌روزرسانی شد."];
    } else {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'بستن تیکت لغو شد.'];
    }
    header("Location: ?page=ticket_detail&id=$ticketId");
    exit;
}

// ── POST: delete ticket ───────────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'delete_ticket') {
    $ticket = Database::getTicket($ticketId);
    $userId = $ticket ? (int)$ticket['user_id'] : 0;

    // Get all messages with tg_message_id BEFORE deleting (so we can edit their buttons)
    $messagesToEdit = [];
    if ($userId > 0) {
        $messagesToEdit = Database::getSupportMessagesWithTgId($ticketId, $userId);
    }

    // Delete all admin-uploaded files for this ticket from the HOST filesystem
    // BEFORE deleting the ticket from the DB. This removes the per-ticket folder
    // admin/uploads/tickets/<ticketId>/ and all files inside it.
    MediaStorage::deleteTicketFiles($ticketId);

    Database::deleteTicket($ticketId);
    AdminDB::logAction($currentUser['user_id'], 'delete_ticket', 'ticket', (string)$ticketId);

    // NOTE: no ID renumbering. Older builds renumbered support_tickets to keep
    // ids sequential (remapping support_messages.ticket_id) — that broke
    // bot_settings active_support_ticket_<uid> pointers (a user's close/reply
    // could hit the WRONG ticket) and falsified audit_log target_ids. Sparse
    // ids are safe; AUTO_INCREMENT simply continues past the deleted row.

    // Edit the buttons on all previous messages sent to the user:
    // replace reply/close/back-to-support buttons with just "back to main menu".
    // The TEXT of the messages stays unchanged — only the keyboard is replaced.
    if ($userId > 0 && !empty($messagesToEdit)) {
        $bot = new TelegramBot($config['telegram_bot_token']);
        $newKeyboard = backToMainMenuKeyboard();
        foreach ($messagesToEdit as $msg) {
            try {
                $bot->editMessageReplyMarkup((int)$msg['tg_chat_id'], (int)$msg['tg_message_id'], $newKeyboard);
            } catch (\Throwable $e) {
                error_log("Failed to edit message buttons: " . $e->getMessage());
            }
            usleep(35000);
        }
    }

    $_SESSION['flash'] = ['type' => 'success', 'msg' => 'تیکت حذف شد.'];
    header('Location: ?page=support&tab=tickets');
    exit;
}

// ── POST: answer ticket ───────────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'answer_ticket') {
    $answer = trim($_POST['answer'] ?? '');
    if ($answer !== '') {
        if (in_array($ticket['status'], ['open', 'claimed', 'answered'], true)) {
            if ($ticket['status'] === 'open') {
                Database::claimTicket($ticketId, (int)$currentUser['user_id'], $currentUser['display_name']);
            }

            // The JS already inserts markdown syntax inline (e.g. **text**, > quote).
            // We just send it as-is — no double wrapping.
            // Detect content_type from the markdown for DB storage.
            $contentType = 'text';
            if (str_starts_with($answer, '```')) $contentType = 'code';
            elseif (str_starts_with($answer, '> ')) $contentType = 'quote';

            $msgDbId = Database::addSupportMessage($ticketId, 'admin', (int)$currentUser['user_id'], $currentUser['display_name'], $contentType, $answer, null, null);
            Database::answerTicket($ticketId, $answer);
            AdminDB::logAction($currentUser['user_id'], 'answer_ticket', 'ticket', (string)$ticketId);

            // Send to user — the answer already has markdown, send as-is.
            $bot = new TelegramBot($config['telegram_bot_token']);
            $template = Settings::getMessage('support_answered', $config);
            $userText = emoji(7) . str_replace('%s', $answer, $template);
            // T46-az: loaded custom-emoji pack emojis render as <tg-emoji> tags
            $userText = CustomEmoji::apply($userText);
            $adminName = $currentUser['display_name'] ?? 'پشتیبانی';
            $result = $bot->sendMessage((int)$ticket['user_id'], $userText, supportAnswerKeyboard($adminName, $ticketId));

            // Store the Telegram message_id so we can edit buttons later (when ticket is closed/deleted)
            if ($result && isset($result->ok) && $result->ok && isset($result->result->message_id)) {
                Database::updateSupportMessageTgId($msgDbId, (int)$result->result->message_id, (int)$ticket['user_id']);
            }

            $_SESSION['flash'] = ['type' => 'success', 'msg' => 'پاسخ ارسال شد.'];
        } else {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'این تیکت بسته شده است.'];
        }
    } else {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'پاسخ نمی‌تواند خالی باشد.'];
    }
    // If this is an AJAX request (from sendReply JS), return JSON instead of redirect
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
        header('Content-Type: application/json');
        echo json_encode(['ok' => true, 'flash' => $_SESSION['flash']]);
        exit;
    }
    header("Location: ?page=ticket_detail&id=$ticketId");
    exit;
}

// ── POST: send media (file upload) ────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'send_media') {
    if (in_array($ticket['status'], ['open', 'claimed', 'answered'], true)) {
        if ($ticket['status'] === 'open') {
            Database::claimTicket($ticketId, (int)$currentUser['user_id'], $currentUser['display_name']);
        }

        $caption = trim($_POST['caption'] ?? '');
        $mediaType = $_POST['media_type'] ?? 'document';

        // Check if a file was uploaded
        if (isset($_FILES['media_file']) && $_FILES['media_file']['error'] === UPLOAD_ERR_OK) {
            $tmpName = $_FILES['media_file']['tmp_name'];
            $origName = $_FILES['media_file']['name'];

            // ── Save the file to the HOST filesystem so the admin panel can
            //    display it permanently (Telegram file_ids expire after ~1h).
            //    This does NOT affect what the user sees in Telegram — the file
            //    is still sent to the user via sendMedia() below using the
            //    original tmp file.
            $hostFilePath = MediaStorage::saveUpload($_FILES['media_file'], $ticketId);

            // Create a CURLFile for multipart upload to Telegram
            $curlFile = new CURLFile($tmpName, $_FILES['media_file']['type'], $origName);

            $bot = new TelegramBot($config['telegram_bot_token']);
            $adminName = $currentUser['display_name'] ?? 'پشتیبانی';
            $params = ['chat_id' => (int)$ticket['user_id']];

            // Auto-detect media type if set to auto
            $mimeType = $_FILES['media_file']['type'] ?? '';
            if ($mediaType === 'auto') {
                if (str_starts_with($mimeType, 'image/')) $mediaType = 'photo';
                elseif (str_starts_with($mimeType, 'video/')) $mediaType = 'video';
                elseif (str_starts_with($mimeType, 'audio/')) $mediaType = 'audio';
                else $mediaType = 'document';
            }

            // Build the caption using the SAME template as a text reply
            // (support_answered: " پاسخ پشتیبانی:\n\n%s") so media replies keep
            // the same look as text replies. The admin's typed caption fills %s.
            $template = Settings::getMessage('support_answered', $config);
            $captionText = emoji(7) . str_replace('%s', $caption, $template);
            // T46-az: loaded custom-emoji pack emojis render as <tg-emoji> tags
            $captionText = CustomEmoji::apply($captionText);
            $params['caption'] = $captionText;

            $apiMethod = 'sendDocument';
            $fileKey = 'document';
            if ($mediaType === 'photo') {
                $apiMethod = 'sendPhoto';
                $fileKey = 'photo';
            } elseif ($mediaType === 'video') {
                $apiMethod = 'sendVideo';
                $fileKey = 'video';
            } elseif ($mediaType === 'audio') {
                $apiMethod = 'sendAudio';
                $fileKey = 'audio';
            }
            $params[$fileKey] = $curlFile;
            // Attach the reply keyboard to the SAME message (no separate sendMessage)
            $params['reply_markup'] = supportAnswerKeyboard($adminName, $ticketId);

            // Use sendMedia() (not send()) so that parse_mode=Markdown is set,
            // which converts [[emoji_id]] placeholders in emoji(7) to <tg-emoji>
            // tags AND processes any markdown in the caption. Falls back to plain
            // text if Telegram rejects the formatted caption.
            $result = $bot->sendMedia($apiMethod, $params);

            // Store in conversation — keep the original caption (or filename) as
            // the stored text so the admin panel shows something meaningful.
            $fileId = '';
            $storedType = $mediaType; // may be corrected below if fallback to document happened
            if ($result && isset($result->ok) && $result->ok) {
                // Try the original file key first (photo/video/audio/document).
                $fileId = $result->result->{$fileKey}->file_id ?? '';
                // If the original key wasn't present, the sendMedia() fallback
                // may have sent it as a document instead. Detect that by
                // checking if the 'document' key is present AND the original
                // key is absent — if so, use the document file_id and correct
                // the stored content_type so the admin panel renders it as a
                // downloadable document (not as an image/video/audio that
                // can't be displayed).
                if ($fileId === '' && $fileKey !== 'document'
                    && isset($result->result->document->file_id)) {
                    $fileId = $result->result->document->file_id;
                    $storedType = 'document';
                }
                $tgMsgId = (int)($result->result->message_id ?? 0);
                $storeText = $caption !== '' ? $caption : $origName;
                // Pass $hostFilePath (11th arg) so the admin panel can render the
                // file from the host instead of resolving the (expiring) Telegram
                // file_id every time.
                Database::addSupportMessage(
                    $ticketId, 'admin', (int)$currentUser['user_id'], $currentUser['display_name'],
                    $storedType, $storeText, $fileId, null,
                    $tgMsgId > 0 ? $tgMsgId : null, (int)$ticket['user_id'],
                    $hostFilePath
                );
            } else {
                // Telegram send failed — remove the file from the host so we
                // don't accumulate orphaned files. Use deleteFile (not
                // deleteTicketFiles) to only remove THIS file, not other
                // successfully-sent files in the same ticket.
                MediaStorage::deleteFile($hostFilePath);
            }

            $_SESSION['flash'] = ['type' => 'success', 'msg' => 'فایل ارسال شد.'];
        } else {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'فایلی انتخاب نشده یا خطا در آپلود.'];
        }
    } else {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'این تیکت بسته شده است.'];
    }
    // If this is an AJAX request (from sendMedia JS), return JSON instead of redirect
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
        header('Content-Type: application/json');
        echo json_encode(['ok' => true, 'flash' => $_SESSION['flash']]);
        exit;
    }
    header("Location: ?page=ticket_detail&id=$ticketId");
    exit;
}

$ticket = Database::getTicket($ticketId);
$messages = Database::getSupportMessages($ticketId);

require __DIR__ . '/layout_top.php';

?>

<?php
function formatChatMessageText(array $msg): string {
    $rawText = $msg['text'] ?? '';
    $contentType = $msg['content_type'] ?? 'text';
    $mediaTypes = ['photo', 'video', 'audio', 'document'];
    if (in_array($contentType, $mediaTypes, true) && $rawText === '') {
        $labels = ['photo' => '🖼 عکس', 'video' => '🎬 ویدیو', 'audio' => '🎵 صدا', 'document' => '📄 فایل'];
        return '<span style="opacity:0.7;font-size:12px;">' . $labels[$contentType] . '</span>';
    }
    $s = htmlspecialchars($rawText, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $s = preg_replace('/```([\s\S]*?)```/', '<pre style="background:rgba(0,0,0,0.4);padding:6px 8px;border-radius:6px;margin:4px 0;overflow-x:auto;font-family:monospace;font-size:12px;direction:ltr;border:1px solid rgba(34,211,238,0.15);">$1</pre>', $s);
    $s = preg_replace('/`([^`]+)`/', '<code style="background:rgba(0,0,0,0.4);padding:2px 4px;border-radius:3px;font-family:monospace;font-size:12px;direction:ltr;">$1</code>', $s);
    $s = preg_replace('/\*\*(.+?)\*\*/', '<b>$1</b>', $s);
    $s = preg_replace('/__(.+?)__/', '<i>$1</i>', $s);
    $s = preg_replace('/\|\|(.+?)\|\|/', '<span class="tg-spoiler" style="background:#333;color:#333;border-radius:3px;padding:1px 3px;cursor:pointer;">$1</span>', $s);
    $s = preg_replace('/^&gt; (.+)$/m', '<blockquote style="border-right:3px solid #22d3ee;padding-right:8px;margin:4px 0;color:#9fb0c9;">$1</blockquote>', $s);
    return $s;
}

function renderMediaHtml(array $msg): string {
    $ct = $msg['content_type'] ?? 'text';
    $fp = $msg['file_path'] ?? '';
    if (!in_array($ct, ['photo','video','audio','document'], true) || $fp === '') return '';
    $url = MediaStorage::toUrlPath($fp);
    if ($url === null) return '';
    if ($ct === 'photo') return '<img src="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" style="max-width:100%;max-height:240px;border-radius:8px;display:block;margin-bottom:4px;" loading="lazy" alt="عکس">';
    if ($ct === 'video') return '<video controls style="max-width:100%;max-height:240px;border-radius:8px;display:block;margin-bottom:4px;" preload="metadata"><source src="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></video>';
    if ($ct === 'audio') return '<audio controls style="width:100%;max-width:260px;display:block;margin-bottom:4px;" preload="metadata"><source src="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></audio>';
    return '<a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" download style="display:flex;align-items:center;gap:8px;padding:8px 12px;background:rgba(0,0,0,0.08);border-radius:8px;text-decoration:none;color:inherit;margin-bottom:4px;font-size:13px;"><span style="font-size:20px;">📄</span><span>دانلود فایل</span></a>';
}

$STATUS_META = [
    'open'     => ['dot' => '#f87171', 'label' => 'باز', 'color' => '#f87171'],
    'claimed'  => ['dot' => '#fbbf24', 'label' => 'در حال پاسخ', 'color' => '#fbbf24'],
    'answered' => ['dot' => '#2dd4bf', 'label' => 'پاسخ داده شد', 'color' => '#2dd4bf'],
    'closed'   => ['dot' => '#94a3b8', 'label' => 'بسته شده', 'color' => '#94a3b8'],
];
$sm = $STATUS_META[$ticket['status']] ?? $STATUS_META['open'];
$isClosed = $ticket['status'] === 'closed';
?>

<div style="display:flex;flex-direction:column;gap:16px;">

    <!-- Header bar -->
    <div class="glass-card" style="display:flex;flex-wrap:wrap;align-items:center;gap:12px;padding:12px 16px;margin-bottom:0;">
        <a href="?page=support&tab=tickets" class="btn btn-glass" style="display:grid;width:36px;height:36px;place-items:center;border-radius:12px;padding:0;" title="بازگشت">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>
        </a>
        <div style="flex:1;min-width:0;">
            <h1 style="font-size:16px;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#e6f0ff;">
                تیکت <span class="text-iridescent" style="font-weight:800;">#<?= (int)$ticketId ?></span>
            </h1>
            <div style="display:flex;flex-wrap:wrap;gap:12px;font-size:12px;color:#5a6b85;margin-top:2px;">
                <span style="display:inline-flex;align-items:center;gap:4px;"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg> <?= e($ticket['user_id']) ?></span>
                <span style="display:inline-flex;align-items:center;gap:4px;"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> <?= e($ticket['question_time']) ?></span>
            </div>
        </div>
        <span id="statusPill" style="display:inline-flex;align-items:center;gap:8px;padding:6px 14px;border-radius:50px;font-size:12px;font-weight:600;background:<?= $sm['color'] ?>1a;color:<?= $sm['color'] ?>;border:1px solid <?= $sm['color'] ?>40;">
            <span class="animate-pulse-dot" style="width:8px;height:8px;border-radius:50%;background:<?= $sm['dot'] ?>;box-shadow:0 0 6px <?= $sm['dot'] ?>;"></span>
            <?= $sm['label'] ?>
        </span>
        <?php if (!$isClosed): ?>
        <button onclick="document.getElementById('closeModal').style.display='flex'" class="btn btn-glass btn-sm" style="display:inline-flex;align-items:center;gap:6px;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg> بستن</button>
        <?php endif; ?>
        <button onclick="document.getElementById('deleteModal').style.display='flex'" class="btn btn-danger btn-sm" style="display:inline-flex;align-items:center;gap:6px;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg> حذف</button>
    </div>

    <?php if ($flash): ?>
        <div class="alert alert-<?= e($flash['type']) ?>" style="margin-bottom:0;"><?= e($flash['msg']) ?></div>
    <?php endif; ?>

    <!-- Chat area -->
    <div class="glass-card" style="padding:0;overflow:hidden;margin-bottom:0;">
        <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid rgba(34,211,238,0.08);">
            <span style="font-size:14px;font-weight:600;color:#e6f0ff;display:flex;align-items:center;gap:8px;"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg> مکالمه</span>
            <span style="font-size:12px;color:#5a6b85;"><span id="msgCount"><?= count($messages) ?></span> پیام</span>
        </div>
        <div id="chatArea" class="tg-chat">
            <?php if (count($messages) === 0): ?>
                <div style="display:grid;place-items:center;height:100%;color:#5a6b85;font-size:13px;">هنوز پیامی در این تیکت وجود ندارد.</div>
            <?php endif; ?>
            <?php foreach ($messages as $msg):
                $isUser = $msg['sender_type'] === 'user';
                $formattedText = formatChatMessageText($msg);
                $mediaHtml = renderMediaHtml($msg);
            ?>
            <div class="tg-row <?= $isUser ? 'in' : 'out' ?>">
                <div class="tg-bubble">
                    <div class="tg-name"><?= e($msg['sender_name'] ?? ($isUser ? 'کاربر' : 'ادمین')) ?></div>
                    <?php if ($mediaHtml !== ''): ?><div style="margin-bottom:4px;"><?= $mediaHtml ?></div><?php endif; ?>
                    <span class="tg-body"><?= $formattedText ?></span>
                    <span class="tg-meta"><?= e(substr($msg['created_at'] ?? '', 11, 5)) ?></span>
                    <div class="tg-clear"></div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Reply area -->
    <div class="glass-card" style="padding:16px 20px;margin-bottom:0;">
        <div id="replyAreaInner">
        <?php if ($isClosed): ?>
            <div style="display:grid;place-items:center;gap:4px;padding:24px 0;text-align:center;">
                <div style="color:#94a3b8;"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg></div>
                <p style="font-size:13px;color:#5a6b85;">این تیکت بسته شده است.</p>
            </div>
        <?php else: ?>
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;flex-wrap:wrap;gap:8px;">
                <div style="display:flex;flex-wrap:wrap;gap:6px;align-items:center;">
                    <span style="font-size:11px;color:#5a6b85;margin-left:4px;">فرمت:</span>
                    <button type="button" class="btn btn-glass btn-xs" onclick="wrapActive('**','**','متن پررنگ')" title="پررنگ" style="font-weight:bold;display:grid;width:32px;height:32px;place-items:center;padding:0;">B</button>
                    <button type="button" class="btn btn-glass btn-xs" onclick="wrapActive('__','__','متن کج')" title="کج" style="font-style:italic;display:grid;width:32px;height:32px;place-items:center;padding:0;">I</button>
                    <button type="button" class="btn btn-glass btn-xs" onclick="wrapActive('`','`','کد')" title="کد" style="display:grid;width:32px;height:32px;place-items:center;padding:0;font-family:monospace;">&lt;/&gt;</button>
                    <button type="button" class="btn btn-glass btn-xs" onclick="wrapQuoteActive()" title="نقل‌قول" style="display:grid;width:32px;height:32px;place-items:center;padding:0;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.756-2.017-2-2H4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.757-2.017-2-2h-4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/></svg></button>
                    <button type="button" class="btn btn-glass btn-xs" onclick="wrapActive('||','||','اسپویلر')" title="اسپویلر" style="display:grid;width:32px;height:32px;place-items:center;padding:0;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg></button>
                </div>
                <button type="button" class="btn btn-glass btn-xs" onclick="toggleMedia()" id="toggleMediaBtn" style="display:inline-flex;align-items:center;gap:6px;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.57 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg> فایل</button>
            </div>
            <form id="replyForm" onsubmit="return sendReply(event);">
                <input type="hidden" name="action" value="answer_ticket">
                <textarea name="answer" id="answerText" class="form-control" rows="4" placeholder="پاسخ خود را بنویسید... (Ctrl+Enter برای ارسال)" required style="font-family:inherit;line-height:1.6;resize:vertical;width:100%;"></textarea>
                <?= CustomEmoji::webPickerHtml(['answerText']) ?>
                <div style="margin-top:12px;display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;">
                    <span id="sendStatus" style="font-size:11px;color:#5a6b85;">پاسخ با مارک‌داون ارسال می‌شود (B / I / کد / نقل‌قول)</span>
                    <button type="submit" class="btn btn-primary" style="padding:12px 24px;display:inline-flex;align-items:center;gap:8px;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg> ارسال پاسخ</button>
                </div>
            </form>
            <form method="POST" id="mediaForm" enctype="multipart/form-data" onsubmit="return sendMedia(event);" style="display:none;margin-top:12px;border-top:1px solid rgba(34,211,238,0.08);padding-top:12px;">
            <?= csrf_field() ?>
                <input type="hidden" name="action" value="send_media">
                <div style="display:grid;grid-template-columns:1fr;gap:16px;" class="nx-media-grid">
                    <div class="form-group" style="margin-bottom:0;">
                        <label>نوع فایل</label>
                        <select name="media_type" class="form-control">
                            <option value="auto">خودکار</option>
                            <option value="photo">عکس</option>
                            <option value="video">ویدیو</option>
                            <option value="audio">صدا</option>
                            <option value="document">فایل</option>
                        </select>
                    </div>
                    <div class="form-group" style="margin-bottom:0;">
                        <label>فایل</label>
                        <input type="file" name="media_file" id="mediaFileInput" class="form-control" required style="padding:8px;">
                    </div>
                </div>
                <style>@media(min-width:768px){.nx-media-grid{grid-template-columns:1fr 1fr !important;}}</style>
                <div class="form-group" style="margin-top:16px;">
                    <label>کپشن (اختیاری)</label>
                    <textarea name="caption" id="captionText" class="form-control" rows="2" placeholder="توضیحات فایل..." style="font-family:inherit;line-height:1.6;resize:vertical;width:100%;"></textarea>
                    <?= CustomEmoji::webPickerHtml(['captionText']) ?>
                </div>
                <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
                    <button type="submit" class="btn btn-primary btn-sm" style="display:inline-flex;align-items:center;gap:6px;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.57 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg> ارسال فایل</button>
                    <button type="button" class="btn btn-glass btn-sm" onclick="toggleMedia()">لغو</button>
                    <span id="mediaSendStatus" style="font-size:12px;color:#5a6b85;"></span>
                </div>
            </form>
        <?php endif; ?>
        </div>
    </div>
</div>

<!-- Close modal -->
<div id="closeModal" style="display:none;position:fixed;inset:0;z-index:100;align-items:center;justify-content:center;padding:16px;">
    <div onclick="document.getElementById('closeModal').style.display='none'" style="position:absolute;inset:0;background:rgba(0,0,0,0.6);backdrop-filter:blur(4px);"></div>
    <div style="position:relative;width:100%;max-width:420px;background:rgba(10,12,26,0.95);border:1px solid rgba(34,211,238,0.2);backdrop-filter:blur(30px);border-radius:18px;padding:24px;box-shadow:0 20px 60px rgba(0,0,0,0.5);animation:nx-fade-up 0.4s both;">
        <button onclick="document.getElementById('closeModal').style.display='none'" style="position:absolute;left:16px;top:16px;width:32px;height:32px;display:grid;place-items:center;border-radius:8px;background:transparent;border:none;color:#9fb0c9;cursor:pointer;"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></button>
        <h3 style="margin-bottom:12px;color:#e6f0ff;font-size:16px;font-weight:700;display:flex;align-items:center;gap:6px;"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg> بستن تیکت #<?= (int)$ticketId ?></h3>
        <p style="margin-bottom:18px;color:#9fb0c9;line-height:1.7;font-size:13px;">آیا از بستن تیکت مطمئن هستید؟ کاربر دیگر نمی‌تواند پاسخ دهد.</p>
        <form method="POST" style="display:flex;gap:8px;justify-content:flex-end;">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="close_ticket">
            <input type="hidden" name="confirm" value="yes">
            <button type="button" class="btn btn-glass btn-sm" onclick="document.getElementById('closeModal').style.display='none'">لغو</button>
            <button type="submit" class="btn btn-danger btn-sm">بله، ببند</button>
        </form>
    </div>
</div>

<!-- Delete modal -->
<div id="deleteModal" style="display:none;position:fixed;inset:0;z-index:100;align-items:center;justify-content:center;padding:16px;">
    <div onclick="document.getElementById('deleteModal').style.display='none'" style="position:absolute;inset:0;background:rgba(0,0,0,0.6);backdrop-filter:blur(4px);"></div>
    <div style="position:relative;width:100%;max-width:420px;background:rgba(10,12,26,0.95);border:1px solid rgba(34,211,238,0.2);backdrop-filter:blur(30px);border-radius:18px;padding:24px;box-shadow:0 20px 60px rgba(0,0,0,0.5);animation:nx-fade-up 0.4s both;">
        <button onclick="document.getElementById('deleteModal').style.display='none'" style="position:absolute;left:16px;top:16px;width:32px;height:32px;display:grid;place-items:center;border-radius:8px;background:transparent;border:none;color:#9fb0c9;cursor:pointer;"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></button>
        <h3 style="margin-bottom:12px;color:#e6f0ff;font-size:16px;font-weight:700;display:flex;align-items:center;gap:6px;"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg> حذف تیکت #<?= (int)$ticketId ?></h3>
        <p style="margin-bottom:18px;color:#9fb0c9;line-height:1.7;font-size:13px;">این عمل قابل بازگشت نیست و تمام پیام‌ها حذف خواهند شد.</p>
        <form method="POST" style="display:flex;gap:8px;justify-content:flex-end;">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="delete_ticket">
            <button type="button" class="btn btn-glass btn-sm" onclick="document.getElementById('deleteModal').style.display='none'">لغو</button>
            <button type="submit" class="btn btn-danger btn-sm">بله، حذف کن</button>
        </form>
    </div>
</div>

<script>
var chatArea = document.getElementById('chatArea');
var lastMsgId = <?= !empty($messages) ? (int)max(array_column($messages, 'id')) : 0 ?>;
var userAtBottom = true;
var ticketId = <?= (int)$ticketId ?>;

if (chatArea) chatArea.scrollTop = chatArea.scrollHeight;
if (chatArea) {
    chatArea.addEventListener('scroll', function() {
        userAtBottom = (chatArea.scrollHeight - chatArea.scrollTop - chatArea.clientHeight) < 60;
    });
}

function escapeHtml(s) {
    var d = document.createElement('div');
    d.textContent = s == null ? '' : String(s);
    return d.innerHTML;
}

function formatHtml(rawText, contentType) {
    var mediaTypes = ['photo', 'video', 'audio', 'document'];
    if (!rawText && mediaTypes.indexOf(contentType) !== -1) {
        var labels = {photo:'🖼 عکس', video:'🎬 ویدیو', audio:'🎵 صدا', document:'📄 فایل'};
        return '<span style="opacity:0.7;font-size:12px;">' + labels[contentType] + '</span>';
    }
    var s = escapeHtml(rawText);
    s = s.replace(/```([\s\S]*?)```/g, '<pre style="background:rgba(0,0,0,0.4);padding:6px 8px;border-radius:6px;margin:4px 0;overflow-x:auto;font-family:monospace;font-size:12px;direction:ltr;border:1px solid rgba(34,211,238,0.15);">$1</pre>');
    s = s.replace(/`([^`]+)`/g, '<code style="background:rgba(0,0,0,0.4);padding:2px 4px;border-radius:3px;font-family:monospace;font-size:12px;direction:ltr;">$1</code>');
    s = s.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>');
    s = s.replace(/__(.+?)__/g, '<i>$1</i>');
    s = s.replace(/\|\|(.+?)\|\|/g, '<span class="tg-spoiler" style="background:#333;color:#333;border-radius:3px;padding:1px 3px;cursor:pointer;">$1</span>');
    s = s.replace(/^&gt; (.+)$/gm, '<blockquote style="border-right:3px solid #22d3ee;padding-right:8px;margin:4px 0;color:#9fb0c9;">$1</blockquote>');
    return s;
}

function timeStr(iso) {
    if (!iso) return '';
    return new Date(iso.replace(' ', 'T')).toLocaleTimeString('fa-IR', {hour:'2-digit', minute:'2-digit'});
}

function buildMedia(msg) {
    var ct = msg.content_type || 'text';
    var url = msg.file_url;
    var mediaTypes = ['photo','video','audio','document'];
    if (mediaTypes.indexOf(ct) === -1) return '';
    if (!url) return '<div style="margin-bottom:4px;padding:8px 12px;background:rgba(0,0,0,0.3);border-radius:8px;font-size:12px;color:#5a6b85;">⚠️ فایل قابل بارگذاری نیست</div>';
    if (ct === 'photo') return '<img src="' + escapeHtml(url) + '" style="max-width:100%;max-height:240px;border-radius:8px;display:block;margin-bottom:4px;" loading="lazy">';
    if (ct === 'video') return '<video controls style="max-width:100%;max-height:240px;border-radius:8px;display:block;margin-bottom:4px;" preload="metadata"><source src="' + escapeHtml(url) + '"></video>';
    if (ct === 'audio') return '<audio controls style="width:100%;max-width:260px;display:block;margin-bottom:4px;" preload="metadata"><source src="' + escapeHtml(url) + '"></audio>';
    return '<a href="' + escapeHtml(url) + '" download style="display:flex;align-items:center;gap:8px;padding:8px 12px;background:rgba(0,0,0,0.08);border-radius:8px;text-decoration:none;color:inherit;margin-bottom:4px;font-size:13px;"><span style="font-size:20px;">📄</span><span>دانلود فایل</span></a>';
}

function appendMessage(msg) {
    var isUser = msg.sender_type === 'user';
    var row = document.createElement('div');
    row.className = 'tg-row ' + (isUser ? 'in' : 'out');
    var mediaHtml = buildMedia(msg);
    var bodyHtml = formatHtml(msg.text || '', msg.content_type || 'text');
    row.innerHTML =
        '<div class="tg-bubble">' +
            '<div class="tg-name">' + escapeHtml(msg.sender_name || (isUser ? 'کاربر' : 'ادمین')) + '</div>' +
            (mediaHtml ? '<div style="margin-bottom:4px;">' + mediaHtml + '</div>' : '') +
            '<span class="tg-body">' + bodyHtml + '</span>' +
            '<span class="tg-meta">' + escapeHtml(timeStr(msg.created_at)) + '</span>' +
            '<div class="tg-clear"></div>' +
        '</div>';
    chatArea.appendChild(row);
}

function pollMessages() {
    fetch('?page=ticket_detail&id=' + ticketId + '&ajax=messages')
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var newMsgs = [];
            for (var i = 0; i < data.messages.length; i++) {
                if (data.messages[i].id > lastMsgId) newMsgs.push(data.messages[i]);
            }
            if (newMsgs.length > 0) {
                newMsgs.forEach(function(m) {
                    appendMessage(m);
                    if (m.id > lastMsgId) lastMsgId = m.id;
                });
                document.getElementById('msgCount').textContent = data.count;
                if (userAtBottom) chatArea.scrollTop = chatArea.scrollHeight;
            }
            var pill = document.getElementById('statusPill');
            if (pill && data.status) {
                var meta = {open:['#f87171','باز'], claimed:['#fbbf24','در حال پاسخ'], answered:['#2dd4bf','پاسخ داده شد'], closed:['#94a3b8','بسته شده']};
                var m = meta[data.status] || meta.open;
                pill.style.background = m[0] + '1a';
                pill.style.color = m[0];
                pill.style.border = '1px solid ' + m[0] + '40';
                pill.innerHTML = '<span class="animate-pulse-dot" style="width:8px;height:8px;border-radius:50%;background:' + m[0] + ';box-shadow:0 0 6px ' + m[0] + ';"></span> ' + m[1];
            }
            if (data.status === 'closed') {
                var ra = document.getElementById('replyAreaInner');
                if (ra && ra.querySelector('textarea') !== null) {
                    ra.innerHTML = '<div style="display:grid;place-items:center;gap:4px;padding:24px 0;text-align:center;"><div style="color:#94a3b8;"><svg xmlns=\'http://www.w3.org/2000/svg\' width=\'28\' height=\'28\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'currentColor\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\'><rect width=\'18\' height=\'11\' x=\'3\' y=\'11\' rx=\'2\' ry=\'2\'/><path d=\'M7 11V7a5 5 0 0 1 10 0v4\'/></svg></div><p style=\'font-size:13px;color:#5a6b85;\'>این تیکت بسته شده است.</p></div>';
                }
            }
        })
        .catch(function() {});
}
setInterval(pollMessages, 3000);

// Determine which textarea is currently visible (text reply form or media caption)
function getActiveTextareaId() {
    var rf = document.getElementById('replyForm');
    var mf = document.getElementById('mediaForm');
    // If media form is visible, target captionText; otherwise answerText
    if (mf && mf.style.display !== 'none' && mf.offsetParent !== null) return 'captionText';
    return 'answerText';
}
// Single toolbar wrappers — target the active textarea
function wrapActive(open, close, ph) {
    wrapSelT(getActiveTextareaId(), open, close, ph);
}
function wrapQuoteActive() {
    wrapQuoteT(getActiveTextareaId());
}
// Parameterized versions — target any textarea by id
function wrapSelT(targetId, open, close, ph) {
    var ta = document.getElementById(targetId);
    if (!ta) return;
    var s = ta.selectionStart, e = ta.selectionEnd;
    var sel = ta.value.substring(s, e) || ph;
    ta.value = ta.value.substring(0, s) + open + sel + close + ta.value.substring(e);
    ta.focus();
    ta.setSelectionRange(s + open.length, s + open.length + sel.length);
}
function wrapQuoteT(targetId) {
    var ta = document.getElementById(targetId);
    if (!ta) return;
    var s = ta.selectionStart, e = ta.selectionEnd;
    var sel = ta.value.substring(s, e) || 'متن نقل‌قول';
    var quoted = sel.split('\n').map(function(l){return '> '+l;}).join('\n');
    ta.value = ta.value.substring(0, s) + quoted + ta.value.substring(e);
    ta.focus();
    ta.setSelectionRange(s + 2, s + 2 + sel.length);
}

function toggleMedia() {
    var mf = document.getElementById('mediaForm');
    var rf = document.getElementById('replyForm');
    var btn = document.getElementById('toggleMediaBtn');
    if (mf.style.display === 'none') {
        mf.style.display = 'block';
        rf.style.display = 'none';
        btn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-left:4px;"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg> متن';
    } else {
        mf.style.display = 'none';
        rf.style.display = 'block';
        btn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-left:4px;"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.57 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg> فایل';
    }
}

function sendReply(event) {
    event.preventDefault();
    var ta = document.getElementById('answerText');
    var answer = ta.value.trim();
    if (!answer) return false;
    var statusEl = document.getElementById('sendStatus');
    statusEl.textContent = 'در حال ارسال...';
    var fd = new FormData();
    fd.append('action', 'answer_ticket');
    fd.append('answer', answer);
    // SECURITY: include the CSRF token so csrf_guard() accepts this AJAX POST.
    var csrf = document.querySelector('meta[name=csrf-token]');
    if (csrf) fd.append('csrf_token', csrf.content);
    fetch('?page=ticket_detail&id=' + ticketId, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: fd
    }).then(function(r) { return r.json(); }).then(function(data) {
        ta.value = '';
        statusEl.textContent = (data.flash && data.flash.msg) ? data.flash.msg : 'ارسال شد';
        setTimeout(function() { statusEl.textContent = 'پاسخ با مارک‌داون ارسال می‌شود (B / I / کد / نقل‌قول)'; }, 3000);
        userAtBottom = true;
        pollMessages();
    }).catch(function() { statusEl.textContent = 'خطا در ارسال'; });
    return false;
}

function sendMedia(event) {
    event.preventDefault();
    var form = document.getElementById('mediaForm');
    var fileInput = document.getElementById('mediaFileInput');
    if (!fileInput.files.length) return false;
    var statusEl = document.getElementById('mediaSendStatus');
    statusEl.textContent = 'در حال آپلود...';
    var fd = new FormData(form);
    // SECURITY: include the CSRF token so csrf_guard() accepts this AJAX POST.
    var csrf = document.querySelector('meta[name=csrf-token]');
    if (csrf) fd.append('csrf_token', csrf.content);
    fetch('?page=ticket_detail&id=' + ticketId, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: fd
    }).then(function(r) { return r.json(); }).then(function(data) {
        form.reset();
        statusEl.textContent = (data.flash && data.flash.msg) ? data.flash.msg : 'ارسال شد';
        setTimeout(function() { statusEl.textContent = ''; }, 3000);
        toggleMedia();
        userAtBottom = true;
        pollMessages();
    }).catch(function() { statusEl.textContent = 'خطا در ارسال'; });
    return false;
}

var at = document.getElementById('answerText');
if (at) at.addEventListener('keydown', function(e) {
    if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault();
        document.getElementById('replyForm').dispatchEvent(new Event('submit'));
    }
});
var ct = document.getElementById('captionText');
if (ct) ct.addEventListener('keydown', function(e) {
    if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault();
        document.getElementById('mediaForm').dispatchEvent(new Event('submit'));
    }
});
</script>

<?php require __DIR__ . '/layout_bottom.php'; ?>
