<?php
// api/starlink.php — Proxy ke Starlink terminal (gRPC/HTTP local) & Starlink Business API
session_start();
require_once '../includes/config.php';
require_once '../includes/auth.php';
requireAdmin();

header('Content-Type: application/json');

$action   = $_GET['action'] ?? 'status';
$slHost   = getConfig('sl_host', '192.168.100.1');
$slPort   = getConfig('sl_grpc_port', '9200');
$slToken  = getConfig('sl_token', '');

// Starlink terminal menyediakan endpoint HTTP lokal (non-gRPC, via router web UI)
// Business API tersedia di https://api.starlink.com/
function slLocalRequest(string $path): array {
    global $slHost;
    // Starlink router web API (HTTP, bukan HTTPS di LAN)
    $url = "http://{$slHost}{$path}";
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 8,
        CURLOPT_CONNECTTIMEOUT => 4,
    ]);
    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    curl_close($ch);

    if ($err || !$resp) return ['demo' => true];
    $d = json_decode($resp, true);
    return $d ? ['data' => $d] : ['demo' => true];
}

function slBusinessRequest(string $endpoint): array {
    global $slToken;
    if (empty($slToken)) return ['demo' => true];

    $url = "https://api.starlink.com/v1{$endpoint}";
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ["Authorization: Bearer $slToken", 'Accept: application/json'],
        CURLOPT_TIMEOUT => 10,
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code >= 400 || !$resp) return ['demo' => true];
    $d = json_decode($resp, true);
    return $d ? ['data' => $d] : ['demo' => true];
}

function getDemoStarlink(string $action): array {
    $now = time();
    $demos = [
        'status' => [
            'terminal_status'  => 'online',
            'hardware_version' => 'hp1_platform',
            'software_version' => '2024.12.0.dm.7',
            'uptime_seconds'   => 1252800,
            'snr_db'           => 9.2,
            'obstruction_pct'  => 0.0,
            'ping_drop_rate'   => 0.001,
            'pop_ping_latency_ms' => 38,
            'downlink_throughput_bps' => 94200000,
            'uplink_throughput_bps'   => 28700000,
            'tilt_angle_deg'   => 12,
            'board_temp_c'     => 38,
            'dish_temp_c'      => 42,
            'latitude'         => -5.14,
            'longitude'        => 119.43,
            'signal_quality'   => 0.94,
        ],
        'history' => array_map(fn($i) => [
            'timestamp'   => $now - ($i * 7200),
            'downlink'    => round((60 + mt_rand(0,40)) * 1e6),
            'uplink'      => round((15 + mt_rand(0,20)) * 1e6),
            'latency_ms'  => mt_rand(30,80),
            'ping_drop'   => round(mt_rand(0,5) / 1000, 4),
        ], range(0, 11)),
        'alerts' => [
            ['time' => $now - 1400, 'cause' => 'OBSTRUCTED', 'message' => 'Sinyal terhalang sementara — 2m14s'],
        ],
    ];
    return $demos[$action] ?? [];
}

$result = [];
switch ($action) {
    case 'status':
        // Coba endpoint lokal Starlink router dulu
        $r = slLocalRequest('/api/starlink/status');
        if (isset($r['demo'])) {
            // Fallback ke Business API
            $r2 = slBusinessRequest('/devices');
            if (isset($r2['demo'])) {
                $result = ['demo' => true, 'data' => getDemoStarlink('status')];
            } else {
                $result = ['data' => $r2['data']];
            }
        } else {
            $result = ['data' => $r['data']];
        }
        break;

    case 'history':
        $r = slLocalRequest('/api/starlink/history');
        $result = isset($r['demo'])
            ? ['demo' => true, 'data' => getDemoStarlink('history')]
            : ['data' => $r['data']];
        break;

    case 'alerts':
        $r = slLocalRequest('/api/starlink/alerts');
        $result = isset($r['demo'])
            ? ['demo' => true, 'data' => getDemoStarlink('alerts')]
            : ['data' => $r['data']];
        break;

    case 'stow':
        $r = slLocalRequest('/api/starlink/stow');
        writeLog('Starlink: perintah stow dikirim');
        $result = ['success' => !isset($r['demo']), 'demo' => isset($r['demo']),
                   'message' => isset($r['demo']) ? 'Demo mode — stow tidak dieksekusi' : 'Stow berhasil dikirim'];
        break;

    case 'unstow':
        $r = slLocalRequest('/api/starlink/unstow');
        writeLog('Starlink: perintah unstow dikirim');
        $result = ['success' => !isset($r['demo']), 'demo' => isset($r['demo']),
                   'message' => isset($r['demo']) ? 'Demo mode — unstow tidak dieksekusi' : 'Unstow berhasil'];
        break;

    case 'reboot':
        $r = slLocalRequest('/api/starlink/reboot');
        writeLog('Starlink: perintah reboot dikirim', 'warn');
        $result = ['success' => !isset($r['demo']), 'demo' => isset($r['demo']),
                   'message' => 'Reboot terminal dikonfirmasi'];
        break;

    case 'test':
        $r = slLocalRequest('/api/starlink/status');
        $result = [
            'success' => !isset($r['demo']),
            'demo'    => isset($r['demo']),
            'message' => isset($r['demo']) ? "Terminal lokal tidak terjangkau di {$slHost}" : 'Terminal terhubung — data diterima',
        ];
        break;

    default:
        $result = ['error' => 'Unknown action'];
}

echo json_encode($result);
