<?php

namespace App\Services\Gateway\UddoktaPay;

use Exception;

class UddoktaPay
{
    private $apiKey;
    private $apiBaseURL;

    public function __construct($apiKey, $apiBaseURL)
    {
        $this->apiKey = $apiKey;
        $this->apiBaseURL = $apiBaseURL;
    }

    public function initPayment($requestData)
    {
        $apiUrl = $this->apiBaseURL . '/api/payment/create'; // Ensure /api is correct
        // Original logic checked for /api in URL. Assuming clean URL here.

        $response = $this->sendRequest('POST', $apiUrl, $requestData);

        if (!isset($response['payment_url'])) {
            throw new Exception($response['message'] ?? 'Payment initiation failed');
        }
        return $response['payment_url'];
    }

    public function verifyPayment($invoiceId)
    {
        $verifyUrl = $this->apiBaseURL . '/api/payment/verify';
        $requestData = ['transaction_id' => $invoiceId];
        return $this->sendRequest('POST', $verifyUrl, $requestData);
    }

    private function sendRequest($method, $url, $data)
    {
        $headers = [
            'API-KEY: ' . $this->apiKey,
            'Content-Type: application/json',
            'Accept: application/json'
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Disable SSL verification for localhost/dev if needed (not recommended for prod)
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            throw new Exception("cURL Error: $error");
        }

        return json_decode($response, true);
    }
}
