<?php

namespace CoinPaymentsApiExamples\Helpers;

class ApiHelper
{
    // ✅ FIXED API URL (VERY IMPORTANT)
    const API_URL = 'https://a-api.coinpayments.net';

    private $clientId;
    private $clientSecret;

    public function __construct(string $clientId, string $clientSecret)
    {
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;
    }

    public function sendApiRequest(string $method, string $endpoint, array $payload = []): array
    {
        $payloadJson = !empty($payload) ? json_encode($payload) : '';
        $apiUrl = self::API_URL . $endpoint;

        $headers = $this->buildHeaders($method, $apiUrl, $payloadJson);
    
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);

        if (!empty($payloadJson)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadJson);
        }

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // you can enable in production

        $response = curl_exec($ch);

        if ($response === false) {
            return [
                'error' => curl_error($ch)
            ];
        }

        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        $decoded = json_decode($response, true);

        if ($decoded !== null) {
            return $decoded;
        }

        return [
            'status_code' => $statusCode,
            'raw' => $response
        ];
    }

   public function calculateSignature(string $method, string $url, string $payload, string $date): string
{
    $message = "\xEF\xBB\xBF" . strtoupper($method) . $url . $this->clientId . $date . $payload;

    return base64_encode(
        hash_hmac('sha256', $message, $this->clientSecret, true)
    );
}

   private function buildHeaders(string $method, string $url, string $payload): array
{
    // ✅ IMPORTANT: exact format
    $date = gmdate('Y-m-d\TH:i:s'); // force UTC Z format

    $signature = $this->calculateSignature($method, $url, $payload, $date);

    return [
        'Content-Type: application/json',
        'X-CoinPayments-Client: ' . $this->clientId,
        'X-CoinPayments-Timestamp: ' . $date,
        'X-CoinPayments-Signature: ' . $signature,
    ];
}
}