<?php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/license.php';

// Verifica estado do ambiente antes de processar
if (!_mp_env_ready()) { exit(0); }
$_mpst = license_check();
if ($_mpst['status'] === 'blocked') { exit(0); }
unset($_mpst);

$pdo = db();

// #31 Busca id + timeout_ms para ajustar o timeout do curl por IP
$stmt = $pdo->query("
    SELECT mi.id, mi.timeout_ms
    FROM monitored_ips mi
    WHERE mi.active = TRUE
      AND (mi.last_check_at IS NULL OR mi.last_check_at <= (NOW() - mi.interval_seconds * INTERVAL '1 second'))
    LIMIT 1500
");

$ips = $stmt->fetchAll();
if (!$ips) {
    echo "Nenhum IP para checar.\n";
    return;
}

$token = get_system_setting('cron_http_token', CRON_HTTP_TOKEN);

if (php_sapi_name() === 'cli') {
    $baseUrl = getenv('WEB_APP_URL') ?: 'http://app'; 
} else {
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http');
    $baseUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . BASE_URL;
    $baseUrl = rtrim($baseUrl, '/');
}

// DIVIDE EM LOTES DE 100 (Para não esgotar as THREADS / RAM do Apache de uma só vez)
$lotes = array_chunk($ips, 100);
$totalSucesso = 0;

foreach ($lotes as $indexLote => $loteAtual) {
    $mh = curl_multi_init();
    $curl_handles = [];

    foreach ($loteAtual as $ip) {
        $id = $ip['id'];
        $url = $baseUrl . "/ping_worker.php?id={$id}&token={$token}";
        
        // #31 Timeout = tempo do ping + margem de 3s (mínimo 5s)
        $curlTimeout = max(5, (int)ceil(($ip['timeout_ms'] ?? 5000) / 1000) + 3);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $curlTimeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        curl_multi_add_handle($mh, $ch);
        $curl_handles[$id] = $ch;
    }

    $running = null;
    do {
        $status = curl_multi_exec($mh, $running);
        if ($running) {
            curl_multi_select($mh, 1);
        }
    } while ($running && $status == CURLM_OK);

    foreach ($curl_handles as $id => $ch) {
        $response = curl_multi_getcontent($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_multi_remove_handle($mh, $ch);
        
        if ($httpCode >= 200 && $httpCode < 300) {
            $totalSucesso++;
        } else {
            mp_log('ERROR', "Worker falhou", ['id' => $id, 'http_code' => $httpCode, 'response' => substr($response ?? '', 0, 200)]);
        }
    }
    curl_multi_close($mh);
    
    // Pequena pausa (ms) opcional entre lotes para respirar
    usleep(100000); // 0.1 segundo
}

echo "Total processado: " . count($ips) . " | Sucessos: {$totalSucesso}\n";
