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

    public $accessToken;
    private $conn;
    private $connMain;
    private $ClassObject;
    private $nonsec;

    function __construct() {
        $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 : '';
    }

    // private $conn;

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

    function createAdvancePaymentId($data) {
        $onlinePaymentId = $data['onlinePaymentId'] ?? '';
        $studentId = $data['studentId'] ?? '';
        $requestUrl = $data['requestUrl'] ?? '';
        if(!$this->accessToken)
        {
             return "ACCESS_TOKEN";
        }
        else
        {

            $authorization = "Authorization: Bearer " . $this->accessToken;
            $params = "onlinePaymentMasterId=".$onlinePaymentId."&studentId=".$studentId;
            $options = array(
                'public_key' => isset($this->nonsec)?$this->nonsec:'',
                'access_token' => isset($this->accessToken)?$this->accessToken:'',
                'params' =>  $params,
                'jsonData' => ''
            );

            $nonce = $this->ClassObject->secMe($options);
            $ch = curl_init(baseURL . advancePaymentDetails."?".$params);
            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);
            $paymentDetails = json_decode($resultcurl, true);
           
            if(isset($paymentDetails['receiptAmount']) && $paymentDetails['receiptAmount'])
            {
                $currency = (isset($paymentDetails['currencyCode']) && $paymentDetails['currencyCode']) ? $paymentDetails['currencyCode'] : '';
                $name = $paymentDetails['fullName'];
                $email = $paymentDetails['emailId'];
                $phoneNo = $paymentDetails['phoneNo'];
                $applicantId = $paymentDetails['applicantId'];
                $code = $paymentDetails['code'];
                $query = "INSERT INTO advance_payment (onlinePaymentId, txnId, paymentStatus, paymentDate, receiptStatus, amount,name,email,phoneNo, applicantId,studentId,code,currency, requestUrl) VALUES ('" .$onlinePaymentId . "','','Initiate', '".date('Y-m-d H:i:s')."' ,''," . $paymentDetails['receiptAmount'] . ",'" . $name . "','" . $email . "','" . $phoneNo . "','" . $applicantId . "','" . $studentId . "','" . $code . "', '" . $currency . "', '" . $requestUrl . "')";
           
                $insert = mysqli_query($this->conn, $query);
                $paymentId = mysqli_insert_id($this->conn);
                return $paymentId;
            }
            else
            {
                return 'No_DATA';
            }
            if(count($responceERPGateway) > 0)
            {
                return $responceERPGateway[0];
            }
            else
            {
                return 'No_DATA';
            }
        }
    }
    function getMerchantDetailsByAl($academyLocationId) {
        if(!$this->accessToken)
        {
             return "ACCESS_TOKEN";
        }
        else
        {
            $params = 'isActive=true&academyLocationIds='.$academyLocationId;
            $options = array(
                'public_key' => isset($this->nonsec)?$this->nonsec:'',
                'access_token' => isset($this->accessToken)?$this->accessToken:'',
                'params' =>  $params,
                'jsonData' => ''
            );
            $nonce = $this->ClassObject->secMe($options);
            $authorization = "Authorization: Bearer " . $this->accessToken;
            $ch = curl_init(baseURL . gatewayDetailsAPI . '?'.$params );
            $authorization = "Authorization: Bearer " . $this->accessToken;
            $url = baseURL . gatewayDetailsAPI . '?'.$params;
            $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);
            if(count($responceERPGateway) > 0)
            {
                return $responceERPGateway[0];
            }
            else
            {
                return 'No_DATA';
            }
        }
    }

    function getStandardMerchantDetailsByAl($gatewayName , $academyLocationId, $currency = '') {
        if(!$this->accessToken)
        {
             return "ACCESS_TOKEN";
        }
        else
        {
            $authorization = "Authorization: Bearer " . $this->accessToken;
            $params = 'qry='.$gatewayName.'&academyLocationId=' . $academyLocationId.'&currencyCode='.$currency;

            $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($orderInfo) {
        if(!$this->accessToken)
        {
            return "ACCESS_TOKEN";
        }
        else
        {
            $authorization = "Authorization: Bearer " . $this->accessToken;
            $selectInstumentCount = 0;
            if($orderInfo['txnId'] && !is_null($orderInfo['txnId']))
            {
                $receiptInstrumentQuery = "SELECT * FROM receipt_payment_instrument where instrumentNo = '".$orderInfo['txnId']."'";
                $selectInstument = mysqli_query($this->connMain, $receiptInstrumentQuery);
                $selectInstumentCount = mysqli_num_rows($selectInstument);
            }

            if($selectInstumentCount == 0)
            {

                $currencyQuery = "SELECT id FROM currency where currencyCode = '".$orderInfo['currency']."'";
                $currencyQuery = mysqli_query($this->connMain, $currencyQuery);
                $currencyData = mysqli_fetch_assoc($currencyQuery);
                $currencyId = isset($currencyData['id']) ? $currencyData['id'] : '1';

                $postdata = json_encode(array(
                    'onlinePaymentmasterId' => $orderInfo['onlinePaymentId'],
                    'receiptAmount' => $orderInfo['amount'],
                    'txnStatus' => $orderInfo['paymentStatus'],
                    'txnid' => $orderInfo['txnId'],
                    'studentId' => $orderInfo['studentId'],
                    'academyLocationId' => $orderInfo['academyLocationId'],
                    'currencyId' => $currencyId
                ));
                $options = array(
                    'public_key' => isset($this->nonsec)?$this->nonsec:'',
                    'access_token' => isset($this->accessToken)?$this->accessToken:'',
                    'params' =>  '',
                    'jsonData' => $postdata
                );

                $nonce = $this->ClassObject->secMe($options);

                $url = baseURL . advancePaymentReceipt;

                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
                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
                    )
                );
                $receiptId = curl_exec($ch);

                if (curl_errno($ch)) {
                    echo 'Curl error: ' . curl_error($ch);
                } else {
                    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                    if ($httpCode == 200) {
                        $responceArr = array('status' => 'SUCCESS', 'receiptId' => $receiptId);
                        return  $responceArr;
                    } else {
                        return "RECEIPT_NOT_GENERATE";
                    }
                }

            }
            else
            {
                return "RECEIPT_ALREADY_GENERATE";
            }
        }
    }

}
