<?php

namespace twa\omnipay\controllers;

use twa\omnipay\repositories\nusoap;
use SoapClient;

class GlobalPayController
{
    public $data;

    public $provider;

    public function __construct($data, $provider)
    {
        $this->provider = $provider;

        $required_data = ['MERCHANTID', 'USERNAME', 'PASSWORD'];
        \twa\omnipay\controllers\GeneralFunctions::checkRequiredData($data, $required_data);

        $this->data = collect([
            'MERCHANTID' => $data['MERCHANTID'],
            'USERNAME' => $data['USERNAME'],
            'PASSWORD' => $data['PASSWORD'],
        ]);
        $this->data = collect($data);
    }

    public function createPayment($id, $value, $currency, $customer_name = null, $customer_email = null, $url_success = null, $url_cancel = null)
    {
        return collect(['redirect' => ['link' => env('APP_URL').'/omnipay/redirect/globalpay/'.$id.'/'.$this->provider.'/'.$value.'/'.$currency.'/'.md5($id.$this->provider.$value.$currency.env('APP_KEY')).'?lang='.app()->getLocale()]]);
    }

    public function checkPayment($id)
    {
        
        $soapClient = new SoapClient('https://www.globalpay.com.ng/globalpaywebservice/service.asmx?wsdl');
        $params = array(
            'merch_txnref' => $id,
            'channel' => "",
            'merchantID' => $this->data['MERCHANTID'],
            'start_date' => "",
            'end_date' => "",
            'uid' => $this->data['USERNAME'],
            'pwd' => $this->data['PASSWORD'],
            'payment_status' => ""
        );
        try {
            $call = $soapClient->getTransactions($params);
            $xml = collect(json_decode(json_encode(simplexml_load_string($call->getTransactionsResult)), 1));
        }catch (\Throwable $e) {
            return response(['status' => 'fail', 'response' => ''], 400);
        }
        if(isset($xml['record']['payment_status']) && strtolower($xml['record']['payment_status']) == "successful"){
            return response(['status' => 'success', 'response' => $xml['record']], 200);
        }
        return response(['status' => 'fail', 'response' => $xml ], 400);

    }
}
