<?php
require_once("./config/db_config.php");
require_once("./config/functionclass.php");
require_once('Logger.php');
class DeclarationPayment{
    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 createDeclarationPaymentId($inputParam){
        if(!$this->accessToken)
        {
             return "ACCESS_TOKEN";
        }
        else
        {
            $responceVal = '';
            if(isset($inputParam['onlinePaymentId']) > 0 && $inputParam['onlinePaymentId'] != "" && isset($inputParam['moduleId']) > 0 && $inputParam['moduleId'] != "" &&  isset($inputParam['setupId']) > 0 && $inputParam['setupId'] != "")
            {
                $authorization = "Authorization: Bearer " . $this->accessToken;
                $params = "id=" . $inputParam['onlinePaymentId'];
                $applicantjson='{"id":"'.$inputParam['onlinePaymentId'].'"}';
                $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(baseURL . declarationPayerInfo . '?' . $params);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
                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);
	            $responceERP2 = json_decode($resultcurl);
                $costCenterId = !empty($inputParam['costCenterId'])?json_encode(['costCentreId' => $inputParam['costCenterId']]):'';
                $currency = (isset($responceERP2->currencyCode) && $responceERP2->currencyCode) ? $responceERP2->currencyCode : '';
                if(isset($responceERP2->receiptAmount) && $responceERP2->receiptAmount && $responceERP2->receiptAmount > 0)
                {
                    if ($responceERP2->phoneNo) {
                        $phoneNo = $responceERP2->phoneNo;
                    } else {
                        $phoneNo = $responceERP2->mobileNo;
                    }
                    try
                    {
                        $moduleId = $inputParam['moduleId'];
                        $setupId = $inputParam['setupId'];
                        $inputParam['paymentType'] = isset($inputParam['paymentType']) ? $inputParam['paymentType'] : '';
                        $query = "INSERT INTO declaration_payment (onlinePaymentId, txnId, paymentStatus, paymentDate, receiptStatus, amount,name,email,phoneNo,applicantId,code,feeHead, moduleId, setupId, currency,paymentType) VALUES ('" . $_POST['onlinePaymentId'] . "','','initiate', '".date('Y-m-d H:i:s')."' ,''," . $responceERP2->receiptAmount . ",'" . $responceERP2->fullName . "','" . $responceERP2->emailId . "','" . $phoneNo . "','" . $responceERP2->applicantId . "','" . $responceERP2->code . "', '" . $costCenterId . "', '".$moduleId."', '".$setupId."', '".$currency."','".$inputParam['paymentType']."')";
                        $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 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($orderInfo) {
               if(!$this->accessToken)
        {
            return "ACCESS_TOKEN";
        }
        else
        {
            $authorization = "Authorization: Bearer " . $this->accessToken;
            if($orderInfo['applicationStatus'] == true || $orderInfo['applicationStatus'] == 'true')
            {
                $formSubmitStatus = $orderInfo['applicationStatus'];
            }
            else
            {
                $urlFormSubmit = baseURL.ApplicantFormSubmit.'?applicationId='.$orderInfo['applicantId'].'&currentDate'.date('Y-m-d');
                $options = array(
                    'public_key' => isset($this->nonsec)?$this->nonsec:'',
                    'params' => 'applicationId='.$orderInfo['applicantId'].'&currentDate'.date('Y-m-d'),
                    'jsonData' => '',
                    'access_token' => isset($this->accessToken)?$this->accessToken:'',
                );
                $nonce = $this->ClassObject->secMe($options);
                $ch = curl_init($urlFormSubmit);
                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
                    )
                );
                $formSubmitStatus = curl_exec($ch);
                if($formSubmitStatus == false || $formSubmitStatus == 'false')
                {
                    $formSubmitStatus = 'Application END Date Pass';
                }
            }

            if(!$orderInfo['portalLinkSave'])
            {
                $portalLinkSave = '';
                if($orderInfo['moduleId'] && $orderInfo['setupId'])
                {
                    $applicantjson = '{"application":{"id":'.$orderInfo['applicantId'].'},"applicantPortalModules":{"id":'.$orderInfo['moduleId'].'},"applicantPortalSetup":{"id":'.$orderInfo['setupId'].'},"isFilled":true}';
                    $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 . portalLinkSaved);
                    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
                        )
                    );
                    $portalLinkSave = curl_exec($ch);
                }
            }
            else
            {
                $portalLinkSave = $orderInfo['portalLinkSave'];
            }
            $query = "UPDATE declaration_payment SET portalLinkSave = '".$portalLinkSave."',  applicationStatus = '".$formSubmitStatus."' WHERE id=" . $orderInfo['id'];
            $update = mysqli_query($this->conn, $query);
            $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)
            {
                $applicantjson='{"id":"'.$orderInfo['onlinePaymentId'].'","txnid":"'.$orderInfo['txnId'].'","status":"'.$orderInfo['paymentStatus'].'"}';
                $options = array(
                    'public_key' => isset($this->nonsec)?$this->nonsec:'',
                    'params' => '',
                    'jsonData' => $applicantjson,
                    'access_token' => isset($this->accessToken)?$this->accessToken:'',
                );
                Logger::debug("Generated JSON for payment update: " . $applicantjson);

                $nonce = $this->ClassObject->secMe($options);
                $ch = curl_init(baseURL . declarationPaymentUpdateStatus);
                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
                    )
                );
                Logger::info("Sending request to update payment status...");

                $resultcurl = curl_exec($ch);
                if ($resultcurl === false) {
                    Logger::error("CURL Error: " . curl_error($ch));
                } else {
                    Logger::info("Response from update payment status: " . $resultcurl);
                }

                $applicantjson_save='{"id":'.$orderInfo['onlinePaymentId'].'}';
                Logger::debug("Generated JSON for receipt creation: " . $applicantjson_save);
                
                $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 . declarationPaymentCreateReceipt);
                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
                    )
                );
                Logger::info("Sending request to create receipt...");

                $resultcurl1 = curl_exec($ch1);
                if ($resultcurl1 === false) {
                    Logger::error("CURL Error (Receipt Creation): " . curl_error($ch1));
                } else {
                    Logger::info("Response from receipt creation: " . $resultcurl1);
                }
                $receiptId = json_decode($resultcurl1);
                Logger::debug("Decoded receipt ID: " . json_encode($receiptId));

                if($receiptId && is_int($receiptId) && $receiptId > 0)
                {
                    Logger::info("Receipt successfully generated with ID: " . $receiptId);

                    $responceArr = array('status' => 'SUCCESS', 'receiptId' => $receiptId);
                    return $responceArr;
                }
                else
                {
                    Logger::error("Failed to generate receipt.");
                    return "RECEIPT_NOT_GENERATE";
                }
            }
            else
            {
                return "RECEIPT_ALREADY_GENERATE";
            }
        }
    }
}


?>