<?php
define('WIZWIZ_CRON', true);
include_once __DIR__ . '/../config.php';

@ignore_user_abort(true);
@set_time_limit(30);

$activeBroadcast = BroadcastQueueService::getActiveJob($connection) !== null;

if (!$activeBroadcast) {
    $rateLimit = $botState['rateLimit'] ?? 0;
    if (time() > $rateLimit) {
        $rate = json_decode((string) curl_get_file_contents('https://api.pooleno.ir/v1/currency/short-name/trx?type=buy'), true);
        if (is_array($rate)) {
            $botState['USDRate'] = round($rate['priceUsdt'], 2);
            $botState['TRXRate'] = round($rate['priceFiat'] / 10, 2);
        }
        $botState['rateLimit'] = strtotime('+1 hour');

        $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'BOT_STATES'");
        $stmt->execute();
        $isExists = $stmt->get_result();
        $stmt->close();
        $query = $isExists->num_rows > 0
            ? "UPDATE `setting` SET `value` = ? WHERE `type` = 'BOT_STATES'"
            : "INSERT INTO `setting` (`type`, `value`) VALUES ('BOT_STATES', ?)";
        $newData = json_encode($botState);

        $stmt = $connection->prepare($query);
        $stmt->bind_param('s', $newData);
        $stmt->execute();
        $stmt->close();
    }
}

$result = BroadcastQueueService::runWorker($connection);
header('Content-Type: text/plain; charset=utf-8');
echo json_encode($result, JSON_UNESCAPED_UNICODE);
