<?php
$pageTitle = 'برداشت';

// Permission: owner OR 'support' OR 'withdrawals'.
if (!$adminAuth->isOwner()
    && !$adminAuth->hasPermission('support')
    && !$adminAuth->hasPermission('withdrawals')) {
    http_response_code(403);
    echo 'Access Denied';
    exit;
}

global $config;

$withdrawalId = (int)($_GET['id'] ?? 0);
$withdrawal   = Database::getWithdrawal($withdrawalId);

if (!$withdrawal) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'درخواست برداشت یافت نشد.'];
    header('Location: ?page=support&tab=withdrawals');
    exit;
}

// ── AJAX endpoint for real-time polling ───────────────────────────
if (isset($_GET['ajax']) && $_GET['ajax'] === 'messages') {
    header('Content-Type: application/json; charset=utf-8');
    $withdrawal = Database::getWithdrawal($withdrawalId);
    $messages   = Database::getWithdrawalMessages($withdrawalId);
    $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'      => $withdrawal['status'] ?? 'open',
        'type'        => $withdrawal['type'] ?? '',
        'amount'      => (int)($withdrawal['amount'] ?? 0),
        'operator'    => $withdrawal['operator'] ?? '',
        'admin_name'  => $withdrawal['admin_name'] ?? '',
        'open_time'   => $withdrawal['question_time'] ?? '',
        'user_id'     => (int)$withdrawal['user_id'],
        'messages'    => $out,
        'count'       => count($out),
    ]);
    exit;
}

// ── Helper: edit prior Telegram keyboards to "back to main menu" ──
// Used by close / delete / approve / reject flows — strips the inline
// reply/close buttons from messages already in the user's chat so the
// user can no longer tap them.
$editPriorKeyboardsToBack = function(int $userId, int $wId) use ($config): void {
    if ($userId <= 0 || $wId <= 0) return;
    $prior = Database::getWithdrawalMessagesWithTgId($wId, $userId);
    if (empty($prior)) return;
    $bot = new TelegramBot($config['telegram_bot_token']);
    $newKeyboard = backToMainMenuKeyboard();
    foreach ($prior as $msg) {
        try {
            $bot->editMessageReplyMarkup((int)$msg['tg_chat_id'], (int)$msg['tg_message_id'], $newKeyboard);
        } catch (\Throwable $e) {
            error_log("Failed to edit withdrawal message buttons: " . $e->getMessage());
        }
        usleep(35000);
    }
};

