<?php

// namespace PaymentGateways\Network;

// use PaymentGateways\PaymentGatewayInterface;
require_once "./config/db_config.php";

class NetworkGateway {
    private $tokenUrl = 'identity/auth/access-token';
    private $orderUrl = 'transactions/outlets/';
    private $accessToken;
    public $domainURL;

    public function __construct()
    {
        $this->domainURL = domainURL;
    }
    public function getAccessToken($authApiKey, $environment) {
        if ($this->accessToken) {
            return $this->accessToken;
        }

        $headers = [
            'accept: application/vnd.ni-identity.v1+json',
            'content-type: application/vnd.ni-identity.v1+json',
            'Authorization: Basic '.$authApiKey,
            'Content-Length:' .strlen('')
        ];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL =>  $environment.$this->tokenUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => $headers,
        ]);

        $response = curl_exec($curl);
        curl_close($curl);

        $this->accessToken = json_decode($response, true)['access_token'] ?? null;
        return $this->accessToken;
    }

    public function createOrder($data) {
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $authApiKey = $gatewayJson['authApiKey'];
        $environment = $gatewayJson['environment'];
        $outletId = $gatewayJson['outletId'];
        $accessToken = $this->getAccessToken($authApiKey, $environment);

        $firstName = '';
        $lastName = '';
        $nameArr = [];
        if(isset($data['name'])){
            $nameArr = explode(' ', trim($data['name']));
        }
        if (count($nameArr)) {
            $firstName = $nameArr[0];
        }
        if (count($nameArr) > 1) {
            $lastName = implode(' ', array_slice($nameArr, 1));
        }
        $payload = [
            "action" => "SALE",
            "amount" => [
                "currencyCode" => $data['currency'],
                "value" => $data['amount'] * 100
            ],
            "emailAddress" => isset($data['email']) ? $data['email'] : "",
            "billingAddress" => [
                "firstName" => $firstName,
                "lastName" => $lastName
            ],
        ];        
        
        if ($data['paymentType'] == 'mobile') {
            $payload["merchantAttributes"] = [
                "redirectUrl" => $this->domainURL . '/mobile-payment',
            ];
        }
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $environment.$this->orderUrl.$outletId."/orders",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => [
                'Accept: application/vnd.ni-payment.v2+json',
                'Content-Type: application/vnd.ni-payment.v2+json',
                "Authorization: Bearer {$accessToken}",
            ],
        ]);

        $response = curl_exec($curl);
        curl_close($curl);

        return json_decode($response, true);
    }

    public function fetchOrder($data) {
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $authApiKey = $gatewayJson['authApiKey'];
        $environment = $gatewayJson['environment'];
        $outletId = $gatewayJson['outletId'];
        $accessToken = $this->getAccessToken($authApiKey, $environment);
        $url = $environment.$this->orderUrl.$outletId."/orders/".$data['txnId'];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => [
                'Accept: application/vnd.ni-payment.v2+json',
                'Content-Type: application/vnd.ni-payment.v2+json',
                "Authorization: Bearer {$accessToken}",
            ],
        ]);

        $response = curl_exec($curl);
        curl_close($curl);

        $paymentResponce = json_decode($response, true);
        $result = array(
            'reference' => $data['txnId'],
            'status' => '',
            'success' => false
        );
        if(isset($paymentResponce['_embedded']['payment']))
        {
            $len = count($paymentResponce['_embedded']['payment']);
            if(isset($paymentResponce['_embedded']['payment'][$len-1]['state']))
            {
                $result = array(
                    'reference' => $paymentResponce['reference'],
                    'status' => $paymentResponce['_embedded']['payment'][$len-1]['state'],
                    'success' => true
                );
            }
        }
        return $result;
    }
}
