<?php
namespace Core;

/**
 * Thin client for the Flutterwave v3 API (hosted checkout). Credentials are
 * configured by the platform admin under Admin > System Settings.
 *
 * We never collect card details ourselves — initializePayment() returns a
 * link to Flutterwave's own hosted checkout page, and the actual charge
 * result is always re-verified server-side via verifyTransaction() rather
 * than trusted from the redirect/webhook payload alone.
 */
class Flutterwave {
    private const BASE_URL = 'https://api.flutterwave.com/v3';

    public static function isConfigured(): bool {
        return self::secretKey() !== '';
    }

    public static function secretKey(): string {
        return (string) getPlatformSetting('flw_secret_key', '');
    }

    public static function publicKey(): string {
        return (string) getPlatformSetting('flw_public_key', '');
    }

    public static function webhookHash(): string {
        return (string) getPlatformSetting('flw_webhook_hash', '');
    }

    /** Create a hosted checkout session. Returns the raw decoded API response. */
    public static function initializePayment(array $payload): array {
        return self::request('POST', '/payments', $payload);
    }

    /** Re-verify a transaction server-side by Flutterwave's transaction id (never trust client params alone). */
    public static function verifyTransaction(string $transactionId): array {
        return self::request('GET', '/transactions/' . rawurlencode($transactionId) . '/verify', null);
    }

    private static function request(string $method, string $path, ?array $body): array {
        $secretKey = self::secretKey();
        if ($secretKey === '') {
            return ['status' => 'error', 'message' => 'Flutterwave is not configured (missing secret key).'];
        }

        $ch = curl_init(self::BASE_URL . $path);
        $options = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST  => $method,
            CURLOPT_HTTPHEADER     => [
                'Authorization: Bearer ' . $secretKey,
                'Content-Type: application/json',
            ],
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_CONNECTTIMEOUT => 5,
        ];
        if ($body !== null) {
            $options[CURLOPT_POSTFIELDS] = json_encode($body);
        }
        curl_setopt_array($ch, $options);

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

        if ($response === false) {
            return ['status' => 'error', 'message' => $error ?: 'Network error contacting the payment gateway.'];
        }

        $decoded = json_decode($response, true);
        if (!is_array($decoded)) {
            return ['status' => 'error', 'message' => 'Unexpected response from the payment gateway.'];
        }

        $decoded['_http_code'] = $httpCode;
        return $decoded;
    }
}
