<?php
// receiver_status.php
require 'db.php'; // or wherever your DB connection is

$receivers = $pdo->query("SELECT id, tcpport, enabled FROM receivers")->fetchAll(PDO::FETCH_ASSOC);
$response = [];

function getServerIp(): string {
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    if (!$socket) return '127.0.0.1';

    // This IP doesn't need to be reachable — it just helps detect the outbound IP
    socket_connect($socket, '8.8.8.8', 80);

    socket_getsockname($socket, $localIp);
    socket_close($socket);

    return $localIp ?? '127.0.0.1';
}

foreach ($receivers as $r) {
    $status = 'down';

    // Check if the port is open (basic socket check)
    $fp = @fsockopen(getServerIp(), $r['tcpport'], $errno, $errstr, 1);
    if ($fp) {
        fclose($fp);
        $status = 'up';
    }

    $response[] = [
        'id' => $r['id'],
        'status' => $status
    ];
}

header('Content-Type: application/json');
echo json_encode($response);
