<?php
// #M - Força check imediato de um IP monitorado pelo usuário autenticado
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Método não permitido']);
    exit;
}

if (!csrf_check($_POST['csrf_token'] ?? null)) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'CSRF inválido']);
    exit;
}

if (!rate_limit_check('check_now_' . $user['id'], 15)) {
    http_response_code(429);
    echo json_encode(['success' => false, 'error' => 'Aguarde 15s antes de checar novamente.']);
    exit;
}

$pdo = db();
$ipId = isset($_POST['ip_id']) ? (int)$_POST['ip_id'] : 0;

$stmt = $pdo->prepare("SELECT * FROM monitored_ips WHERE id = ? AND user_id = ?");
$stmt->execute([$ipId, $user['id']]);
$ipRow = $stmt->fetch();

if (!$ipRow) {
    http_response_code(404);
    echo json_encode(['success' => false, 'error' => 'IP não encontrado']);
    exit;
}

$result  = ping_host($ipRow['host'], (int)$ipRow['timeout_ms'], $ipRow['check_method'] ?? 'auto');
$status  = $result['status'];
$latency = $result['latency_ms'];

$pdo->prepare("INSERT INTO ping_logs (monitored_ip_id, status, latency_ms, checked_at) VALUES (?, ?, ?, NOW())")
    ->execute([$ipRow['id'], $status, $latency]);

$pdo->prepare("UPDATE monitored_ips SET last_status = ?, last_latency_ms = ?, last_check_at = NOW() WHERE id = ?")
    ->execute([$status, $latency, $ipRow['id']]);

$tz = new DateTimeZone($user['timezone'] ?? 'America/Sao_Paulo');
$now = (new DateTimeImmutable('now'))->setTimezone($tz)->format('d/m/Y H:i:s');

echo json_encode([
    'success'    => true,
    'status'     => $status,
    'latency_ms' => $latency,
    'checked_at' => $now,
]);
exit;
