<?php
declare(strict_types=1);

class Pasarguard {
    /**
     * ورود به پنل پاسارگاد و دریافت access_token ادمین
     */
    public static function getToken(string $panelUrl, string $username, string $password): ?string {
        $baseUrl = rtrim($panelUrl, '/');
        $endpoints = [
            '/api/admin/token',
            '/api/v1/admin/token',
            '/api/v1/auth/token'
        ];

        foreach ($endpoints as $endpoint) {
            $ch = curl_init($baseUrl . $endpoint);
            curl_setopt_array($ch, [
                CURLOPT_POST           => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POSTFIELDS     => http_build_query([
                    'username'   => $username,
                    'password'   => $password,
                    'grant_type' => 'password'
                ]),
                CURLOPT_HTTPHEADER     => [
                    'Content-Type: application/x-www-form-urlencoded',
                    'Accept: application/json'
                ],
                CURLOPT_TIMEOUT        => 8,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false
            ]);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode === 200 && $response) {
                $json = json_decode((string)$response, true);
                if (!empty($json['access_token'])) {
                    return (string)$json['access_token'];
                }
            }
        }
        return null;
    }

    /**
     * دریافت حجم کل ترافیک مصرفی یک نود (به بایت) از پاسارگاد
     * مجموع آپلود و دانلود یا فیلد کل ترافیک
     */
    public static function getNodeTrafficBytes(string $panelUrl, string $token, string $nodeIp): ?int {
        $baseUrl = rtrim($panelUrl, '/');
        $endpoints = [
            '/api/nodes',
            '/api/v1/nodes',
            '/api/admin/nodes'
        ];

        $isApiKey = str_starts_with($token, 'pg_key_');

        foreach ($endpoints as $endpoint) {
            $ch = curl_init($baseUrl . $endpoint);
            $headers = ['Accept: application/json'];
            
            if ($isApiKey) {
                $headers[] = "X-Api-Key: {$token}";
            } else {
                $headers[] = "Authorization: Bearer {$token}";
            }

            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER     => $headers,
                CURLOPT_TIMEOUT        => 8,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false
            ]);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode === 200 && $response) {
                $data = json_decode((string)$response, true);
                $nodes = $data['nodes'] ?? $data['result'] ?? (is_array($data) ? $data : []);

                if (is_array($nodes)) {
                    foreach ($nodes as $node) {
                        $ip = $node['address'] ?? $node['ip'] ?? $node['hostname'] ?? '';
                        if (trim((string)$ip) === trim($nodeIp)) {
                            $up = (int)($node['uplink'] ?? $node['bytes_sent'] ?? $node['traffic_up'] ?? 0);
                            $down = (int)($node['downlink'] ?? $node['bytes_received'] ?? $node['traffic_down'] ?? 0);
                            $total = (int)($node['usage'] ?? $node['used_traffic'] ?? ($up + $down));

                            return $total > 0 ? $total : ($up + $down);
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * تست مستقیم سلامت نود از طریق اندپوینت سرویس نود (/info)
     */
    public static function checkNodeStatusByApi(string $nodeIp, int $nodePort = 62050, ?string $apiToken = null, int $timeout = 4): bool {
        $endpoints = [
            "/info",
            "/api/v1/node/info",
            "/api/node/info"
        ];
        $protocols = ['http', 'https'];

        foreach ($protocols as $proto) {
            foreach ($endpoints as $endpoint) {
                $url = "{$proto}://{$nodeIp}:{$nodePort}{$endpoint}";
                $ch = curl_init($url);
                $headers = [
                    'Accept: application/json',
                    'User-Agent: PasarGuard-Failover-Bot'
                ];

                if (!empty($apiToken)) {
                    $headers[] = "Authorization: Bearer {$apiToken}";
                    $headers[] = "X-Api-Key: {$apiToken}";
                }

                curl_setopt_array($ch, [
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_HTTPHEADER     => $headers,
                    CURLOPT_CONNECTTIMEOUT => $timeout,
                    CURLOPT_TIMEOUT        => $timeout,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_SSL_VERIFYHOST => false
                ]);

                $response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                $curlError = curl_errno($ch);
                curl_close($ch);

                if ($curlError === 0 && $httpCode === 200 && $response) {
                    $json = json_decode((string)$response, true);
                    if (is_array($json)) {
                        $status = strtolower((string)($json['status'] ?? $json['state'] ?? 'running'));
                        if ($status === 'stopped' || $status === 'error' || $status === 'failed') {
                            return false;
                        }
                        return true;
                    }
                    return true;
                }
            }
        }
        return false;
    }
}