<?php
// api/aruba.php — Proxy ke Aruba Instant On Cloud API
session_start();
require_once '../includes/config.php';
require_once '../includes/auth.php';
requireAdmin();

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

$action = $_GET['action'] ?? 'aps';

$clientId     = getConfig('ar_client_id', '');
$clientSecret = getConfig('ar_client_secret', '');
$siteId       = getConfig('ar_site_id', '');
$region       = getConfig('ar_region', 'ap');

// Aruba Instant On OAuth2 token endpoint per region
$tokenUrls = [
    'ap' => 'https://app-apigw.arubainston.com/oauth2/token',
    'us' => 'https://app-apigw.arubainstanton.com/oauth2/token',
    'eu' => 'https://app-apigw.arubainstanton.eu/oauth2/token',
];
$apiUrls = [
    'ap' => 'https://app-apigw.arubainston.com/api/v1',
    'us' => 'https://app-apigw.arubainstanton.com/api/v1',
    'eu' => 'https://app-apigw.arubainstanton.eu/api/v1',
];

$TOKEN_CACHE = BASE_PATH . '/data/aruba_token.json';

function getArubaToken(): ?string {
    global $clientId, $clientSecret, $region, $tokenUrls, $TOKEN_CACHE;

    // Cek cache token
    if (file_exists($TOKEN_CACHE)) {
        $cache = json_decode(file_get_contents($TOKEN_CACHE), true);
        if ($cache && $cache['expires'] > time() + 60) {
            return $cache['token'];
        }
    }

    if (empty($clientId) || empty($clientSecret)) return null;

    $url = $tokenUrls[$region] ?? $tokenUrls['ap'];
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'grant_type'    => 'client_credentials',
            'client_id'     => $clientId,
            'client_secret' => $clientSecret,
        ]),
        CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_TIMEOUT => 10,
    ]);
    $resp = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($resp, true);
    if (!empty($data['access_token'])) {
        file_put_contents($TOKEN_CACHE, json_encode([
            'token'   => $data['access_token'],
            'expires' => time() + ($data['expires_in'] ?? 3600),
        ]));
        return $data['access_token'];
    }
    return null;
}

function arubaRequest(string $endpoint): array {
    global $siteId, $region, $apiUrls;

    $token = getArubaToken();
    if (!$token) {
        return ['demo' => true, 'data' => getDemoArubaData($GLOBALS['action'])];
    }

    $baseUrl = $apiUrls[$region] ?? $apiUrls['ap'];
    $url = $baseUrl . '/sites/' . urlencode($siteId) . $endpoint;

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ["Authorization: Bearer $token", 'Accept: application/json'],
        CURLOPT_TIMEOUT => 10,
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);

    if ($err || $code >= 400) {
        return ['demo' => true, 'data' => getDemoArubaData($GLOBALS['action'])];
    }

    $decoded = json_decode($resp, true);
    return $decoded ? ['data' => $decoded] : ['demo' => true, 'data' => getDemoArubaData($GLOBALS['action'])];
}

function getDemoArubaData(string $action): array {
    $demos = [
        'aps' => [
            'total' => 6, 'online' => 6, 'offline' => 0,
            'devices' => [
                ['name'=>'AP-Anjungan','model'=>'AP22D','ip'=>'192.168.1.11','clients'=>5,'band'=>'5GHz','util_24'=>32,'util_5'=>18,'status'=>'online'],
                ['name'=>'AP-Ruang Mesin','model'=>'AP22','ip'=>'192.168.1.12','clients'=>8,'band'=>'Dual','util_24'=>45,'util_5'=>28,'status'=>'online'],
                ['name'=>'AP-Dek Penumpang','model'=>'AP25','ip'=>'192.168.1.13','clients'=>14,'band'=>'Dual','util_24'=>71,'util_5'=>55,'status'=>'online'],
                ['name'=>'AP-Kamar Kru','model'=>'AP22','ip'=>'192.168.1.14','clients'=>11,'band'=>'2.4GHz','util_24'=>83,'util_5'=>0,'status'=>'warning'],
                ['name'=>'AP-Dek 3','model'=>'AP22D','ip'=>'192.168.1.15','clients'=>3,'band'=>'5GHz','util_24'=>18,'util_5'=>12,'status'=>'online'],
                ['name'=>'AP-Ruang Navigasi','model'=>'AP25','ip'=>'192.168.1.16','clients'=>1,'band'=>'5GHz','util_24'=>9,'util_5'=>5,'status'=>'online'],
            ]
        ],
        'clients' => [
            'total' => 42,
            'by_ssid' => ['Crew-WiFi'=>15,'Ops-WiFi'=>8,'Passenger-WiFi'=>16,'IoT-Net'=>3]
        ],
        'ssids' => [
            ['name'=>'Crew-WiFi','band'=>'Dual','security'=>'WPA3-SAE','clients'=>15,'vlan'=>10,'status'=>'active'],
            ['name'=>'Ops-WiFi','band'=>'5GHz','security'=>'WPA2-Enterprise','clients'=>8,'vlan'=>20,'status'=>'active'],
            ['name'=>'Passenger-WiFi','band'=>'Dual','security'=>'WPA2-PSK + Captive','clients'=>16,'vlan'=>30,'status'=>'active'],
            ['name'=>'IoT-Net','band'=>'2.4GHz','security'=>'WPA2-PSK','clients'=>3,'vlan'=>40,'status'=>'active'],
        ],
    ];
    return $demos[$action] ?? [];
}

$result = [];
switch ($action) {
    case 'aps':
        $r = arubaRequest('/devices');
        $result = isset($r['demo']) ? ['demo' => true, 'data' => $r['data']] : ['data' => $r['data']];
        break;

    case 'clients':
        $r = arubaRequest('/clients');
        $result = isset($r['demo']) ? ['demo' => true, 'data' => $r['data']] : ['data' => $r['data']];
        break;

    case 'ssids':
        $r = arubaRequest('/networks');
        $result = isset($r['demo']) ? ['demo' => true, 'data' => $r['data']] : ['data' => $r['data']];
        break;

    case 'test':
        $token = getArubaToken();
        $result = [
            'success' => $token !== null,
            'demo'    => $token === null,
            'message' => $token ? 'OAuth berhasil — token diterima' : 'Gagal: periksa Client ID & Secret',
        ];
        break;

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

echo json_encode($result);