// ── POST: close withdrawal ─────────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'close_withdrawal') {
    $confirm = trim($_POST['confirm'] ?? '');
    if ($confirm === 'yes') {
        $withdrawal = Database::getWithdrawal($withdrawalId);
        $userId     = $withdrawal ? (int)$withdrawal['user_id'] : 0;
        $openTime   = $withdrawal ? ($withdrawal['question_time'] ?? '') : '';

        // Guarded close FIRST: only open/claimed/answered rows can be closed.
        // If another actor already approved/rejected/closed the row, abort
        // with NO refund and NO notifications (rowCount !== 1).
        if (Database::transitionWithdrawalStatus($withdrawalId, ['open', 'claimed', 'answered'], 'closed') !== 1) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => "برداشت #{$withdrawalId} قابل بستن نیست (وضعیت آن قبلاً تغییر کرده است)."];
            if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
                header('Content-Type: application/json');
                echo json_encode(['ok' => false, 'flash' => $_SESSION['flash']]);
                exit;
            }
            header("Location: ?page=withdrawal_detail&id=$withdrawalId");
            exit;
        }

        // Refund the held toman for card/stars withdrawals — it was debited
        // up-front when the request was created (same as the bot-side user
        // close and the admin reject flow).
        $refunded = 0;
        $wType    = (string)($withdrawal['type'] ?? '');
        $wAmount  = (int)($withdrawal['amount'] ?? 0);
        // v2.9.45 (R6-58/M1): charge rows hold toman up-front (F-A3) — refund
        // when no code was delivered yet.
        $chargeRefundable = ($wType === 'charge' && trim((string)($withdrawal['assigned_code'] ?? '')) === '');
        if (($wType === 'card' || $wType === 'stars' || $chargeRefundable) && $wAmount > 0 && $userId > 0) {
            try {
                Wallet::credit($userId, 'toman', $wAmount, 'withdrawal_refund_admin_close', 'withdrawal', $withdrawalId);
                $refunded = $wAmount;
            } catch (\Throwable $e) {
                error_log("Failed to refund held toman on admin close of withdrawal #{$withdrawalId}: " . $e->getMessage());
            }
        }

        $messages = $withdrawal ? Database::getWithdrawalMessages($withdrawalId) : [];
        $userMsgCount  = 0;
        $adminMsgCount = 0;
        foreach ($messages as $m) {
            if ($m['sender_type'] === 'user') $userMsgCount++;
            else $adminMsgCount++;
        }

        // 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.
        $editPriorKeyboardsToBack($userId, $withdrawalId);

        AdminDB::logAction($currentUser['user_id'], 'close_withdrawal', 'withdrawal', (string)$withdrawalId);
        $closeTime = date('Y-m-d H:i:s');

        // Send a NEW message to the user with closure details
        if ($userId > 0) {
            $bot = new TelegramBot($config['telegram_bot_token']);
            $adminDisplayName = $currentUser['display_name'] ?? 'ادمین';
            $closeText  = emoji(32) . " برداشت #{$withdrawalId} بسته شد.\n\n";
            $closeText .= " زمان باز شدن: {$openTime}\n";
            $closeText .= " زمان بسته شدن: {$closeTime}\n";
            $closeText .= " تعداد پیام‌های شما: {$userMsgCount}\n";
            $closeText .= " تعداد پیام‌های ادمین: {$adminMsgCount}\n\n";
            $closeText .= " بسته شده توسط: " . $adminDisplayName;
            if ($refunded > 0) {
                $closeText .= "\n\n💰 مبلغ {$refunded} تومان که بابت این درخواست مسدود شده بود به موجودی شما بازگشت داده شد.";
            }
            try { $bot->sendMessage($userId, $closeText, backToMainMenuKeyboard()); } catch (\Throwable $e) {}
        }

        $_SESSION['flash'] = ['type' => 'success', 'msg' => "برداشت #{$withdrawalId} بسته شد و دکمه‌ها به‌روزرسانی شد." . ($refunded > 0 ? " مبلغ {$refunded} تومان موجودی مسدودشده به کاربر بازگشت داده شد." : '')];
    } else {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'بستن برداشت لغو شد.'];
    }
    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=withdrawal_detail&id=$withdrawalId");
    exit;
}

// ── POST: delete withdrawal ────────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'delete_withdrawal') {
    // Deleting a withdrawal is a destructive money-adjacent action — it
    // requires the 'withdrawals' permission (support-only admins keep
    // reply/close/chat). Mirrors the API's withdrawals:write gate.
    if (!$adminAuth->hasPermission('withdrawals')) {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'حذف درخواست برداشت فقط با دسترسی «برداشت‌ها» مجاز است.'];
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode(['ok' => false, 'flash' => $_SESSION['flash']]);
            exit;
        }
        header("Location: ?page=withdrawal_detail&id=$withdrawalId");
        exit;
    }
    $withdrawal = Database::getWithdrawal($withdrawalId);
    // Never delete a row that already reached a terminal money state — it is
    // the audit trail of a decided/paid payout (aligns with the API, which
    // refuses approve/reject on terminal states).
    // v2.9.45 (R6-61/L1): rows with a LIVE toman hold (open/claimed/answered —
    // card/stars/charge all debit up-front) are also undeletable: deleting one
    // destroyed the hold AND its only refund path.
    if ($withdrawal && in_array($withdrawal['status'], ['approved', 'rejected', 'paid', 'open', 'claimed', 'answered'], true)) {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'این درخواست در وضعیت نهایی یا در جریان (دارای موجودی مسدود) است و قابل حذف نیست.'];
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode(['ok' => false, 'flash' => $_SESSION['flash']]);
            exit;
        }
        header("Location: ?page=withdrawal_detail&id=$withdrawalId");
        exit;
    }
    $userId     = $withdrawal ? (int)$withdrawal['user_id'] : 0;

    $editPriorKeyboardsToBack($userId, $withdrawalId);

    // Delete all admin-uploaded files for this withdrawal from the HOST filesystem
    // BEFORE deleting the withdrawal from the DB.
    MediaStorage::deleteEntityFiles($withdrawalId, MediaStorage::KIND_WITHDRAWAL);

    Database::deleteWithdrawal($withdrawalId);
    AdminDB::logAction($currentUser['user_id'], 'delete_withdrawal', 'withdrawal', (string)$withdrawalId);

    $_SESSION['flash'] = ['type' => 'success', 'msg' => 'درخواست برداشت حذف شد.'];
    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=support&tab=withdrawals');
    exit;
}

