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

class SendPaymentLinkPayment
{
    public $accessToken;
    private $conn;
    private $connMain;
    private $ClassObject;
    private $nonsec;

    public 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 : '';
        $authorization = "Authorization: Bearer " . $this->accessToken;
    }

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

    public function createPaymentId($inputParam)
    {
        if (!$this->accessToken) {
            return "ACCESS_TOKEN";
        } else {
            $responseVal = '';

            if ((isset($inputParam['id']) && $inputParam['id'] !== "") ||
            (isset($inputParam['studentId']) && $inputParam['studentId'] !== "") ||
            (isset($inputParam['applicantId']) && $inputParam['applicantId'] !== "")) {
                $authorization = "Authorization: Bearer " . $this->accessToken;
                $paymentLinkId = str_replace(" ", "+", $inputParam['id']);
                $studentId = isset($inputParam['studentId']) ? $inputParam['studentId'] : '';
                $applicantId = isset($inputParam['applicantId']) ? $inputParam['applicantId'] : '';
                $studentId = str_replace(" ", "+", $studentId);
                $applicantId = str_replace(" ", "+", $applicantId);
                $params = '?id=' . $paymentLinkId . '&' . (isset($inputParam['studentId']) ? 'studentId='.$studentId : 'applicantId=' . $applicantId);
                $options = array(
                    'access_token' => isset($this->accessToken) ? $this->accessToken : '',
                    'public_key' => isset($this->nonsec) ? $this->nonsec : '',
                    'params' => $params,
                    'jsonData' => '',
                );
                $nonce = $this->ClassObject->secMe($options);
                $url = baseURL . studentPaymentLinkDetails . $params;
                Logger::info("[URL] : " . $url);
                $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,
                        'platform: mobile_serosoft'
                    )
                );
                $resultcurl = curl_exec($ch);
            $curlError = curl_error($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $headers = substr($resultcurl, 0, $headerSize);
            $body = substr($resultcurl, $headerSize);
            curl_close($ch);

            if ($curlError) {
                Logger::info("[createPaymentId] CURL ERROR: " . $curlError);
            }

            Logger::info("[createPaymentId] HTTP Status Code: " . $httpCode);
            Logger::info("[createPaymentId] Response Headers: " . trim($headers));
            Logger::info("[createPaymentId] Response Body: " . $body);
                $paymentLinkInfo = json_decode($resultcurl, true);
                if (isset($paymentLinkInfo['receiptAmount']) && $paymentLinkInfo['receiptAmount'] !== "") {

                    try {
                        if (isset($paymentLinkInfo['onlinePaymentId']) && $paymentLinkInfo['onlinePaymentId'] && isset($paymentLinkInfo['paymentLinkId']) && $paymentLinkInfo['paymentLinkId'] && isset($paymentLinkInfo['academyLocationId']) && $paymentLinkInfo['academyLocationId'] && isset($paymentLinkInfo['receiptAmount']) && $paymentLinkInfo['receiptAmount']) {
                            $fullName = isset($paymentLinkInfo['fullName']) ? $paymentLinkInfo['fullName'] : '';
                            $emailId = isset($paymentLinkInfo['emailId']) ? $paymentLinkInfo['emailId'] : '';
                            $phoneNo = isset($paymentLinkInfo['phoneNo']) ? $paymentLinkInfo['phoneNo'] : '';
                            $currency = isset($paymentLinkInfo['currencyCode']) ? $paymentLinkInfo['currencyCode'] : '';
                            $studentId = isset($paymentLinkInfo['studentId']) ? $paymentLinkInfo['studentId'] : '';
                            $studentCode = isset($paymentLinkInfo['studentcode']) ? $paymentLinkInfo['studentcode'] : '';
                            $applicantId = isset($paymentLinkInfo['applicantId']) ? $paymentLinkInfo['applicantId'] : '';
                            $applicantCode = isset($paymentLinkInfo['applicantCode']) ? $paymentLinkInfo['applicantCode'] : '';
                            $phoneCode = isset($paymentLinkInfo['phoneCode']) ? $paymentLinkInfo['phoneCode'] : '';
                            $paymentType = (isset($paymentLinkInfo['paymentType'])) ? $paymentLinkInfo['paymentType'] : 'SendPaymentLink-PAYMENT';
                            $costCenterId = isset($paymentLinkInfo['costCenterId']) ? $paymentLinkInfo['costCenterId'] : '';
                            $currentDateTime = date('Y-m-d H:i:s');
                            $query = "INSERT INTO online_payment (sendPaymentLinkId, onlinePaymentId, txnId, paymentStatus, paymentDate, receiptStatus, amount,name,email,phoneNo,applicantId,applicantCode,studentId,code,feeHead, academyLocationId, phoneCode ,paymentType,currency) VALUES ('" . $paymentLinkInfo['paymentLinkId'] . "','" . $paymentLinkInfo['onlinePaymentId'] . "','','initiate', '" . $currentDateTime . "' ,''," . $paymentLinkInfo['receiptAmount'] . ",'" . $fullName . "','" . $emailId . "','" . $phoneNo . "','" . $applicantId . "','" . $applicantCode . "','" . $studentId . "','" . $studentCode . "', '".$costCenterId."' ,'" . $paymentLinkInfo['academyLocationId'] . "', '" . $phoneCode . "' , '".$paymentType."', '".$currency."')";

                            $insert = mysqli_query($this->conn, $query);
                            $paymentId = mysqli_insert_id($this->conn);
                            $responseVal = $paymentId;
                        } else {
                            $responseVal = "MYSQL_ERROR";
                        }
                    } catch (Exception $e) {
                        $responseVal = 'QUERY_ERROR';
                    }
                } else {
                    $responseVal = 'AMOUNT_ISSUE';
                }


            }else
            {
                $responseVal = "PARAM_ISSUE";
            }
            return $responseVal ;
        }

    }

    public function getMerchantDetailsByAl($academyLocationId)
    {
        if(!$this->accessToken)
        {
             return "ACCESS_TOKEN";
        }
        else
        {
            $authorization = "Authorization: Bearer " . $this->accessToken;
            $url = baseURL . gatewayDetailsAPI . '?isActive=true&academyLocationIds=' . $academyLocationId;
            $options = array(
                'public_key' => isset($this->nonsec)?$this->nonsec:'',
                'params' => 'isActive=true&academyLocationIds=' . $academyLocationId,
                '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);
            if(count($responceERPGateway) > 0)
            {
                return $responceERPGateway[0];
            }
            else
            {
                return 'No_DATA';
            }
        }
    }

    function getStandardMerchantDetailsByAl($gatewayName , $academyLocationId, $currencyCode = '' , $costCenter = '') {
        if(!$this->accessToken)
        {
             return "ACCESS_TOKEN";
        }
        else
        {
            $authorization = "Authorization: Bearer " . $this->accessToken;
            $params ='qry='.$gatewayName.'&academyLocationId=' . $academyLocationId.'&currencyCode='.$currencyCode.'&costCenterId='.$costCenter;
            $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($sendPaymentLinkId,$onlinePaymentId, $txnId, $orderStatus) {
        if(!$this->accessToken)
        {
            return "ACCESS_TOKEN";
        }
        else
        {
            $authorization = "Authorization: Bearer " . $this->accessToken;
            $selectInstumentCount = 0;
            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='{"id":"'.$onlinePaymentId.'","txnid":"'.$txnId.'","status":"'.$orderStatus.'"}';
                $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 . successRestUpdateStatus);
                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);

                $applicantjson_save='{"id":"'.$onlinePaymentId.'"}';
                $options = array(
                    'public_key' => isset($this->nonsec)?$this->nonsec:'',
                    'params' => '',
                    'jsonData' => $applicantjson_save,
                    'access_token' => isset($this->accessToken)?$this->accessToken:'',
                );
                $nonce = $this->ClassObject->secMe($options);

                $ch1 = curl_init(baseURL . successRestCreateReceipt);
                curl_setopt($ch1, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch1, CURLOPT_POSTFIELDS, $applicantjson_save);
                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($applicantjson_save),
                    'nonce:' .$nonce
                    )
                );

                $resultcurl1 = curl_exec($ch1);
                $responceERP1 = json_decode($resultcurl1);
                $this->setPaymentLinkExpire($sendPaymentLinkId , $txnId);               
                if($responceERP1 == $onlinePaymentId)
                {
                    return "SUCCESS";
                }
                else
                {
                    return "RECEIPT_NOT_GENERATE";
                }
            }
            else
            {
                return "RECEIPT_ALREADY_GENERATE";
            }
        }
    }

    function setPaymentLinkExpire($sendPaymentLinkId , $txnId)
    {
        $authorization = "Authorization: Bearer " . $this->accessToken;
        $jsonData = '{"paymentLinkId":'.$sendPaymentLinkId.',"txnId":"'.$txnId.'"}';
        $options = array(
            'public_key' => isset($this->nonsec)?$this->nonsec:'',
            'params' => '',
            'jsonData' => $jsonData,
            'access_token' => isset($this->accessToken)?$this->accessToken:'',
        );
        $nonce = $this->ClassObject->secMe($options);
        $ch1 = curl_init(baseURL . updatePaymentLinkExpire);
        curl_setopt($ch1, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $jsonData);
        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($jsonData),
                'nonce: ' . $nonce
                    )
                );
        $resultcurl1 = curl_exec($ch1);  
        return $resultcurl1;      
    }
}
