<?php
/**
 * Send All (Broadcast) Cron Job
 * Run every 1 minute
 */

declare(strict_types=1);

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../Database.php';
require_once __DIR__ . '/../Telegram.php';

set_time_limit(60);

$db = Database::getInstance();
$telegram = Telegram::getInstance();

// Get pending broadcast
$broadcast = $db->fetchOne(
    "SELECT * FROM `sendall` WHERE status = 'pending' OR status = 'processing' ORDER BY id ASC LIMIT 1"
);

if (!$broadcast) {
    echo "No pending broadcasts\n";
    exit;
}

// Update status to processing
if ($broadcast['status'] === 'pending') {
    $db->update('sendall', [
        'status' => 'processing'
    ], 'id = ?', [(int)$broadcast['id']]);
}

$data = json_decode($broadcast['send'], true);
$now = (int)$broadcast['now'];
$target = $data['for'] === 'gp' ? 'groups' : 'members';

// Get total count
$total = $db->query("SELECT COUNT(*) as count FROM `{$target}`")->fetch_assoc()['count'];

// Update total if not set
if ($broadcast['total'] == 0) {
    $db->update('sendall', ['total' => $total], 'id = ?', [(int)$broadcast['id']]);
}

// Get batch of recipients (100 per run)
$limit = min(100, $total - $now);
$recipients = $db->fetchAll(
    "SELECT id FROM `{$target}` LIMIT {$limit} OFFSET {$now}"
);

$sent = 0;
foreach ($recipients as $recipient) {
    try {
        if ($data['send'] === 'forward') {
            $telegram->forwardMessage(
                $recipient['id'],
                $data['chat'],
                (int)$data['msgid']
            );
        } elseif ($data['send'] === 'message') {
            $telegram->sendMessage(
                $recipient['id'],
                $data['caption']
            );
        } elseif ($data['send'] === 'photo') {
            $telegram->sendPhoto(
                $recipient['id'],
                $data['file_id'],
                $data['caption']
            );
        }
        
        $sent++;
        
        // Sleep to avoid rate limit (30 messages per second)
        usleep(35000); // 0.035 second
        
    } catch (Exception $e) {
        // Log error but continue
        error_log("Broadcast error: " . $e->getMessage());
    }
}

// Update progress
$newNow = $now + $sent;

if ($newNow >= $total) {
    // Completed
    $db->update('sendall', [
        'now' => $newNow,
        'status' => 'completed'
    ], 'id = ?', [(int)$broadcast['id']]);
    
    // Notify admin
    $telegram->sendMessage(
        $data['chat'],
        "✅ ارسال همگانی شماره {$broadcast['id']} با موفقیت به پایان رسید!\n\n" .
        "📊 تعداد ارسال: {$newNow} از {$total}"
    );
    
    echo "Broadcast #{$broadcast['id']} completed\n";
} else {
    // Update progress
    $db->update('sendall', [
        'now' => $newNow
    ], 'id = ?', [(int)$broadcast['id']]);
    
    echo "Broadcast #{$broadcast['id']} progress: {$newNow}/{$total}\n";
}