// ── POST: approve withdrawal ───────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'approve_withdrawal') {
    // Approving pays out the withdrawal — requires the 'withdrawals'
    // permission (support-only admins keep reply/close/chat).
    if (!$adminAuth->hasPermission('withdrawals')) {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'تأیید درخواست برداشت فقط با دسترسی «برداشت‌ها» مجاز است.'];
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode(['ok' => false, 'flash' => $_SESSION['flash']]);
            exit;
        }
        header("Location: ?page=withdrawal_detail&id=$withdrawalId");
        exit;
    }
    $withdrawal = Database::getWithdrawal($withdrawalId);
    if ($withdrawal) {
        $userId = (int)$withdrawal['user_id'];
        $type   = (string)$withdrawal['type'];

        // Edit prior keyboards to back-to-main so the user can't tap "پاسخ"/"بستن"
        // after the withdrawal is already approved.
        $editPriorKeyboardsToBack($userId, $withdrawalId);

        $bot = new TelegramBot($config['telegram_bot_token']);
        $adminId   = (int)$currentUser['user_id'];
        $adminName = $currentUser['display_name'] ?? 'ادمین';

        if ($type === 'charge') {
            // Charge is normally auto-approved inside RechargeCode::assign.
            // This branch is the manual fallback: the admin fulfilled the
            // charge externally and wants to record the assigned code.
            $assignedCode = trim($_POST['assigned_code'] ?? '');
            // Withdrawal::approve sends the 'withdraw_approved' + 'satisfaction_prompt' messages.
            Withdrawal::approve($withdrawalId, $adminId, $adminName, null, $bot, $config);
            // Persist the assigned code separately (approve sets assigned_code=null).
            // T46-p: only stamp when the row really ended up 'approved' — the
            // old unconditional stamp flipped rejected (already refunded) /
            // closed rows to approved and could overwrite a delivered code.
            if ($assignedCode !== '') {
                $afterApprove = Database::getWithdrawal($withdrawalId);
                if ($afterApprove !== null && (string)$afterApprove['status'] === 'approved'
                    && trim((string)($afterApprove['assigned_code'] ?? '')) === '') {
                    Database::approveWithdrawal($withdrawalId, null, $assignedCode, ['approved']);
                }
            }
        } else {
            // stars / card: $txid is the payment transaction reference.
            $txid = trim($_POST['txid'] ?? '');
            Withdrawal::approve($withdrawalId, $adminId, $adminName, $txid !== '' ? $txid : null, $bot, $config);
        }

        AdminDB::logAction($adminId, 'approve_withdrawal', 'withdrawal', (string)$withdrawalId);
        $_SESSION['flash'] = ['type' => 'success', 'msg' => "برداشت #{$withdrawalId} تأیید شد و به کاربر اطلاع داده شد."];
    } else {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'درخواست برداشت یافت نشد.'];
    }
    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=withdrawal_detail&id=$withdrawalId");
    exit;
}

// ── POST: reject withdrawal ────────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'reject_withdrawal') {
    // Rejecting refunds the held amount and ends the request — requires the
    // 'withdrawals' permission (support-only admins keep reply/close/chat).
    if (!$adminAuth->hasPermission('withdrawals')) {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'رد درخواست برداشت فقط با دسترسی «برداشت‌ها» مجاز است.'];
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode(['ok' => false, 'flash' => $_SESSION['flash']]);
            exit;
        }
        header("Location: ?page=withdrawal_detail&id=$withdrawalId");
        exit;
    }
    $withdrawal = Database::getWithdrawal($withdrawalId);
    if ($withdrawal) {
        $userId = (int)$withdrawal['user_id'];

        // Edit prior keyboards to back-to-main so the user can't tap "پاسخ"/"بستن".
        $editPriorKeyboardsToBack($userId, $withdrawalId);

        $bot       = new TelegramBot($config['telegram_bot_token']);
        $adminId   = (int)$currentUser['user_id'];
        $adminName = $currentUser['display_name'] ?? 'ادمین';
        $reason    = trim($_POST['reason'] ?? '');
        $reasonArg = $reason !== '' ? $reason : null;

        // Withdrawal::reject sends the user the rejection message (with reason)
        // and refunds card withdrawals (Wallet::credit 'withdrawal_refund').
        Withdrawal::reject($withdrawalId, $reasonArg, $adminId, $adminName, $bot, $config);

        AdminDB::logAction($adminId, 'reject_withdrawal', 'withdrawal', (string)$withdrawalId);
        $_SESSION['flash'] = ['type' => 'success', 'msg' => "برداشت #{$withdrawalId} رد شد و به کاربر اطلاع داده شد."];
    } else {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'درخواست برداشت یافت نشد.'];
    }
    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=withdrawal_detail&id=$withdrawalId");
    exit;
}

