<?php

namespace Mtc\Plugins\Judopay\Classes;

class JudopayService
{
    private $api_token;
    private $api_secret;
    private $basic_token;
    private $merchant_id;
    private $api_url;

    public function __construct($config)
    {
        $this->api_token = $config['api_token'];
        $this->api_secret = $config['api_secret'];
        $this->basic_token = base64_encode($this->api_token.':'.$this->api_secret);
        $this->merchant_id = $config['merchant_id'];

        if (config('judopay.testmode')) {
            $this->api_url = 'https://api-sandbox.judopay.com';
        } else {
            $this->api_url = 'https://api.judopay.com';
        }
    }

    public function request($endpoint, $method = 'GET', $data = [], $headers = [])
    {
        try {
            $ch = curl_init();
            $url = $this->api_url.$endpoint;

            if (strtolower($method) === 'get') {
                $url .= http_build_query($data);
            }

            curl_setopt_array($ch, array(
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => $method,
                CURLOPT_HTTPHEADER => array_merge([
                    'Content-Type: application/json',
                    'Authorization: Basic '.$this->basic_token,
                    'API-Version: 6.16',
                ], $headers),
            ));

            if (strtolower($method) === 'post') {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }

            $res = json_decode(curl_exec($ch), true);
        } catch (\Exception $e) {
            $res = [
                'error' => $e->getMessage(),
            ];
        }

        return $res;
    }

    public function createSession(\Basket $basket)
    {
        $data = $this->getPaymentSession($basket);
        $res = $this->request('/paymentsession', 'POST', $data);

        $_SESSION["judopay-{$data['yourPaymentReference']}"] = $_SESSION['order_id'] ?? null;

        return [
            'ref' => $res['reference'] ?? 'error',
            'data' => $data,
        ];
    }

    public function createPayment(\Basket $basket, array $data)
    {
        $session = $this->getPaymentSession($basket);

        return $this->request('/transactions/payments/', 'POST', array_merge($session, $data));
    }

    public function getPaymentSession(\Basket $basket)
    {
        return [
            'judoId' => $this->merchant_id,
            'amount' => number_format($basket->cost_total, 2),
            'currency' => 'GBP',
            'yourConsumerReference' => $basket->member,
            'yourPaymentReference' => config('site.tnx_prefix').'-'.$basket->id.'-'.time(),
        ];
    }

    public function createRefund($data)
    {
        return $this->request('/transactions/refunds', 'POST', $data);
    }
}
