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

    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 createPaymentId($inputParam){
       if(!$this->accessToken)
       {
            return "ACCESS_TOKEN";
       }
       else
       {
            $responceVal = '';

            if ($inputParam['totalAmount'] != "")
            {
                $txnId = '';
                $studentName = $inputParam['firstName']." ".$inputParam['lastName'];
                $currency = isset($inputParam['currencyCode'])?$inputParam['currencyCode']:'';
                $costCenterId = isset($inputParam['examRevalPaymentDetail'][0]['costCenterId'])?$inputParam['examRevalPaymentDetail'][0]['costCenterId']:'';
                $query = "INSERT INTO reval_payment (studentCode,name, email, phoneNo, txnId, amount,costCenterId, paymentStatus, paymentDate,currency) VALUES ('" . $inputParam['studentCode'] . "','" . $studentName . "','" . $inputParam['email'] . "', '" . $inputParam['phoneNo'] . "' ,'" . $txnId . "'," . $inputParam['totalAmount'] . ", '".$costCenterId."' ,'initiate', '".date('Y-m-d H:i:s')."','" . $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['feePlanRuleStageId'];
                            $amount = $examDetailModelData['amount'];
                            $examRevalRuleMappingId = $examDetailModelData['examRevalRuleMappingId'];
                            $examinationResultId = $examDetailModelData['examinationResultId'];
                            $examinationResultId = ($examDetailModelData['examinationResultId'] == null) ? 0: $examDetailModelData['examinationResultId'];
                            $courseVariantId = $examDetailModelData['courseVariantId'];
                            $periodId = $examDetailModelData['periodId'];
                            $eventId = $examDetailModelData['eventId'];
                            $revaluationType = $examDetailModelData['revaluationType'];
                            if(is_int($examDetailModelData['appliedDate']))
                            {
                                $appliedDate = date('Y-m-d', $examDetailModelData['appliedDate']/1000);
                            }
                            else if($examDetailModelData['appliedDate'])
                            {
                                $appliedDate = date('Y-m-d', strtotime($examDetailModelData['appliedDate']));
                            }
                            else
                            {
                                $appliedDate = date('Y-m-d');
                            }
                            $previousMarks = $examDetailModelData['previousMarks'];
                            $previousGrade = $examDetailModelData['previousGrade'];
                            $previousGradePoint = ($examDetailModelData['previousGradePoint'] == null)? 0 : $examDetailModelData['previousGradePoint'];
                            $previousResultStatus = $examDetailModelData['previousResultStatus'];
                            $courseName = $examDetailModelData['courseName'];
                            $eventName = $examDetailModelData['eventName'];
                            $queryPrograms = "INSERT INTO reval_payment_detail(examRevalPaymentId,admissionId,studentId,feePlanRuleStageId,amount,examRevalRuleMappingId,examinationResultId,courseVariantId,periodId,eventId,revaluationType,appliedDate,previousMarks,previousGrade,previousGradePoint,previousResultStatus,courseName,eventName)
                                    VALUES('" . $paymentId . "','" . $admissionId . "','" . $studentId . "','" . $feePlanRuleStageId . "','" . $amount . "','" . $examRevalRuleMappingId . "','" . $examinationResultId . "'
                                    ,'" . $courseVariantId . "','" . $periodId . "','" . $eventId . "','" . $revaluationType . "','" . $appliedDate . "','" . $previousMarks . "','" . $previousGrade . "'
                                    ,'" . $previousGradePoint . "','" . $previousResultStatus . "','" . $courseName . "','" . $eventName . "')";
                            $insert = mysqli_query($this->conn, $queryPrograms);
                        }
                        $responceVal = $paymentId;
                    }
                    else
                    {
                        $responceVal = 'MYSQL_ERROR';
                    }
                }
                catch (Exception $e)
                {
                    $responceVal = 'QUERY_ERROR';
                }
            }
            else
            {
                $responceVal = 'AMOUNT_ISSUE';
            }
            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 = '' , $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 getStudentDetails($studentId) {
        if(!$this->accessToken)
        {
             return "ACCESS_TOKEN";
        }
        else
        {
            $authorization = "Authorization: Bearer " . $this->accessToken;
            $url = baseURL . getStudentDetails . '?studentId=' . $studentId;
            $options = array(
                'public_key' => isset($this->nonsec)?$this->nonsec:'',
                'params' => 'studentId=' . $studentId,
                '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
                )
            );

            $studentDetailCurl = curl_exec($ch);
            $studentDetailResult = json_decode($studentDetailCurl, true);
            if(isset($studentDetailResult[0]['userAacademyLocations'][0]['academyLocationId']))
            {
                $academyLocationId = $studentDetailResult[0]['userAacademyLocations'][0]['academyLocationId'];
            }
            else
            {
                $academyLocationId = '';
            }
            return $academyLocationId;
        }
    }

    function createReceipt($paymentId, $amount, $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)
            {
                $sqlPro = "SELECT * from reval_payment_detail where examRevalPaymentId=" . $paymentId;
                $selectPro = mysqli_query($this->conn, $sqlPro);
                $resultCom = array();
                while ($dataPro = mysqli_fetch_assoc($selectPro))
                {
                    $fetchDataDetail[] = $dataPro;
                }
                $examjsonPro = "";

                /*---------------------------------------Program Json-------------------------------*/
                $examjsonProgram = '[';
                foreach ($fetchDataDetail as $key => $resultProData)
                {
                    $examRevalPayment='{"id":'.$resultProData['examRevalPaymentId'].'}';
                    $examjsonPro1='{"id":'.$resultProData['id'].',"examRevalPayment":'.$examRevalPayment.',"admissionId":'.$resultProData['admissionId'].',"studentId":'.$resultProData['studentId'].',"feePlanRuleStageId":'.$resultProData['feePlanRuleStageId'].',"amount":'.$resultProData['amount'].',"examRevalRuleMappingId":'.$resultProData['examRevalRuleMappingId'].',"examinationResultId":'.$resultProData['examinationResultId'].',"courseVariantId":'.$resultProData['courseVariantId'].',"periodId":'.$resultProData['periodId'].',"eventId":'.$resultProData['eventId'].',"revaluationType":"'.$resultProData['revaluationType'].'","appliedDate":"'.$resultProData['appliedDate'].'","approvalStatus":"APPROVED","previousMarks":'.$resultProData['previousMarks'].',"previousGrade":"'.$resultProData['previousGrade'].'","previousGradePoint":'.$resultProData['previousGradePoint'].',"previousResultStatus":"'.$resultProData['previousResultStatus'].'"},';
                    $examjsonPro .= $examjsonPro1;
                }
                $examjsonPro = rtrim($examjsonPro, ',');
                $examjsonPro .= ']';
                $examjsonProgram .= $examjsonPro;
                /*-------------------------------------------------------------------------*/

                $examJson='{"id":'.$resultProData['id'].',"totalAmount":'.$amount.',"txnId":"'.$txnId.'","detailModel":'.$examjsonProgram.'}';
                $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 . billHeaderCreation);
                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);
                curl_close($ch1);
                $responceERP1 = json_decode($resultcurl1);
                if (isset($responceERP1->receiptStatus) && ($responceERP1->receiptStatus == '1' || $responceERP1->receiptStatus == 1))
                {

                    $receiptNo = '';
                    foreach ($responceERP1->detailModel as $examDetailModelData)
                    {
                        $query = "UPDATE reval_payment_detail SET billNo='" . $examDetailModelData->billNo . "', receiptNo='" . $examDetailModelData->receiptNo . "', billId='" . $examDetailModelData->billId . "', receiptId='" . $examDetailModelData->receiptId . "' WHERE id=" . $examDetailModelData->id;
                        $update = mysqli_query($this->conn, $query);
                        $receiptNo = $examDetailModelData->receiptNo;

                    }

                    $query = "UPDATE reval_payment SET receiptStatus='" . $orderStatus . "' WHERE id=" . $paymentId;
                    $update = mysqli_query($this->conn, $query);
                    $responceArr = array('status' => 'SUCCESS', 'receiptId' => $receiptNo);

                    return $responceArr;
                }
                else
                {
                    return "RECEIPT_NOT_GENERATE";
                }
            }
            else
            {
                return "RECEIPT_ALREADY_GENERATE";
            }
        }
    }

}


// $res_result = callAPI($method, $url, $finalJsonReq);
// $dualVerifyData = json_decode($res_result, true);

// print_r($response_msg);