// ── POST: answer withdrawal (text reply) ───────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'answer_withdrawal') {
    $answer = trim($_POST['answer'] ?? '');
    if ($answer !== '') {
        if (in_array($withdrawal['status'], ['open', 'claimed', 'answered'], true)) {
            if ($withdrawal['status'] === 'open') {
                // Two-admin claim race: claimWithdrawal is atomic (status='open'
                // in the WHERE). On a lost race the withdrawal was claimed by
                // someone else while this reply was being typed — abort with a
                // clear message instead of silently answering a claimed ticket.
                if (!Database::claimWithdrawal($withdrawalId, (int)$currentUser['user_id'], $currentUser['display_name'])) {
                    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'این درخواست هم‌اکنون توسط ادمین دیگری پاسخ داده می‌شود.'];
                    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
                        header('Content-Type: application/json');
                        echo json_encode(['ok' => false, 'flash' => $_SESSION['flash']]);
                        exit;
                    }
                    header("Location: ?page=withdrawal_detail&id=$withdrawalId");
                    exit;
                }
            }
            // 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 = Withdrawal::addAdminMessage(
                $withdrawalId,
                (int)$currentUser['user_id'],
                $currentUser['display_name'],
                $contentType,
                $answer,
                null, null, null, null
            );
            Database::answerWithdrawal($withdrawalId, $answer);
            AdminDB::logAction($currentUser['user_id'], 'answer_withdrawal', 'withdrawal', (string)$withdrawalId);

            // Send to user — the answer already has markdown, send as-is.
            $bot = new TelegramBot($config['telegram_bot_token']);
            $adminName = $currentUser['display_name'] ?? 'پشتیبانی';
            $userText  = emoji(7) . ' پاسخ به درخواست برداشت #' . $withdrawalId . ":\n\n" . $answer;
            // T46-az: loaded custom-emoji pack emojis render as <tg-emoji> tags
            $userText  = CustomEmoji::apply($userText);
            $result = $bot->sendMessage(
                (int)$withdrawal['user_id'],
                $userText,
                withdrawalAnswerKeyboard($adminName, $withdrawalId)
            );

            // Store the Telegram message_id so we can edit buttons later.
            if ($result && isset($result->ok) && $result->ok && isset($result->result->message_id)) {
                Database::updateWithdrawalMessageTgId($msgDbId, (int)$result->result->message_id, (int)$withdrawal['user_id']);
            }

            $_SESSION['flash'] = ['type' => 'success', 'msg' => 'پاسخ ارسال شد.'];
        } else {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'این برداشت قابل پاسخ نیست (بسته/تأیید/رد شده).'];
        }
    } else {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'پاسخ نمی‌تواند خالی باشد.'];
    }
    // AJAX → 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=withdrawal_detail&id=$withdrawalId");
    exit;
}

