<?php
require_once("./config/db_config.php");
require_once("./config/functionclass.php");

class donationPayment
{
    public $accessToken;
    private $conn;

    private $connMain;
    private $ClassObject;
    private $nonsec;
    public $logger;
    function __construct($accessToken = '')
    {

        // global $conn;
        $this->ClassObject = new PHPClass();
        $token =  $this->ClassObject->getToken();
        $token = json_decode($token);
        $this->accessToken = isset($token->access_token) ? $token->access_token : '';
        $this->nonsec = isset($token->nonsec) ? $token->nonsec : '';
        // $this->conn = $conn;
    }

    public function setConnection($applyNowConnection, $coreERPConnection)
    {
        $this->conn = $applyNowConnection;
        $this->connMain = $coreERPConnection;
    }

    function createOnlinePaymentId($inputParam)
    {
        $responseVal = '';
        if(isset($inputParam['onlinePaymentId']) > 0 && $inputParam['onlinePaymentId'] != "" && isset($inputParam['alumniToken']) && isset($inputParam['serverUrl']) && $inputParam['serverUrl'] && isset($inputParam['alumniDonationRangeId']) && $inputParam['alumniDonationRangeId'])
        {
            $authorization = "Authorization: ".$inputParam['alumniToken'];
            $url = $inputParam["serverUrl"] . findAlumniDetailsById . '?onlinePaymentId='. $inputParam['onlinePaymentId'];
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 120);
            curl_setopt(
                $ch,
                CURLOPT_HTTPHEADER,
                array(
                     $authorization,
                )
            );
            $resultcurl = curl_exec($ch);
            $responceERP2 = json_decode($resultcurl);

            if(isset($responceERP2->amount) && $responceERP2->amount && $responceERP2->amount > 0)
            {
                $name = $responceERP2->name ? $responceERP2->name : '';
                $email = $responceERP2->email ? $responceERP2->email : '';
                $address = $responceERP2->address ? $responceERP2->address : '';
                $phoneNo = $responceERP2->phoneNo ? $responceERP2->phoneNo : '';
                $amount = $responceERP2->amount ? $responceERP2->amount : '';
                $currency = $responceERP2->currency ? $responceERP2->currency : '';
                $academyLocation = $responceERP2->academyLocation ? $responceERP2->academyLocation : '';
                $redirectUrl = $inputParam["redirectURL"];
                $serverUrl = $inputParam["serverUrl"];
                $alumniDonationRangeId = $inputParam["alumniDonationRangeId"];
                try {
                    $query = "INSERT INTO donation_payment (onlinePaymentId, txnId, paymentStatus, paymentDate, receiptStatus, amount,name,email,address,phoneNo,academyLocationId,currency,redirectURL,alumniToken, serverUrl, alumniDonationRangeId) VALUES ('" . $inputParam['onlinePaymentId'] . "','','initiate', '".date('Y-m-d H:i:s')."'  ,''," . $amount . ",'" . $name . "','" . $email . "','".$address."','" . $phoneNo . "','" . $academyLocation . "','" . $currency . "','".$redirectUrl."' ,'".$inputParam['alumniToken']."', '".$inputParam['serverUrl']."', '".$alumniDonationRangeId."')";
                    $insert = mysqli_query($this->conn, $query);
                    $paymentId = mysqli_insert_id($this->conn);
                    $responceVal = $paymentId;
                } catch (Exception $e) {
                    $responceVal = "QUERY_ERROR";
                }
            }
            else
            {
                $responceVal = "AMOUNT_ISSUE";
            }
        }
        else
        {
            $responceVal = "INVALID_PARAM";
        }
        return $responceVal;

    }

    function getStandardMerchantDetailsByAl($gatewayName , $academyLocationId, $currencyCode = '') {
        if(!$this->accessToken)
        {
             return "ACCESS_TOKEN";
        }
        else
        {
            $authorization = "Authorization: Bearer " . $this->accessToken;
            $params = 'qry='.$gatewayName.'&academyLocationId=' . $academyLocationId.'&currencyCode='.$currencyCode;
            $url = baseURL . getStandardMerchantDetails . '?'.$params;
            
            $options = array(
                'public_key' => isset($this->nonsec)?$this->nonsec:'',
                'params' => $params,
                'jsonData' => '',
                'access_token' => isset($this->accessToken)?$this->accessToken:'',
            );
            $nonce = $this->ClassObject->secMe($options);
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 120);
            curl_setopt(
                $ch,
                CURLOPT_HTTPHEADER,
                array(
                    'Content-Type: application/json',
                    $authorization,
                    'nonce:' .$nonce
                )
            );

            $resultcurl = curl_exec($ch);
            $responceERPGateway = json_decode($resultcurl, true);
            $responceERPGateway = array_change_key_case($responceERPGateway, CASE_LOWER); 
            if($responceERPGateway && count($responceERPGateway) > 0 && !empty($responceERPGateway[$gatewayName]))
            {
                return $responceERPGateway;
            }
            else
            {
                return 'No_DATA';
            }
        }
    }

    function createReceipt($donationInfo ,$orderStatus)
    {
        $onlinePaymentId = $donationInfo['onlinePaymentId'];
        $txnId = $donationInfo['txnId'];
        $alumniToken =  $donationInfo['alumniToken'];
        $authorization = "Authorization: ".$alumniToken;
        $responseVal = '';
        $selectInstumentCount = 0;
        $alumniDonationRangeId = $donationInfo['alumniDonationRangeId'];
        if($txnId && !is_null($txnId))
        {
            $receiptInstrumentQuery = "SELECT * FROM receipt_payment_instrument where instrumentNo = '".$txnId."'";
            $selectInstument = mysqli_query($this->connMain, $receiptInstrumentQuery);
            $selectInstumentCount = mysqli_num_rows($selectInstument);
        }
        if($selectInstumentCount == 0)
        {
            $donationJSON = '{"id":"'.$onlinePaymentId.'","paymentGateway":"'.$donationInfo['paymentOption'].'","transactionId":"'.$txnId.'","paymentDate":"'.$donationInfo['paymentDate'].'","paymentStatus":"'.$orderStatus.'","alumniDonationRangeId":"'.$alumniDonationRangeId.'"}';

            $ch = curl_init($donationInfo['serverUrl'] . createAlumniReceipt);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $donationJSON);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 120);
            curl_setopt(
                $ch,
                CURLOPT_HTTPHEADER,
                array(
                    'Content-Type: application/json',
                    $authorization,
                )
            );
            $resultcurl = curl_exec($ch);
            $responceERP2 = json_decode($resultcurl);
            $errorDebug = '{"response": "'.$resultcurl.'","donationJSON": "'.$donationJSON.'","url": "'.$donationInfo['serverUrl'] . createAlumniReceipt.'", "authorization": "'.$authorization.'"}';
            Logger::debug("Generated JSON for payment update: " . $errorDebug);
            if($responceERP2 && isset($responceERP2->receiptStatus) && ($responceERP2->receiptStatus == 'SUCCESS' || $responceERP2->receiptStatus == 'success'))
            {
                return "SUCCESS";
            }
            else
            {
                return "RECEIPT_NOT_GENERATE";
            }
        }
        else
        {
            return "RECEIPT_ALREADY_GENERATE";
        }
    }
}