<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("./config/db_config.php");
require_once("./config/functionclass.php");
class CourseRegistrationPendingPayment{

    public $accessToken;
    private $conn;

    private $connMain;
    private $ClassObject;
    private $nonsec;

    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;
    }

    // private $conn;

    public function setConnection($applyNowConnection, $coreERPConnection) {
        $this->conn = $applyNowConnection;
        $this->connMain = $coreERPConnection;
    }
    function createOnlinePaymentId($inputParam){
       if(!$this->accessToken)
       {
            return "ACCESS_TOKEN";
       }
       else
       {
            $responceVal = '';
            $onlinePaymentIds = isset($inputParam['onlinePaymentIds']) ? $inputParam['onlinePaymentIds'] : '';
            $onlinePaymentIdArr = explode(',', $onlinePaymentIds);
            if(count($onlinePaymentIdArr) > 0 && $onlinePaymentIdArr[0])
            {
                $paymentUniqueId = 0;
                $requestUrl = isset($inputParam['requestUrl']) ? $inputParam['requestUrl'] : '';
                $authorization = "Authorization: Bearer " . $this->accessToken;
                $applicantjson='{"id":"'.$onlinePaymentIdArr[0].'"}';
                $options = array(
                    'public_key' => isset($this->nonsec)?$this->nonsec:'',
                    'params' => '',
                    'jsonData' => $applicantjson,
                    'access_token' => isset($this->accessToken)?$this->accessToken:'',
                );
                $nonce = $this->ClassObject->secMe($options);
                $ch = curl_init(baseURL . fetchRegistrationPortalInfo);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $applicantjson);
                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,
                        'Content-Length: ' . strlen($applicantjson),
                        'nonce:' .$nonce
                    )
                );
                $resultcurl = curl_exec($ch);
                // echo $resultcurl;
                $responceERP2 = json_decode($resultcurl);
                // print_r($responceERP2);
                // if (isset($responceERP2[0]->key)) {
                //     $responceVal = "INVALID_PARAM";
                // }else{
                // }
                if(empty($responceERP2->fullName))
                {
                    $responceERP2->fullName = $responceERP2->firstName.' '.$responceERP2->lastName;
                }
                $currentDateTime = date('Y-m-d H:i:s');
                $academyLocationId = $responceERP2->academyLocationId;
                if(isset($responceERP2->receiptAmount) && $responceERP2->receiptAmount && $responceERP2->receiptAmount > 0)
                {
                    try {
                        $query = 'INSERT INTO course_registration_pending_payment (paymentType, onlinePaymentIds, txnId, paymentStatus, paymentDate, receiptStatus, amount,name,email,studentId,code,phoneNo,mobileNo,cellCountryCode,academyLocationId, requestUrl, currency) VALUES ("Course-Registration-Pending-Payment","' . $onlinePaymentIds . '","","", "' . $currentDateTime . '" ,"",' . $responceERP2->receiptAmount . ',"' . $responceERP2->fullName . '","' . $responceERP2->emailId . '","' . $responceERP2->studentId . '","' . $responceERP2->code . '","' . $responceERP2->phoneNo . '","' . $responceERP2->mobileNo . '","' . $responceERP2->cellCountryCode . '", "' . $academyLocationId . '", "' . $requestUrl . '", "'.$responceERP2->currencyCode.'")';
                        $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(count($responceERPGateway) > 0 && !empty($responceERPGateway[$gatewayName]))
            {
                return $responceERPGateway;
            }
            else
            {
                return 'No_DATA';
            }
        }
    }

    function createReceipt($data) {             
        if(!$this->accessToken)
        {
            return "ACCESS_TOKEN";
        }
        else
        {
            $txnId = $data['txnId'];
            $authorization = "Authorization: Bearer " . $this->accessToken;
            $selectInstumentCount = 0;
            if (!$this->connMain) {
                die("Connection failed: " . mysqli_connect_error());
            }
            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)
            {
                $applicantjson = '{"onlineMasterIds":"'.$data['onlinePaymentIds'].'","txnid":"'.$data['txnId'].'","status":"SUCCESS"}';
                $options = array(
                    'public_key' => isset($this->nonsec)?$this->nonsec:'',
                    'params' => '',
                    'jsonData' => $applicantjson,
                    'access_token' => isset($this->accessToken)?$this->accessToken:'',
                );   
                $nonce = $this->ClassObject->secMe($options);
                $ch = curl_init(baseURL . updateTransactionStatusPayLetter);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

                curl_setopt($ch, CURLOPT_POSTFIELDS, $applicantjson);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 120);
                curl_setopt(
                    $ch,
                    CURLOPT_HTTPHEADER,
                    array(
                        'Content-Type: application/json', $authorization,
                        'Content-Length: ' . strlen($applicantjson),
                        'nonce:' .$nonce
                    )
                );

                $resultcurl = curl_exec($ch);

                $applicantjsonReceipt = '{"ids":"'.$data['onlinePaymentIds'].'"}';
                $options = array(
                    'public_key' => isset($this->nonsec)?$this->nonsec:'',
                    'params' => '',
                    'jsonData' => $applicantjsonReceipt,
                    'access_token' => isset($this->accessToken)?$this->accessToken:'',
                );
                $nonce = $this->ClassObject->secMe($options);

                $ch1 = curl_init(baseURL . createReceiptForPayLetter.'?ids='.$data['onlinePaymentIds']);
                curl_setopt($ch1, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch1, CURLOPT_POSTFIELDS, $applicantjsonReceipt);
                curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, TRUE);
                curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch1, CURLOPT_TIMEOUT, 120);
                curl_setopt(
                    $ch1,
                    CURLOPT_HTTPHEADER,
                    array(
                    'Content-Type: application/json', $authorization,
                    'Content-Length: ' . strlen($applicantjsonReceipt),
                    'nonce:' .$nonce
                    )
                );

                $resultcurl1 = curl_exec($ch1);
                // echo $resultcurl1;
                // echo baseURL . createReceiptForPayLetter.'?ids='.$data['onlinePaymentIds'];
                // echo $applicantjsonReceipt;
                // echo strtolower($resultcurl1);
                if(strtolower($resultcurl1) == 'success')
                {
                    return "SUCCESS";
                }
                else
                {
                    return 'RECEIPT-FAILED';
                }
            }
            else
            {
                return "RECEIPT_ALREADY_GENERATE";
            }
        }
    }

}