<?php
declare(strict_types=1);
require_once __DIR__.'/../bootstrap.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    exit(json_encode(['ok'=>false,'error'=>'GET required']));
}

RBAC::enforce('view.security');

if (!defined('C1O2N3S4T5A6N7T8')) define('C1O2N3S4T5A6N7T8', true);
require_once PRIVATE_DIR.'/p1a2y3m4_bridge.php';
require_once DASHBOARD_ROOT.'/core/payment_client.php';

try {
    $engineData = p1a2y3m4_query('ping', []);
    $reachable = !empty($engineData['ok']);
    $nodeRow = Database::fetchOne("SELECT last_heartbeat, metrics, engine_version, status FROM nodes WHERE node_id = '669427' LIMIT 1");
    $metrics = $nodeRow ? json_decode($nodeRow['metrics'] ?? '{}', true) : [];
    if ($reachable) {
        $engine = [
            'running'=>true,
            'uptime'=>$metrics['uptime'] ?? null,
            'last_heartbeat'=>$nodeRow['last_heartbeat'] ?? null,
            'blacklist_count'=>(int)($metrics['blacklist_count'] ?? 0),
            'ddos_active'=>!empty($metrics['ddos_active']),
            'watchdog_files'=>(int)($metrics['watchdog_files'] ?? 0),
            'dns_failover_mode'=>$metrics['dns_failover_mode'] ?? 'normal',
            'version'=>$nodeRow['engine_version'] ?? null,
        ];
    } else {
        $engine = ['running'=>false,'error'=>'unreachable'];
    }
} catch (\Throwable $ex) {
    $engine = ['running'=>false,'error'=>'unreachable'];
}

$payment = ['configured'=>false,'connected'=>false,'latency_ms'=>null];
try {
    $payment['configured'] = PaymentServerClient::isConfigured();
    if ($payment['configured']) {
        $t0 = hrtime(true);
        $pResult = PaymentServerClient::call('health.ping', []);
        $t1 = hrtime(true);
        $payment['connected'] = !empty($pResult['ok']);
        $payment['latency_ms'] = round(($t1 - $t0) / 1e6, 1);
    }
} catch (\Throwable $ex) {
    $payment['connected'] = false;
}

echo json_encode(['ok'=>true,'engine'=>$engine,'payment'=>$payment]);