<?php
/**
 * پردازش صف پیام همگانی
 * اجرای cron: * * * * * php /path/to/pourrajabi/queue.php
 */

function processBroadcastQueue($bot, $db, $batchSize = 25)
{
    $sql = "SELECT * FROM broadcast_queue WHERE status = 'pending' ORDER BY id ASC LIMIT " . intval($batchSize);
    $stmt = $db->conn->prepare($sql);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $items = $stmt->fetchAll();

    foreach ($items as $item) {
        $result = $bot->copyMessage(
            $item['target_chat_id'],
            $item['from_chat_id'],
            $item['message_id']
        );

        if (is_numeric($result)) {
            $updateSql = "UPDATE broadcast_queue SET status = 'sent', sent_at = '" . time() . "' WHERE id = '" . $item['id'] . "'";
        } else {
            $updateSql = "UPDATE broadcast_queue SET status = 'failed', sent_at = '" . time() . "' WHERE id = '" . $item['id'] . "'";
        }
        $db->conn->exec($updateSql);

        usleep(50000);
    }

    return count($items);
}

if (php_sapi_name() === 'cli' || (isset($_SERVER['SCRIPT_FILENAME']) && realpath(__FILE__) === realpath($_SERVER['SCRIPT_FILENAME']))) {
    ini_set('display_errors', '0');
    include('class/bot.php');
    include('class/db.php');

    $token = '8829690343:AAE1F7b2R7ABJ7mvXOmqHcXPUPDEEs7e_sY';
    $bot = new bot($token, '');
    $db = new db();

    $processed = processBroadcastQueue($bot, $db);
    echo "Processed $processed queue items\n";
}