// ── POST: send media (file upload) ─────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'send_media') {
    if (in_array($withdrawal['status'], ['open', 'claimed', 'answered'], true)) {
        if ($withdrawal['status'] === 'open') {
            // Two-admin claim race: see answer_withdrawal above — abort when
            // another admin won the atomic claim.
            if (!Database::claimWithdrawal($withdrawalId, (int)$currentUser['user_id'], $currentUser['display_name'])) {
                $_SESSION['flash'] = ['type' => 'error', 'msg' => 'این درخواست هم‌اکنون توسط ادمین دیگری پاسخ داده می‌شود.'];
                if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
                    header('Content-Type: application/json');
                    echo json_encode(['ok' => false, 'flash' => $_SESSION['flash']]);
                    exit;
                }
                header("Location: ?page=withdrawal_detail&id=$withdrawalId");
                exit;
            }
        }
        $caption   = trim($_POST['caption'] ?? '');
        $mediaType = $_POST['media_type'] ?? 'document';

        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).
            $hostFilePath = MediaStorage::saveUpload($_FILES['media_file'], $withdrawalId, MediaStorage::KIND_WITHDRAWAL);

            // 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)$withdrawal['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';
            }

            // Caption: same prefix as text replies so the user sees a consistent header.
            $captionText = emoji(7) . ' پاسخ به درخواست برداشت #' . $withdrawalId . ":\n\n" . $caption;
            // 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'] = withdrawalAnswerKeyboard($adminName, $withdrawalId);

            $result = $bot->sendMedia($apiMethod, $params);

            $fileId = '';
            $storedType = $mediaType;
            if ($result && isset($result->ok) && $result->ok) {
                $fileId = $result->result->{$fileKey}->file_id ?? '';
                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;
                Withdrawal::addAdminMessage(
                    $withdrawalId,
                    (int)$currentUser['user_id'],
                    $currentUser['display_name'],
                    $storedType,
                    $storeText,
                    $fileId !== '' ? $fileId : null,
                    $tgMsgId > 0 ? $tgMsgId : null,
                    (int)$withdrawal['user_id'],
                    $hostFilePath
                );
            } else {
                // Telegram send failed — remove the file from the host so we
                // don't accumulate orphaned files.
                MediaStorage::deleteFile($hostFilePath);
            }

            $_SESSION['flash'] = ['type' => 'success', 'msg' => 'فایل ارسال شد.'];
        } else {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'فایلی انتخاب نشده یا خطا در آپلود.'];
        }
    } else {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'این برداشت قابل پاسخ نیست.'];
    }
    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=withdrawal_detail&id=$withdrawalId");
    exit;
}

// Reload withdrawal + messages after any POST handler that fell through.
$withdrawal = Database::getWithdrawal($withdrawalId);
$messages   = Database::getWithdrawalMessages($withdrawalId);

// Fetch the withdrawal user's data for the info panel shown below the first
// message of the conversation. Wrapped in try/catch so a missing column or
// table doesn't 500 the page.
$__withdrawalUser = null;
$__withdrawalUserCompletedTasks = 0;
if (!empty($withdrawal['user_id'])) {
    try { $__withdrawalUser = Database::loadUser((int)$withdrawal['user_id']); } catch (\Throwable $e) {}
    try { $__withdrawalUserCompletedTasks = count(Database::getCompletedTasksForUser((int)$withdrawal['user_id'])); } catch (\Throwable $e) {}
}
$__genderLabels = ['نامشخص', 'پسر', 'دختر'];
$__withdrawalUserGender = $__genderLabels[(int)($__withdrawalUser['gender'] ?? 0)] ?? 'نامشخص';

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>';
}

$TYPE_LABELS = [
    'charge' => 'شارژ',
    'stars'  => 'استارز',
    'card'   => 'کارت به کارت',
];
$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'],
    'approved' => ['dot' => '#22c55e', 'label' => 'تأیید شده',          'color' => '#22c55e'],
    'rejected' => ['dot' => '#ef4444', 'label' => 'رد شده',             'color' => '#ef4444'],
    'paid'     => ['dot' => '#22c55e', 'label' => 'پرداخت شده',         'color' => '#22c55e'],
];
$sm = $STATUS_META[$withdrawal['status']] ?? $STATUS_META['open'];
$isClosed   = in_array($withdrawal['status'], ['closed','approved','rejected','paid'], true);
$typeLabel  = $TYPE_LABELS[$withdrawal['type']] ?? $withdrawal['type'];
$canReply   = in_array($withdrawal['status'], ['open','claimed','answered'], true);
?>

