<?php
require_once __DIR__ . '/../config.php';

$db = mysqli_connect('localhost', $databaseUser, $databasePass, $databaseName);
if (!$db) {
    exit;
}

// تابع API تلگرام
function SBoOS($method, $datas = []) {
    $url = "https://api.telegram.org/bot" . API_TOKEN . "/" . $method;
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => $datas,
        CURLOPT_TIMEOUT => 10
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

// دریافت پیام در صف ارسال
$send = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM `send` LIMIT 1"));
$usersCount = mysqli_num_rows(mysqli_query($db, "SELECT * FROM `user`"));

if (!$send || !$send['step']) {
    exit;
}

$admin = $send['from'];
$offset = intval($send['user']);
$batchSize = 50;
$delayMicroSeconds = 500000; // 0.5 ثانیه

$users = mysqli_query($db, "SELECT * FROM `user` LIMIT {$batchSize} OFFSET {$offset}");
$sentCount = 0;

while ($row = mysqli_fetch_assoc($users)) {
    $chatId = $row['from_id'];
    $sendText = urldecode($send['text']);

    if ($send['step'] === 'for') {
        $result = SBoOS('forwardMessage', [
            'chat_id' => $chatId,
            'from_chat_id' => $send['from'],
            'message_id' => $sendText,
        ]);
    } else {
        $result = SBoOS('sendMessage', [
            'chat_id' => $chatId,
            'text' => $sendText,
            'disable_web_page_preview' => true,
            'parse_mode' => 'html'
        ]);
    }

    usleep($delayMicroSeconds); // تأخیر بین ارسال‌ها
    $offset++;
    $sentCount++;
}

// بروزرسانی وضعیت ارسال
if ($offset >= $usersCount) {
    SBoOS('sendMessage', [
        'chat_id' => $admin,
        'text' => "☑️ پیام به " . number_format($usersCount) . " کاربر ارسال شد."
    ]);
    $db->query("DELETE FROM `send`");
} else {
    $db->query("UPDATE `send` SET `user` = {$offset}");
}
?>