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

class ExaminationPayment{

    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 : '';
    }
    public function setConnection($applyNowConnection, $coreERPConnection) {
        $this->conn = $applyNowConnection;
        $this->connMain = $coreERPConnection;
    }

    function createExaminationPayemntId($inputParam)
    {
        if(!$this->accessToken)
        {
             return "ACCESS_TOKEN";
        }
        $responceVal = '';
        if(isset($inputParam['program'])  && $inputParam['program'] != "" && isset($inputParam['batch'])  && $inputParam['batch'] != "" && isset($inputParam['totalAmount'])  && $inputParam['totalAmount'] != "" && isset($inputParam['examRevalPaymentDetail']) && count($inputParam['examRevalPaymentDetail']) > 0)
        {
            $studentName = $inputParam['studentName'];
            $fullName =  $inputParam['firstName']." ".$inputParam['lastName'];
            $programName = $inputParam['program'];
            $batchName =    $inputParam['batch'];
            $currency = $inputParam['currencyCode'];
            $feePlanName = isset($inputParam['examRevalPaymentDetail'][0]['feeHeadName']);
            $query = "INSERT INTO assessment_payment (studentCode,name, email, phoneNo, amount, studentName, program, batch, feeHead, paymentDate, paymentStatus , currency) VALUES ('" . $inputParam['studentCode'] . "','" . $fullName. "','" . $inputParam['email'] . "', '". $inputParam['phoneNo'] . "' ,'" . $inputParam['totalAmount'] . "' ,'" . $studentName . "' ,'" . $programName . "' ,'" . $batchName . "' ,'" . $feePlanName . "', '".date('Y-m-d H:i:s')."', 'Initiate','" . $currency . "')";
            try
            {
                if ($insert = mysqli_query($this->conn, $query))
                {
                    $paymentId = mysqli_insert_id($this->conn);
                    foreach ($inputParam['examRevalPaymentDetail'] as $examDetailModelData)
                    {
                        $admissionId = $examDetailModelData['admissionId'];
                        $studentId = $examDetailModelData['studentId'];
                        $feePlanRuleStageId = $examDetailModelData['feePlanId'];
                        $amount = $examDetailModelData['amount'];
                        $evaluationGroupId = $examDetailModelData['evaluationGroupId'];
                        $periodId = $examDetailModelData['periodId'];

                    }
                    $queryPrograms = "INSERT INTO assessment_payment_detail(examAssessmentPaymentId,admissionId,studentId,receiptId,feePlanRuleStageId,amount,periodId,voucherMode,evaluationGroupId,currency,feePlanType,stageName,appliedDate,courseName,eventName)
                                VALUES('" . $paymentId . "','" . $admissionId . "','" . $studentId . "',null,'" . $feePlanRuleStageId . "','" . $amount . "','" . $periodId . "',null
                                ,'" . $evaluationGroupId . "',null,null,null,null,null,null)";

                        $insert = mysqli_query($this->conn, $queryPrograms);
                    $responceVal = $paymentId;
                }
                else
                {
                    $responceVal = "QUERY_ERROR";
                }
            }catch (Exception $e) {
                $responceVal = "QUERY_ERROR";
            }
        }
        else
        {
            $responceVal = "INVALID_PARAM";
        }
        return $responceVal;
    }

    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 = '') {
        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($paymentId , $academyLocationId , $txnId , $totalAmount , $currency = null)
    {
        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)
            {
                $currencyQuery = "SELECT id FROM currency where currencyCode = '".$currency."'";
                $currencyQuery = mysqli_query($this->connMain, $currencyQuery);
                $currencyData = mysqli_fetch_assoc($currencyQuery);
                $currencyId = isset($currencyData['id']) ? $currencyData['id'] : '1';
                $sqlPro = "SELECT * from assessment_payment_detail where examAssessmentPaymentId=" . $paymentId;
                $selectPro = mysqli_query($this->conn, $sqlPro);
                $dataPro = mysqli_fetch_assoc($selectPro);
                $academyLocationId ;
                $examJson='{"academyLocationId":"'.$academyLocationId.'","voucherMode":"BANK","receiptType":"REGULAR","receiptNo":"","raiseBillType":"P_AND_C_FEE","receiptFor":{"id":1,"value":"STUDENT"},"currency":{"id":"'.$currencyId.'"},"depositedCash":null,"transactionDate":"'.date('Y-m-d').'","student":{"id":"'.$dataPro['studentId'].'"},"narration":"NA","evaluationGroupId":"'.$dataPro['evaluationGroupId'].'","evalGroupId":"'.$dataPro['evaluationGroupId'].'","admissionId":"'.$dataPro['admissionId'].'","periodId":"'.$dataPro['periodId'].'","stageName":"Assessment Group","feePlanType":"Exam","feePlanId":"'.$dataPro['feePlanRuleStageId'].'","status":"FULLY_PENDING","receiptPaymentInstruments":[{"paymentMode":{"id":5},"instrumentBank":{"id":1},"instrumentNo":"'.$txnId.'","instrumentDate":"'.date('Y-m-d').'","amount":"'.$totalAmount.'"}]}';
                $options = array(
                    'public_key' => isset($this->nonsec)?$this->nonsec:'',
                    'params' => '',
                    'jsonData' => $examJson,
                    'access_token' => isset($this->accessToken)?$this->accessToken:'',
                );
                $nonce = $this->ClassObject->secMe($options);
                $ch1 = curl_init(baseURL . billHeaderCreationAssessment);
                curl_setopt($ch1, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch1, CURLOPT_POSTFIELDS, $examJson);
                curl_setopt($ch1, CURLOPT_TIMEOUT, 120);
                curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, TRUE);
                curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch1, CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt(
                    $ch1,
                    CURLOPT_HTTPHEADER,
                    array(
                        'Content-Type: application/json', $authorization,
                        'Content-Length: ' . strlen($examJson),
                        'nonce:' .$nonce
                    )
                );

                $resultcurl1 = curl_exec($ch1);
                // $errorDebug = '{"response": "'.$resultcurl1.'","examJson": "'.$examJson.'","url": "'.baseURL . billHeaderCreationAssessment.'", "authorization": "'.$authorization.'"}';
                curl_close($ch1);
                $responceERP1 = json_decode($resultcurl1);
                if ($responceERP1 != "" && $responceERP1 != 'Array' && is_numeric($responceERP1))
                {
                    $responceArr = array('status' => 'SUCCESS', 'receiptId' => $responceERP1);
                    return $responceArr;
                }
                else
                {
                    return "RECEIPT_NOT_GENERATE";
                }
            }
            else
            {
                return "RECEIPT_ALREADY_GENERATE";
            }
        }
    }
}

?>