<?php declare(strict_types=1);
if (!defined('DASHBOARD_ROOT')) { http_response_code(403); exit; }

class PaymentServerClient {
    private static string $endpoint = '';
    private static string $hmacKey = '';
    private static bool $loaded = false;

    private static function loadKeys(): void {
        if (self::$loaded) return;
        $privateDir = defined('PRIVATE_DIR') ? PRIVATE_DIR : dirname(__DIR__, 2) . '/private';
        $envFile = $privateDir . '/.env';
        if (!file_exists($envFile)) { self::$loaded = true; return; }
        $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            if ($line === '' || $line[0] === '#') continue;
            $parts = explode('=', $line, 2);
            if (count($parts) !== 2) continue;
            $k = trim($parts[0]); $v = trim($parts[1]);
            if ($k === 'payment_node_url') self::$endpoint = $v;
            if ($k === 'bridge_hmac') self::$hmacKey = $v;
        }
        self::$loaded = true;
    }

    public static function isConfigured(): bool {
        self::loadKeys();
        return self::$endpoint !== '' && self::$hmacKey !== '';
    }

    private static function sign(string $body): array {
        $ts = (string)time();
        $nonce = bin2hex(random_bytes(16));
        $sig = hash_hmac('sha256', "{$ts}.{$nonce}.{$body}", self::$hmacKey);
        return ['sig' => $sig, 'ts' => $ts, 'nonce' => $nonce];
    }

    public static function call(string $path, array $payload = []): array {
        self::loadKeys();
        if (!self::isConfigured()) return ['ok' => false, 'error' => 'Payment server not configured'];

        try {
            $body = json_encode($payload);
            $signed = self::sign($body);

            $ch = curl_init(self::$endpoint . $path);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $body,
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'X-Bridge-Sig: ' . $signed['sig'],
                    'X-Bridge-Ts: ' . $signed['ts'],
                    'X-Bridge-Nonce: ' . $signed['nonce'],
                ],
                CURLOPT_TIMEOUT => 15,
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_SSL_VERIFYHOST => 2,
            ]);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $err = curl_error($ch);
            curl_close($ch);

            if ($err || !$response) return ['ok' => false, 'error' => $err ?: 'Empty response'];
            if ($httpCode !== 200) return ['ok' => false, 'error' => 'HTTP ' . $httpCode];

            $result = json_decode($response, true);
            return is_array($result) ? $result : ['ok' => false, 'error' => 'JSON parse failed'];
        } catch (\Throwable $e) {
            return ['ok' => false, 'error' => 'Exception: ' . $e->getMessage()];
        }
    }

    // Payment processing
    public static function processPayment(array $order): array {
        return self::call('/api/process', $order);
    }

    // Payment status
    public static function getStatus(array $query): array {
        return self::call('/api/status', $query);
    }

    // Wallet check
    public static function getWalletStatus(string $coin): array {
        return self::call('/api/wallet/' . strtolower($coin), []);
    }

    // Dashboard compatibility methods
    public static function getWallets(): array {
        $result = ['ok' => true, 'data' => []];
        foreach (['xmr', 'usdt', 'usdc'] as $coin) {
            $r = self::getWalletStatus($coin);
            if ($r['ok'] ?? false) $result['data'][] = array_merge($r, ['coin' => strtoupper($coin)]);
        }
        return $result;
    }

    public static function getTransactions(string $currency = '', int $limit = 50): array {
        return self::call('/api/status', ['action' => 'transactions', 'currency' => $currency, 'limit' => $limit]);
    }

    public static function sendCrypto(string $currency, string $to, float $amount): array {
        return self::call('/api/process', ['payment_method' => 'crypto', 'crypto_coin' => $currency, 'to' => $to, 'amount' => $amount]);
    }

    public static function getEtransfers(string $status = 'all', int $limit = 50): array {
        return self::call('/api/status', ['action' => 'etransfers', 'status' => $status, 'limit' => $limit]);
    }

    public static function verifyEtransfer(int $id, int $orderId = 0): array {
        return self::call('/api/process', ['payment_method' => 'etransfer', 'action' => 'verify', 'id' => $id, 'order_id' => $orderId]);
    }

    public static function rejectEtransfer(int $id, string $reason = ''): array {
        return self::call('/api/process', ['payment_method' => 'etransfer', 'action' => 'reject', 'id' => $id, 'reason' => $reason]);
    }

    public static function getLedger(int $page = 1, int $limit = 50): array {
        return self::call('/api/status', ['action' => 'ledger', 'page' => $page, 'limit' => $limit]);
    }

    public static function getTotals(): array {
        return self::call('/api/status', ['action' => 'totals']);
    }

    public static function health(): array {
        self::loadKeys();
        if (!self::isConfigured()) return ['ok' => false, 'error' => 'Not configured'];
        $ch = curl_init(self::$endpoint . '/health');
        curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 5, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2]);
        $r = curl_exec($ch); curl_close($ch);
        $d = json_decode($r ?: '', true);
        return is_array($d) ? $d : ['ok' => false, 'error' => 'Unreachable'];
    }
}