<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=withdrawals" 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)$withdrawalId ?></span>
                <span style="color:#5a6b85;font-weight:500;font-size:13px;">— <?= e($typeLabel) ?></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($withdrawal['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($withdrawal['question_time']) ?></span>
                <?php if (!empty($withdrawal['amount']) && (int)$withdrawal['amount'] > 0): ?>
                <span style="display:inline-flex;align-items:center;gap:4px;color:#22d3ee;font-weight:600;"><?= number_format((int)$withdrawal['amount']) ?> تومان</span>
                <?php endif; ?>
                <?php if (!empty($withdrawal['operator'])): ?>
                <span style="display:inline-flex;align-items:center;gap:4px;">اپراتور: <?= e(Withdrawal::getOperatorName($withdrawal['operator'])) ?></span>
                <?php endif; ?>
            </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>
    </div>

    <!-- Action buttons row -->
    <div class="glass-card" style="display:flex;flex-wrap:wrap;gap:8px;padding:10px 12px;margin-bottom:0;">
        <?php if ($canReply): ?>
        <button onclick="document.getElementById('replyAreaInner').scrollIntoView({behavior:'smooth',block:'center'});document.getElementById('answerText').focus();" 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="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg> پاسخ</button>
        <?php endif; ?>
        <?php if ($withdrawal['status'] !== 'approved' && $withdrawal['status'] !== 'rejected' && $withdrawal['status'] !== 'closed'): ?>
        <button onclick="document.getElementById('approveModal').style.display='flex'" class="btn btn-sm" style="display:inline-flex;align-items:center;gap:6px;background:rgba(34,197,94,0.15);color:#22c55e;border:1px solid rgba(34,197,94,0.3);"><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="M20 6 9 17l-5-5"/></svg> تأیید برداشت</button>
        <button onclick="document.getElementById('rejectModal').style.display='flex'" class="btn btn-sm" style="display:inline-flex;align-items:center;gap:6px;background:rgba(239,68,68,0.15);color:#ef4444;border:1px solid rgba(239,68,68,0.3);"><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="M18 6 6 18"/><path d="m6 6 12 12"/></svg> رد کردن</button>
        <?php endif; ?>
        <?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 $__msgIdx = 0; ?>
            <?php foreach ($messages as $msg):
                $isUser = $msg['sender_type'] === 'user';
                $formattedText = formatChatMessageText($msg);
                $mediaHtml = renderMediaHtml($msg);

                // For the FIRST message, format the text with emoji + label
                // based on the withdrawal type so admins see a clean summary
                // (card number / stars / charge operator+amount) instead of
                // the raw user-supplied string.
                if ($__msgIdx === 0) {
                    $__rawFirst = $msg['text'] ?? '';
                    if ($withdrawal['type'] === 'card') {
                        $formattedText = '<b>💳 شماره کارت:</b> ' . nl2br(htmlspecialchars($__rawFirst, ENT_QUOTES | ENT_HTML5, 'UTF-8'));
                    } elseif ($withdrawal['type'] === 'stars') {
                        // Strip the trailing " (مبلغ: X تومان)" suffix that Withdrawal::createStarsRequest appends.
                        $__starsDesc = preg_replace('/\s*\(مبلغ:\s*\d+\s*تومان\)\s*$/u', '', $__rawFirst);
                        $formattedText = '<b>⭐ تعداد استارز:</b> ' . htmlspecialchars($__starsDesc, ENT_QUOTES | ENT_HTML5, 'UTF-8');
                    } elseif ($withdrawal['type'] === 'charge') {
                        $__opName = Withdrawal::getOperatorName($withdrawal['operator'] ?? '');
                        $__amount = (int)($withdrawal['amount'] ?? 0);
                        $formattedText = '<b>📱 اپراتور:</b> ' . htmlspecialchars($__opName, ENT_QUOTES | ENT_HTML5, 'UTF-8')
                            . '<br><b>💰 مبلغ:</b> ' . number_format($__amount) . ' تومان';
                    }
                }
            ?>
            <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 if ($__msgIdx === 0 && $__withdrawalUser !== null): ?>
            <div class="tg-row in" style="opacity:0.92;">
                <div class="tg-bubble" style="background:rgba(34,211,238,0.05);border:1px dashed rgba(34,211,238,0.22);">
                    <div class="tg-body" style="font-size:12px;line-height:1.9;white-space:pre-line;">
────────────
👤 نام: <?= e($__withdrawalUser['displayName'] ?? '-') ?>
💰 توکن بازی: <?= number_format((int)($__withdrawalUser['gameTokens'] ?? 0)) ?>
💵 تومان: <?= number_format((int)($__withdrawalUser['toman'] ?? 0)) ?>
🪙 NTX: <?= number_format((int)($__withdrawalUser['ntxBalance'] ?? 0)) ?>
⚧️ جنسیت: <?= e($__withdrawalUserGender) ?>
📋 تسک‌های انجام شده: <?= number_format($__withdrawalUserCompletedTasks) ?>
👥 زیرمجموعه‌ها: <?= number_format((int)($__withdrawalUser['sub_count'] ?? 0)) ?>
────────────
                    </div>
                </div>
            </div>
            <?php endif; ?>
            <?php $__msgIdx++; endforeach; ?>
        </div>
    </div>

    <!-- Reply area -->
    <div class="glass-card" style="padding:16px 20px;margin-bottom:0;">
        <div id="replyAreaInner">
        <?php if (!$canReply): ?>
            <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;">این برداشت قابل پاسخ نیست (<?= e($sm['label']) ?>).</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_withdrawal">
                <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>

<!-- Approve modal -->
<div id="approveModal" style="display:none;position:fixed;inset:0;z-index:100;align-items:center;justify-content:center;padding:16px;">
    <div onclick="document.getElementById('approveModal').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:460px;background:rgba(10,12,26,0.95);border:1px solid rgba(34,197,94,0.25);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('approveModal').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="#22c55e" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg> تأیید برداشت #<?= (int)$withdrawalId ?></h3>
        <p style="margin-bottom:18px;color:#9fb0c9;line-height:1.7;font-size:13px;">با تأیید این برداشت، مبلغ/کد به کاربر اطلاع داده شده و کاربر تا ارسال رضایت‌سنجی از سایر امکانات ربات مسدود می‌شود.</p>
        <form method="POST" id="approveForm" onsubmit="return submitApprove(event);">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="approve_withdrawal">
            <?php if ($withdrawal['type'] === 'charge'): ?>
            <div class="form-group" style="margin-bottom:16px;">
                <label>کد شارژ اختصاص‌یافته (اختیاری)</label>
                <input type="text" name="assigned_code" class="form-control" placeholder="کد شارژ را وارد کنید..." style="direction:ltr;text-align:left;">
                <small style="display:block;margin-top:4px;color:#5a6b85;font-size:11px;">اگر کد را به‌صورت دستی به کاربر داده‌اید، اینجا وارد کنید تا در سوابق ثبت شود.</small>
            </div>
            <?php else: ?>
            <div class="form-group" style="margin-bottom:16px;">
                <label>شناسه تراکنش / TXID (اختیاری)</label>
                <input type="text" name="txid" class="form-control" placeholder="مثلاً شماره واریز یا TXID استارز..." style="direction:ltr;text-align:left;">
                <small style="display:block;margin-top:4px;color:#5a6b85;font-size:11px;">برای پیگیری مالی در سوابق ثبت می‌شود.</small>
            </div>
            <?php endif; ?>
            <div style="display:flex;gap:8px;justify-content:flex-end;">
                <button type="button" class="btn btn-glass btn-sm" onclick="document.getElementById('approveModal').style.display='none'">لغو</button>
                <button type="submit" class="btn btn-sm" style="background:#22c55e;color:#fff;">بله، تأیید کن</button>
            </div>
        </form>
    </div>
</div>

<!-- Reject modal -->
<div id="rejectModal" style="display:none;position:fixed;inset:0;z-index:100;align-items:center;justify-content:center;padding:16px;">
    <div onclick="document.getElementById('rejectModal').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:460px;background:rgba(10,12,26,0.95);border:1px solid rgba(239,68,68,0.25);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('rejectModal').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="#ef4444" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg> رد برداشت #<?= (int)$withdrawalId ?></h3>
        <p style="margin-bottom:18px;color:#9fb0c9;line-height:1.7;font-size:13px;">
            با رد این درخواست، وضعیت به «رد شده» تغییر می‌کند.
            <?php if ($withdrawal['type'] === 'card'): ?>
             مبلغ debited شده به کاربر بازگردانده می‌شود.
            <?php endif; ?>
        </p>
        <form method="POST" id="rejectForm" onsubmit="return submitReject(event);">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="reject_withdrawal">
            <div class="form-group" style="margin-bottom:16px;">
                <label>دلیل رد (اختیاری)</label>
                <textarea name="reason" class="form-control" rows="3" placeholder="دلیل رد را برای کاربر توضیح دهید..." style="font-family:inherit;line-height:1.6;resize:vertical;width:100%;"></textarea>
            </div>
            <div style="display:flex;gap:8px;justify-content:flex-end;">
                <button type="button" class="btn btn-glass btn-sm" onclick="document.getElementById('rejectModal').style.display='none'">لغو</button>
                <button type="submit" class="btn btn-danger btn-sm">بله، رد کن</button>
            </div>
        </form>
    </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)$withdrawalId ?></h3>
        <p style="margin-bottom:18px;color:#9fb0c9;line-height:1.7;font-size:13px;">آیا از بستن این درخواست مطمئن هستید؟ کاربر دیگر نمی‌تواند پاسخ دهد.</p>
        <?php if (in_array($withdrawal['status'] ?? '', ['open', 'claimed', 'answered'], true) && in_array($withdrawal['type'] ?? '', ['card', 'stars'], true) && (int)($withdrawal['amount'] ?? 0) > 0): ?>
        <p style="margin:-10px 0 18px;color:#fbbf24;line-height:1.7;font-size:12px;">💡 توجه: مبلغ <?= number_format((int)$withdrawal['amount']) ?> تومان که از موجودی کاربر بابت این درخواست مسدود شده بود، با بستن به‌صورت خودکار به او بازگردانده می‌شود.</p>
        <?php endif; ?>
        <form method="POST" style="display:flex;gap:8px;justify-content:flex-end;">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="close_withdrawal">
            <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)$withdrawalId ?></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_withdrawal">
            <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 withdrawalId = <?= (int)$withdrawalId ?>;

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=withdrawal_detail&id=' + withdrawalId + '&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','بسته شده'],
                    approved:['#22c55e','تأیید شده'], rejected:['#ef4444','رد شده'],
                    paid:['#22c55e','پرداخت شده']
                };
                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];
            }
            // Lock the reply area once the withdrawal leaves the answerable set.
            var answerable = ['open','claimed','answered'];
            if (answerable.indexOf(data.status) === -1) {
                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 (mf && mf.style.display !== 'none' && mf.offsetParent !== null) return 'captionText';
    return 'answerText';
}
function wrapActive(open, close, ph) {
    wrapSelT(getActiveTextareaId(), open, close, ph);
}
function wrapQuoteActive() {
    wrapQuoteT(getActiveTextareaId());
}
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_withdrawal');
    fd.append('answer', answer);
    var csrf = document.querySelector('meta[name=csrf-token]');
    if (csrf) fd.append('csrf_token', csrf.content);
    fetch('?page=withdrawal_detail&id=' + withdrawalId, {
        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);
    var csrf = document.querySelector('meta[name=csrf-token]');
    if (csrf) fd.append('csrf_token', csrf.content);
    fetch('?page=withdrawal_detail&id=' + withdrawalId, {
        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;
}

function submitApprove(event) {
    event.preventDefault();
    var form = document.getElementById('approveForm');
    var fd = new FormData(form);
    var csrf = document.querySelector('meta[name=csrf-token]');
    if (csrf) fd.append('csrf_token', csrf.content);
    var btn = form.querySelector('button[type=submit]');
    if (btn) { btn.disabled = true; btn.textContent = 'در حال ارسال...'; }
    fetch('?page=withdrawal_detail&id=' + withdrawalId, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: fd
    }).then(function(r) { return r.json(); }).then(function(data) {
        if (data.ok) {
            document.getElementById('approveModal').style.display = 'none';
            // Reload to refresh status + UI.
            window.location.reload();
        } else {
            if (btn) { btn.disabled = false; btn.textContent = 'بله، تأیید کن'; }
            alert((data.flash && data.flash.msg) ? data.flash.msg : 'خطا در تأیید.');
        }
    }).catch(function() {
        if (btn) { btn.disabled = false; btn.textContent = 'بله، تأیید کن'; }
        alert('خطا در ارتباط با سرور.');
    });
    return false;
}

function submitReject(event) {
    event.preventDefault();
    var form = document.getElementById('rejectForm');
    var fd = new FormData(form);
    var csrf = document.querySelector('meta[name=csrf-token]');
    if (csrf) fd.append('csrf_token', csrf.content);
    var btn = form.querySelector('button[type=submit]');
    if (btn) { btn.disabled = true; btn.textContent = 'در حال ارسال...'; }
    fetch('?page=withdrawal_detail&id=' + withdrawalId, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: fd
    }).then(function(r) { return r.json(); }).then(function(data) {
        if (data.ok) {
            document.getElementById('rejectModal').style.display = 'none';
            window.location.reload();
        } else {
            if (btn) { btn.disabled = false; btn.textContent = 'بله، رد کن'; }
            alert((data.flash && data.flash.msg) ? data.flash.msg : 'خطا در رد.');
        }
    }).catch(function() {
        if (btn) { btn.disabled = false; btn.textContent = 'بله، رد کن'; }
        alert('خطا در ارتباط با سرور.');
    });
    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'; ?>
