<?php
$pageTitle = 'ارسال پیام همگانی';
$adminAuth->requireOwner();

global $config;

$result = null;

// ── One-time nonce against refresh re-send ────────────────────────
// F5 after a broadcast re-POSTs the form and would spam every user again.
// The rendered form carries $_SESSION['broadcast_nonce']; on POST the value
// is verified and IMMEDIATELY regenerated (single use). A replayed POST hits
// the mismatch branch below. The nonce is armed on the first GET render and
// re-armed after every POST, so multiple tabs keep working.
$broadcastNonceOk = false;
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $expectedNonce = $_SESSION['broadcast_nonce'] ?? '';
    $sentNonce     = (string)($_POST['broadcast_nonce'] ?? '');
    $_SESSION['broadcast_nonce'] = bin2hex(random_bytes(16)); // burn it now
    $broadcastNonceOk = $expectedNonce !== '' && hash_equals($expectedNonce, $sentNonce);
} elseif (empty($_SESSION['broadcast_nonce'])) {
    $_SESSION['broadcast_nonce'] = bin2hex(random_bytes(16));
}

if (!$broadcastNonceOk
    && isset($_POST['action'])
    && ($_POST['action'] === 'send_broadcast' || $_POST['action'] === 'send_broadcast_media')) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'درخواست تکراری؛ عملیات انجام نشد.'];
    header("Location: ?page=broadcast");
    exit;
}

// ── POST: send text broadcast ─────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'send_broadcast') {
    $messageText = trim($_POST['message'] ?? '');

    if ($messageText === '') {
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'متن پیام خالی است.'];
        header("Location: ?page=broadcast");
        exit;
    }

    // T46-ar: enqueue-only — the paced queue engine (cron.php + bcloop.php,
    // ~25 msg/s, 429-aware, resumable) sends in the background; the panel
    // answers immediately and the progress card below tracks the job.
    $userIds = Database::getAllUserIds();
    $adminId = (int)$currentUser['user_id'];
    $adminName = $currentUser['display_name'] ?? 'ادمین';

    $broadcastId = Database::createBroadcast($adminId, $adminName, $messageText, 'text', null, null);
    BroadcastEngine::enqueue('send', 'sendMessage',
        json_encode(['text' => $messageText, 'parse_mode' => 'Markdown'], JSON_UNESCAPED_UNICODE),
        json_encode(array_map('intval', $userIds)), $broadcastId);
    AdminDB::logAction($adminId, 'broadcast', 'message', null, "total=" . count($userIds) . ",queued=1");

    $result = ['total' => count($userIds), 'sent' => 0, 'failed' => 0, 'queued' => true];
}

