<?php
$pageTitle  = 'Broadcast';
$activePage = 'broadcast';

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/../db.php';

$result = null;
$lastMsg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify()) {
    $message = trim($_POST['message'] ?? '');
    if ($message !== '') {
        set_time_limit(300);
        $lastMsg = $message;

        $users  = $pdo->query("SELECT chat_id FROM users")->fetchAll(PDO::FETCH_COLUMN);
        $sent   = 0;
        $failed = 0;
        $blocked = 0;

        foreach ($users as $uid) {
            $url  = "https://api.telegram.org/bot{$config['telegram_token']}/sendMessage";
            $body = http_build_query([
                'chat_id'    => $uid,
                'text'       => "📢 <b>Message from Admin:</b>\n\n{$message}",
                'parse_mode' => 'HTML',
            ]);
            $ctx  = stream_context_create(['http' => [
                'method'  => 'POST',
                'header'  => 'Content-Type: application/x-www-form-urlencoded',
                'content' => $body,
                'timeout' => 10,
            ]]);
            $resp = @file_get_contents($url, false, $ctx);
            if ($resp) {
                $decoded = json_decode($resp, true);
                if ($decoded['ok'] ?? false) {
                    $sent++;
                } else {
                    // 403 = user blocked bot
                    ($decoded['error_code'] ?? 0) === 403 ? $blocked++ : $failed++;
                }
            } else {
                $failed++;
            }
            usleep(50000); // 50 ms between sends
        }

        $result = compact('sent', 'failed', 'blocked');
    }
}

$totalUsers = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();

require_once __DIR__ . '/_header.php';
?>

<div class="page-header">
    <h4 class="fw-bold mb-0">Broadcast Message</h4>
    <p class="text-muted mb-0 mt-1 small">Send a Telegram message to all registered users at once.</p>
</div>

<?php if ($result): ?>
<div class="alert alert-<?= $result['failed'] === 0 ? 'success' : 'warning' ?> alert-dismissible fade show">
    📡 Broadcast complete &mdash;
    ✅ Sent: <b><?= $result['sent'] ?></b> &nbsp;
    🚫 Blocked: <b><?= $result['blocked'] ?></b> &nbsp;
    ❌ Failed: <b><?= $result['failed'] ?></b>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="row g-3">
    <div class="col-lg-7">
        <div class="card table-card">
            <div class="card-header bg-white border-0 pt-3 pb-1">
                <h6 class="fw-semibold mb-0">Compose Message</h6>
            </div>
            <div class="card-body">
                <form method="POST" id="broadcastForm">
                    <input type="hidden" name="_csrf" value="<?= csrf_token() ?>">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">
                            Message
                            <span class="text-muted fw-normal small ms-1">— HTML tags supported: &lt;b&gt;, &lt;i&gt;, &lt;code&gt;, &lt;a href=""&gt;</span>
                        </label>
                        <textarea name="message" id="msgBody" class="form-control" rows="8"
                                  placeholder="Type your message here…" required><?= htmlspecialchars($lastMsg) ?></textarea>
                        <div class="form-text text-end"><span id="charCount">0</span> chars</div>
                    </div>
                    <div class="d-flex gap-2 flex-wrap">
                        <button type="submit" class="btn btn-primary px-4"
                                onclick="return confirm('Send this message to all <?= number_format($totalUsers) ?> users?')">
                            <i class="bi bi-megaphone me-1"></i>Send Broadcast
                        </button>
                        <button type="button" id="previewBtn" class="btn btn-outline-secondary">
                            <i class="bi bi-eye me-1"></i>Preview
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-5 d-flex flex-column gap-3">
        <!-- Preview pane -->
        <div class="card table-card">
            <div class="card-header bg-white border-0 pt-3 pb-1">
                <h6 class="fw-semibold mb-0">Preview</h6>
            </div>
            <div class="card-body">
                <div class="p-3 rounded" style="background:#f0f2f5;min-height:120px;font-size:.875rem;line-height:1.5">
                    <div class="fw-semibold mb-1">📢 <b>Message from Admin:</b></div>
                    <div id="previewBox" class="text-secondary">Your message will appear here…</div>
                </div>
            </div>
        </div>

        <!-- Info card -->
        <div class="card table-card">
            <div class="card-body">
                <div class="d-flex align-items-center gap-2 mb-2">
                    <div class="fs-4 fw-bold text-primary"><?= number_format($totalUsers) ?></div>
                    <div class="text-muted small">registered users will receive this message</div>
                </div>
                <p class="small text-muted mb-0">
                    Large broadcasts (~600 users) take about 30 seconds. Do not refresh the page while sending.
                    Users who blocked the bot are counted separately as <em>Blocked</em>.
                </p>
            </div>
        </div>
    </div>
</div>

<script>
const msgBox     = document.getElementById('msgBody');
const previewBox = document.getElementById('previewBox');
const charCount  = document.getElementById('charCount');

function updatePreview() {
    previewBox.innerHTML = msgBox.value || '<span class="text-muted">Your message will appear here…</span>';
    charCount.textContent = msgBox.value.length;
}

msgBox.addEventListener('input', updatePreview);
document.getElementById('previewBtn').addEventListener('click', updatePreview);
updatePreview();
</script>

<?php require_once __DIR__ . '/_footer.php'; ?>
