<?php
/**
 * Browser-Based Broadcast Worker
 * 
 * ULTIMATE FALLBACK: If automatic self-chaining doesn't work on the hosting,
 * the admin can open this page in their browser and leave the tab open.
 * JavaScript will automatically call the broadcast processor every 3 seconds
 * until the broadcast is complete.
 * 
 * Usage: Open in browser: https://yoursite.com/broadcast_worker.php?key=YOUR_CRON_SECRET
 */

require_once __DIR__ . '/vendor/autoload.php';

$config = require __DIR__ . '/config.php';

// Security check
$secret = $config['cron_secret'] ?? null;
$inputKey = $_GET['key'] ?? null;

if ($inputKey !== $secret) {
    http_response_code(403);
    die("Access Denied. Append ?key=YOUR_CRON_SECRET to the URL.");
}

// If this is an AJAX call (from the JavaScript below), process one batch and return JSON
if (isset($_GET['action']) && $_GET['action'] === 'process') {
    header('Content-Type: application/json');
    
    try {
        $db = new Bot\Database($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
        $broadcast = $db->getActiveBroadcast();
        
        if (!$broadcast) {
            echo json_encode(['status' => 'idle', 'message' => 'No active broadcast']);
            exit;
        }
        
        // Try to trigger the broadcast processor
        $siteUrl = $config['site_url'] ?? '';
        if ($siteUrl) {
            $url = rtrim($siteUrl, '/') . '/process_broadcast.php?key=' . urlencode($secret);
            
            // Use cURL to call process_broadcast.php (which handles actual sending)
            if (function_exists('curl_init')) {
                $ch = curl_init();
                curl_setopt_array($ch, [
                    CURLOPT_URL            => $url,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_TIMEOUT        => 25,
                    CURLOPT_CONNECTTIMEOUT => 5,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_SSL_VERIFYHOST => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                ]);
                @curl_exec($ch);
                curl_close($ch);
            } else {
                $ctx = stream_context_create([
                    'http' => ['timeout' => 25, 'ignore_errors' => true],
                    'ssl'  => ['verify_peer' => false, 'verify_peer_name' => false]
                ]);
                @file_get_contents($url, false, $ctx);
            }
        }
        
        // Re-fetch broadcast status after processing
        $db->ensureConnection();
        $broadcast = $db->getBroadcastById($broadcast['id']);
        
        $total = $broadcast['total_targets'] ?? 0;
        $sent = $broadcast['sent_count'] ?? 0;
        $failed = $broadcast['failed_count'] ?? 0;
        $processed = $sent + $failed;
        $progress = $total > 0 ? round($processed / $total * 100) : 0;
        
        echo json_encode([
            'status'   => $broadcast['status'],
            'sent'     => $sent,
            'failed'   => $failed,
            'total'    => $total,
            'progress' => $progress,
        ]);
    } catch (\Throwable $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// === HTML PAGE: Auto-processing broadcast worker ===
$safeKey = htmlspecialchars($inputKey, ENT_QUOTES, 'UTF-8');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Broadcast Worker</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #1a1a2e; color: #e0e0e0; 
            display: flex; justify-content: center; align-items: center;
            min-height: 100vh; padding: 20px;
        }
        .container { 
            background: #16213e; border-radius: 16px; padding: 40px;
            max-width: 500px; width: 100%; box-shadow: 0 8px 32px rgba(0,0,0,0.3);
        }
        h1 { font-size: 24px; margin-bottom: 8px; color: #fff; }
        .subtitle { color: #888; margin-bottom: 30px; font-size: 14px; }
        .progress-container {
            background: #0f3460; border-radius: 12px; height: 28px;
            overflow: hidden; margin: 20px 0;
        }
        .progress-bar {
            height: 100%; background: linear-gradient(90deg, #e94560, #0f3460);
            border-radius: 12px; transition: width 0.5s ease;
            display: flex; align-items: center; justify-content: center;
            font-weight: bold; font-size: 13px; min-width: 40px;
        }
        .stats { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; margin: 20px 0; }
        .stat { background: #0f3460; border-radius: 10px; padding: 16px; text-align: center; }
        .stat-value { font-size: 28px; font-weight: bold; color: #e94560; }
        .stat-label { font-size: 12px; color: #888; margin-top: 4px; }
        .status { 
            padding: 12px 20px; border-radius: 8px; text-align: center;
            font-weight: 600; margin-top: 20px;
        }
        .status.running { background: #1b4332; color: #52b788; }
        .status.completed { background: #1b3a4b; color: #48cae4; }
        .status.idle { background: #3d3522; color: #e9c46a; }
        .status.error { background: #3d2222; color: #e76f51; }
        .log { 
            margin-top: 20px; background: #0a0a1a; border-radius: 8px;
            padding: 12px; font-family: monospace; font-size: 12px;
            max-height: 150px; overflow-y: auto; color: #6c757d;
        }
        .log-entry { margin: 2px 0; }
        .warn { color: #e9c46a; font-size: 13px; margin-top: 16px; text-align: center; }
    </style>
</head>
<body>
    <div class="container">
        <h1>📡 Broadcast Worker</h1>
        <p class="subtitle">Keep this tab open until the broadcast completes</p>
        
        <div class="progress-container">
            <div class="progress-bar" id="progressBar" style="width: 0%">0%</div>
        </div>
        
        <div class="stats">
            <div class="stat">
                <div class="stat-value" id="sent">0</div>
                <div class="stat-label">Sent</div>
            </div>
            <div class="stat">
                <div class="stat-value" id="failed">0</div>
                <div class="stat-label">Failed</div>
            </div>
            <div class="stat">
                <div class="stat-value" id="total">0</div>
                <div class="stat-label">Total</div>
            </div>
        </div>
        
        <div class="status idle" id="statusBox">Initializing...</div>
        
        <div class="log" id="log"></div>
        
        <p class="warn">⚠️ Do not close this tab while broadcast is running</p>
    </div>

    <script>
        const key = <?= json_encode($safeKey) ?>;
        const processUrl = `broadcast_worker.php?key=${encodeURIComponent(key)}&action=process`;
        let running = true;
        let cycles = 0;
        
        function log(msg) {
            const el = document.getElementById('log');
            const time = new Date().toLocaleTimeString();
            el.innerHTML += `<div class="log-entry">[${time}] ${msg}</div>`;
            el.scrollTop = el.scrollHeight;
        }
        
        function updateUI(data) {
            document.getElementById('sent').textContent = data.sent || 0;
            document.getElementById('failed').textContent = data.failed || 0;
            document.getElementById('total').textContent = data.total || 0;
            
            const progress = data.progress || 0;
            const bar = document.getElementById('progressBar');
            bar.style.width = progress + '%';
            bar.textContent = progress + '%';
            
            const box = document.getElementById('statusBox');
            if (data.status === 'completed') {
                box.className = 'status completed';
                box.textContent = '✅ Broadcast Completed!';
                running = false;
            } else if (data.status === 'processing' || data.status === 'pending') {
                box.className = 'status running';
                box.textContent = '🔄 Processing... (' + (data.sent + data.failed) + '/' + data.total + ')';
            } else if (data.status === 'idle') {
                box.className = 'status idle';
                box.textContent = '⏸️ No active broadcast';
                running = false;
            } else if (data.status === 'error') {
                box.className = 'status error';
                box.textContent = '❌ Error: ' + (data.message || 'Unknown');
            }
        }
        
        async function tick() {
            if (!running) return;
            cycles++;
            
            try {
                log(`Cycle #${cycles}: Triggering processor...`);
                const response = await fetch(processUrl);
                const data = await response.json();
                updateUI(data);
                log(`Status: ${data.status} | Sent: ${data.sent}/${data.total}`);
            } catch (err) {
                log(`Error: ${err.message}`);
            }
            
            if (running) {
                // Wait 3 seconds between cycles
                setTimeout(tick, 3000);
            }
        }
        
        // Start after 1 second
        log('Worker started. Waiting for first cycle...');
        setTimeout(tick, 1000);
    </script>
</body>
</html>