// ── POST: send media broadcast ────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'send_broadcast_media') {
    $caption = trim($_POST['caption'] ?? '');
    $mediaType = $_POST['media_type'] ?? 'document';
    $adminId = (int)$currentUser['user_id'];
    $adminName = $currentUser['display_name'] ?? 'ادمین';

    if (isset($_FILES['media_file']) && $_FILES['media_file']['error'] === UPLOAD_ERR_OK) {
        $tmpName = $_FILES['media_file']['tmp_name'];
        $origName = $_FILES['media_file']['name'];
        $curlFile = new CURLFile($tmpName, $_FILES['media_file']['type'], $origName);

        $userIds = Database::getAllUserIds();
        $bot = new TelegramBot($config['telegram_bot_token']);

        // Auto-detect
        $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';
        }

        $fileId = null;
        $sent = 0;
        $failed = 0;
        $total = count($userIds);
        $messageIds = [];
        set_time_limit(max(180, (int)($total * 0.35) + 120)); // v2.9.45 (R6-82): realistic 0.35s/user budget

        // First send to get file_id
        $firstUid = $userIds[0] ?? 0;
        if ($firstUid > 0) {
            $params = ['chat_id' => $firstUid, $mediaType => $curlFile];
            if ($caption) $params['caption'] = $caption;
            $apiMethod = 'sendDocument';
            if ($mediaType === 'photo') $apiMethod = 'sendPhoto';
            elseif ($mediaType === 'video') $apiMethod = 'sendVideo';
            elseif ($mediaType === 'audio') $apiMethod = 'sendAudio';

            // Use sendMedia() so [[emoji_id]] placeholders and markdown in the
            // caption are processed (consistent with text broadcasts which use
            // sendMessage with parse_mode=Markdown). Also falls back to
            // sendDocument if sendPhoto/Video/Audio fails (e.g. wrong file type).
            $firstResult = $bot->sendMedia($apiMethod, $params);
            if ($firstResult && isset($firstResult->ok) && $firstResult->ok) {
                // Try the original file key first (photo/video/audio/document).
                $fileId = $firstResult->result->{$mediaType}->file_id ?? null;
                // If the original key wasn't present, the sendMedia() fallback
                // may have sent it as a document instead. Use the document
                // file_id and switch mediaType+apiMethod to 'document' so the
                // remaining users also receive it as a document.
                if ($fileId === null && $mediaType !== 'document'
                    && isset($firstResult->result->document->file_id)) {
                    $fileId = $firstResult->result->document->file_id;
                    $mediaType = 'document';
                    $apiMethod = 'sendDocument';
                }
                $sent++;
                $messageIds[$firstUid] = (int)$firstResult->result->message_id;
            } else {
                $failed++;
            }
            usleep(35000);
        }

        // T46-ar: the first send above (file_id capture) stays inline — ONE
        // send. The remaining users are handled by the paced queue engine;
        // prepared here, enqueued right after the broadcast row exists.
        $bcRestIds = [];
        $bcApiMethod = 'sendDocument';
        $bcParams = [];
        if ($fileId) {
            $bcApiMethod = 'sendDocument';
            if ($mediaType === 'photo') $bcApiMethod = 'sendPhoto';
            elseif ($mediaType === 'video') $bcApiMethod = 'sendVideo';
            elseif ($mediaType === 'audio') $bcApiMethod = 'sendAudio';
            for ($i = 1; $i < count($userIds); $i++) {
                $bcRestIds[] = (int)$userIds[$i];
            }
            $bcParams = [$mediaType => $fileId];
            if ($caption) $bcParams['caption'] = $caption;
        }

        $broadcastText = $caption !== '' ? $caption : 'فایل: ' . $origName;
        $broadcastId = Database::createBroadcast($adminId, $adminName, $broadcastText, $mediaType, $fileId, $caption);
        // T46-ar: enqueue the remaining users (paced ~25 msg/s) linked to
        // this broadcast row so the progress card can follow it.
        if (!empty($bcRestIds)) {
            BroadcastEngine::enqueue('send', $bcApiMethod,
                json_encode($bcParams, JSON_UNESCAPED_UNICODE),
                json_encode($bcRestIds), $broadcastId);
        }
        Database::updateBroadcastMessageIds($broadcastId, $messageIds, $sent);
        AdminDB::logAction($adminId, 'broadcast_media', 'message', null, "total={$total},sent={$sent},queued=" . count($bcRestIds));

        $result = ['total' => $total, 'sent' => $sent, 'failed' => $failed, 'queued' => count($bcRestIds)];
    }
}

// ── POST: delete broadcast ────────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'delete_broadcast') {
    $bid = (int)$_POST['broadcast_id'];
    $broadcast = Database::getBroadcast($bid);
    if ($broadcast) {
        // T46-ar: the Telegram-side removal runs through the paced queue;
        // the broadcasts row is deleted by the engine when the last
        // message is gone.
        $messageIds = json_decode($broadcast['message_ids'] ?? '{}', true);
        $queued = 0;
        if (is_array($messageIds) && !empty($messageIds)) {
            BroadcastEngine::enqueue('delete', 'deleteMessage', '{}', json_encode($messageIds), $bid);
            $queued = count($messageIds);
            $_SESSION['flash'] = ['type' => 'success', 'msg' => "حذف پیام همگانی در صف قرار گرفت ({$queued} پیام) و به‌صورت خودکار از تلگرام پاک می‌شود."];
        } else {
            Database::deleteBroadcast($bid);
            $_SESSION['flash'] = ['type' => 'success', 'msg' => 'پیام همگانی حذف شد.'];
        }
        AdminDB::logAction($currentUser['user_id'], 'delete_broadcast', 'broadcast', (string)$bid, "queued={$queued}");
    }
    header("Location: ?page=broadcast");
    exit;
}

$broadcasts = Database::getBroadcasts(50);

require __DIR__ . '/layout_top.php';
?>

<style>
select.form-control, option {
    background: rgba(10,12,26,0.95) !important;
    color: var(--text, #e2e8f0) !important;
}
select.form-control option {
    background: rgba(10,12,26,0.95) !important;
    color: var(--text, #e2e8f0) !important;
}
</style>

<div class="page-header">
    <h1><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" style="vertical-align:-3px;margin-left:6px;"><path d="m3 11 18-5v12L3 14v-3z"/><path d="M11.6 16.8a3 3 0 1 1-5.8-1.6"/></svg> ارسال پیام همگانی</h1>
    <span class="breadcrumb">خانه / ارسال پیام همگانی</span>
</div>

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

<?php if ($result !== null): ?>
<div class="glass-card" style="margin-bottom:24px;border-left:4px solid var(--success);">
    <div style="padding:16px;">
        <div style="font-size:18px;font-weight:700;margin-bottom:8px;display:flex;align-items:center;gap:8px;"><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="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><path d="m9 11 3 3L22 4"/></svg> <?= !empty($result['queued']) ? 'پیام در صف ارسال قرار گرفت' : 'ارسال با موفقیت انجام شد' ?></div>
        <div style="display:flex;gap:24px;flex-wrap:wrap;">
            <div style="display: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="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg> کل کاربران: <strong><?= (int)$result['total'] ?></strong></div>
            <div style="color:var(--success);display: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 11.08V12a10 10 0 1 1-5.93-9.14"/><path d="m9 11 3 3L22 4"/></svg> موفق: <strong><?= (int)$result['sent'] ?></strong></div>
            <div style="color:var(--danger);display: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"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg> ناموفق: <strong><?= (int)$result['failed'] ?></strong></div>
        </div>
        <?php if (!empty($result['queued'])): ?>
        <div style="margin-top:10px;color:var(--text-muted);font-size:13px;">ارسال به‌صورت خودکار و پله‌ای انجام می‌شود (مقاوم در برابر قطعی). پیشرفت در کادر «صف ارسال همگانی» زیر دیده می‌شود؛ می‌توانید همین حالا صفحه را ببندید.</div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<div class="glass-card">
    <div class="card-title" style="margin-bottom:16px;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"><rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg> ارسال پیام به همه کاربران</div>

    <!-- Toggle row: just the "switch to media" button. The format toolbars
         live INSIDE each form so only the active form's toolbar is visible. -->
    <div style="display:flex;justify-content:flex-end;margin-bottom:8px;">
        <button type="button" class="btn btn-glass btn-xs" onclick="bcToggleMedia()" title="ارسال فایل" id="bcToggleMediaBtn" style="display:inline-flex;align-items:center;gap:4px;"><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>

    <!-- Text form -->
    <form method="POST" id="bcTextForm">
            <?= csrf_field() ?>
        <input type="hidden" name="action" value="send_broadcast">
        <input type="hidden" name="broadcast_nonce" value="<?= e($_SESSION['broadcast_nonce']) ?>">
        <!-- Format toolbar (inside the text form so it's hidden when media form is shown) -->
        <div style="display:flex;gap:6px;margin-bottom:8px;flex-wrap:wrap;align-items:center;">
            <span style="font-size:12px;color:var(--text-muted);margin-left:4px;">فرمت:</span>
            <button type="button" class="btn btn-glass btn-xs" onclick="bcWrap('**','**','bcMessageText')" title="پررنگ" style="font-weight:bold;">B</button>
            <button type="button" class="btn btn-glass btn-xs" onclick="bcWrap('__','__','bcMessageText')" title="کج" style="font-style:italic;">I</button>
            <button type="button" class="btn btn-glass btn-xs" onclick="bcWrap('`','`','bcMessageText')" title="کد">&lt;/&gt;</button>
            <button type="button" class="btn btn-glass btn-xs" onclick="bcQuote('bcMessageText')" title="نقل‌قول" style="display:inline-flex;align-items:center;"><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="bcWrap('||','||','bcMessageText')" title="اسپویلر" style="display:inline-flex;align-items:center;"><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>
        <div class="form-group">
            <label>متن پیام</label>
            <textarea name="message" id="bcMessageText" class="form-control" rows="8" required
                placeholder="متن پیام خود را وارد کنید...&#10;برای ایموجی کاستم از [[ایدی]] استفاده کنید. مثال: [[5812198298999596295]]"
                style="font-family:inherit;line-height:1.6;resize:vertical;"></textarea>
            <?= CustomEmoji::webPickerHtml(['bcMessageText']) ?>
            <small style="color:var(--text-muted);">
                از [[ایدی ایموجی]] برای ایموجی کاستم استفاده کنید. مثال: [[5812198298999596295]]
            </small>
        </div>
        <div style="margin-top:16px;display:flex;gap:12px;align-items:center;flex-wrap:wrap;"><!-- T46-r: flex-wrap added — button + warning span cramped at 360px -->
            <button type="submit" class="btn btn-primary" style="padding:14px 32px;display:inline-flex;align-items:center;gap:8px;"
                onclick="return confirm('آیا مطمئن هستید؟ این پیام به همه کاربران ارسال می‌شود.')">
                <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="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg> ارسال
            </button>
            <span style="color:var(--text-muted);font-size:13px;display:inline-flex;align-items:center;gap:4px;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fbbf24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" x2="12" y1="9" y2="13"/><line x1="12" x2="12.01" y1="17" y2="17"/></svg> این عملیات قابل لغو نیست.</span>
        </div>
    </form>

    <!-- Media form (hidden by default) -->
    <form method="POST" id="bcMediaForm" enctype="multipart/form-data" style="display:none;margin-top:12px;border-top:1px solid var(--border);padding-top:12px;">
            <?= csrf_field() ?>
        <input type="hidden" name="action" value="send_broadcast_media">
        <input type="hidden" name="broadcast_nonce" value="<?= e($_SESSION['broadcast_nonce']) ?>">
        <div class="grid-2">
            <div class="form-group">
                <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">
                <label>فایل</label>
                <input type="file" name="media_file" class="form-control" required style="padding:8px;">
            </div>
        </div>
        <div class="form-group">
            <label>کپشن (اختیاری)</label>
            <!-- Format toolbar (targets the caption textarea below) -->
            <div style="display:flex;gap:6px;margin-bottom:6px;flex-wrap:wrap;align-items:center;">
                <span style="font-size:12px;color:var(--text-muted);margin-left:4px;">فرمت:</span>
                <button type="button" class="btn btn-glass btn-xs" onclick="bcWrap('**','**','bcCaptionText')" title="پررنگ" style="font-weight:bold;">B</button>
                <button type="button" class="btn btn-glass btn-xs" onclick="bcWrap('__','__','bcCaptionText')" title="کج" style="font-style:italic;">I</button>
                <button type="button" class="btn btn-glass btn-xs" onclick="bcWrap('`','`','bcCaptionText')" title="کد">&lt;/&gt;</button>
                <button type="button" class="btn btn-glass btn-xs" onclick="bcQuote('bcCaptionText')" title="نقل‌قول" style="display:inline-flex;align-items:center;"><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="bcWrap('||','||','bcCaptionText')" title="اسپویلر" style="display:inline-flex;align-items:center;"><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>
            <textarea name="caption" id="bcCaptionText" class="form-control" rows="3" placeholder="توضیحات فایل..." style="font-family:inherit;line-height:1.6;resize:vertical;"></textarea>
            <?= CustomEmoji::webPickerHtml(['bcCaptionText']) ?>
        </div>
        <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="bcToggleMedia()">لغو</button>
    </form>
</div>

<!-- T46-ar: broadcast queue progress -->
<?php
$bcJobs = BroadcastEngine::getActiveJobs(10);
$bcStatusFa = ['pending' => 'در صف', 'running' => 'در حال ارسال', 'done' => 'تکمیل شد', 'failed' => 'متوقف شد'];
?>
<?php if (!empty($bcJobs)): ?>
<div class="glass-card" style="margin-top:24px;border-left:4px solid var(--primary);">
    <div class="card-title" style="margin-bottom:16px;">صف ارسال همگانی</div>
    <div class="table-container">
        <table>
            <thead><tr><th>#</th><th>عملیات</th><th>وضعیت</th><th>پیشرفت</th><th>موفق</th><th>ناموفق</th></tr></thead>
            <tbody>
            <?php foreach ($bcJobs as $job): ?>
                <tr>
                    <td>#<?= (int)$job['id'] ?></td>
                    <td><?= $job['op'] === 'delete' ? 'حذف از تلگرام' : 'ارسال پیام' ?></td>
                    <td><?= e($bcStatusFa[(string)$job['status']] ?? (string)$job['status']) ?></td>
                    <td><?= (int)$job['cursor'] ?> / <?= (int)$job['total_count'] ?></td>
                    <td><?= (int)$job['sent_count'] ?></td>
                    <td><?= (int)$job['failed_count'] ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Sent broadcasts list -->
<div class="glass-card" style="margin-top:24px;">
    <div class="card-title" style="margin-bottom:16px;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="M15 12h-5"/><path d="M15 8h-5"/><path d="M19 17V5a2 2 0 0 0-2-2H4"/><path d="M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3"/></svg> پیام‌های همگانی ارسال‌شده (<?= count($broadcasts) ?>)</div>
    <?php if (empty($broadcasts)): ?>
        <div class="empty-state"><div class="empty-icon"><svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-6l-2 3h-4l-2-3H2"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg></div><div class="empty-text">پیامی ارسال نشده</div></div>
    <?php else: ?>
        <div class="table-container">
            <table>
                <thead><tr><th>#</th><th>متن/کپشن</th><th>نوع</th><th>ارسال‌کننده</th><th>تعداد ارسال</th><th>زمان</th><th>عملیات</th></tr></thead>
                <tbody>
                    <?php foreach ($broadcasts as $b): ?>
                    <tr>
                        <td>#<?= $b['id'] ?></td>
                        <td style="font-size:13px;"><div style="max-width:300px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?= e(mb_substr($b['text'], 0, 80)) ?><?= mb_strlen($b['text']) > 80 ? '...' : '' ?></div></td><!-- T46-r: ellipsis moved to inner div — max-width on <td> is ignored in auto table layout -->
                        <td><?= e($b['content_type']) ?></td>
                        <td><?= e($b['admin_name'] ?? '-') ?></td>
                        <td><?= (int)$b['total_sent'] ?></td>
                        <td style="font-size:12px;color:var(--text-muted);"><?= e($b['created_at']) ?></td>
                        <td>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('حذف پیام همگانی؟ این پیام از تلگرام تمام کاربران حذف خواهد شد.')">
            <?= csrf_field() ?>
                                <input type="hidden" name="action" value="delete_broadcast">
                                <input type="hidden" name="broadcast_id" value="<?= $b['id'] ?>">
                                <button class="btn btn-danger btn-xs" style="display:inline-flex;align-items:center;gap:4px;"><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>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<script>
function bcWrap(open, close, targetId) {
    var ta = document.getElementById(targetId || 'bcMessageText');
    if (!ta) return;
    var start = ta.selectionStart;
    var end = ta.selectionEnd;
    var selected = ta.value.substring(start, end);
    var placeholder = open === '**' ? 'متن پررنگ' : (open === '__' ? 'متن کج' : (open === '`' ? 'کد' : (open === '||' ? 'اسپویلر' : 'متن')));
    var text = selected || placeholder;
    ta.value = ta.value.substring(0, start) + open + text + close + ta.value.substring(end);
    ta.focus();
    ta.setSelectionRange(start + open.length, start + open.length + text.length);
}

function bcQuote(targetId) {
    var ta = document.getElementById(targetId || 'bcMessageText');
    if (!ta) return;
    var start = ta.selectionStart;
    var end = ta.selectionEnd;
    var selected = ta.value.substring(start, end);
    var text = selected || 'متن نقل‌قول';
    var lines = text.split('\n');
    var quoted = lines.map(function(l) { return '> ' + l; }).join('\n');
    ta.value = ta.value.substring(0, start) + quoted + ta.value.substring(end);
    ta.focus();
    ta.setSelectionRange(start + 2, start + 2 + text.length);
}

function bcToggleMedia() {
    var mf = document.getElementById('bcMediaForm');
    var rf = document.getElementById('bcTextForm');
    var toggleBtn = document.getElementById('bcToggleMediaBtn');
    if (mf.style.display === 'none') {
        mf.style.display = 'block';
        rf.style.display = 'none';
        if (toggleBtn) { toggleBtn.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> متن'; toggleBtn.title = 'پیام متنی'; }
    } else {
        mf.style.display = 'none';
        rf.style.display = 'block';
        if (toggleBtn) { toggleBtn.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> فایل'; toggleBtn.title = 'ارسال فایل'; }
    }
}
</script>

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