<?php
require_once("dokuPaymentGateway.php");
require_once("./config/QueryBuilder.php");

class PaymentRequest
{
    private $conn;
    private $queryBuilder;
    private $dokuObj;
    private $translationMsg;

    public function __construct($conn)
    {
        $this->conn = $conn;
        $this->queryBuilder = new QueryBuilder($conn);
        $this->dokuObj = new DokuPaymentGateway();
        $this->translationMsg = json_decode(TRANSLATION_MSG, true);
    }

    public function paymentRequest($data, $screenName, $tableName, $merchantDetails)
    {
        if ($data['gatewayConfig']) {
            echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . $this->translationMsg['TXN_ID_ALREADY_GENERATED'] . '</h4>
                    </div>';
        } else {            
            $activeGateway = $data['paymentOption'];
            $gatewayJSON = <<<GATEWAYJSON
            {
                "environment": "{$merchantDetails['checkoutURL']}",
                "clientId": "{$merchantDetails['clientId']}",
                "secretKey": "{$merchantDetails['secretKey']}",
                "currencyCode": "{$merchantDetails['currencyCode']}",
                "itemName": "{$tableName}",
                "dueDate": "{$merchantDetails['customfield1']}",
                "retry":"{$merchantDetails['customfield2']}"
            }
            GATEWAYJSON;
            $txnId = 'INV' . rand(100000, 199999) . '-' . time();
            $updateData = [
                'txnId' => $txnId,
                'gatewayConfig' => $gatewayJSON,
                'academyLocationId' => $data['academyLocationId'],
                'paymentOption' => $activeGateway
            ];
            $where = ['id' => $data['id']];
            $result = $this->queryBuilder->update($tableName, $updateData, $where);

            if ($result == 1) {
                $paymentRequestColumnData = [
                    'screen' => $screenName,
                    'txnId' => $txnId,
                    'paymentDate' => date('Y-m-d H:i:s'),
                    'onlinePaymentId' => !empty($data['onlinePaymentId']) ? $data['onlinePaymentId'] : (isset($data['onlinePaymentId']) ? 0 : NULL),
                    'paymentId' => $data['id'],
                    'payment_gateway' => $activeGateway
                ];
                $this->queryBuilder->insert('payment_request', $paymentRequestColumnData);
                $where = ['id' => $data['id']];
                $paymentDetails = $this->queryBuilder->selectById($tableName, '*', $where);
                $gatewayInfo = '';

                if ($paymentDetails && $paymentDetails['gatewayConfig']) {
                    $gatewayInfoArr = json_decode($paymentDetails['gatewayConfig'], true);
                    $requiredKeys = ['environment', 'clientId', 'secretKey', 'currencyCode', 'itemName'];

                    if (count(array_filter($gatewayInfoArr, fn($value) => !empty($value) && isset($value))) === count($requiredKeys)) {
                        $gatewayInfo = 'EXIST';
                    }
                }

                if (!$paymentDetails || $paymentDetails == 0 || $gatewayInfo = '') {
                    echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</h4>
                            </div>';
                } else {                    
                    $paymentRequest = $this->dokuObj->createOrder($paymentDetails);
                    //Storing Create Order Response in DB
                    $updateData = [
                        'paymentRequest' => json_encode($paymentRequest),
                        'paymentStatus' => $paymentRequest['status'] == 'SUCCESS' ? 'PENDING' : 'FAILED'
                    ];
                    $where = ['id' => $data['id']];
                    $this->queryBuilder->update($tableName, $updateData, $where);

                    if (isset($paymentRequest['status']) && $paymentRequest['status'] == 'SUCCESS' && isset($paymentRequest['url'])) {
                        echo header('Location: ' . $paymentRequest['url']);
                    } else {

                        echo '<div class="col-md-12 text-center alert alert-warning">
                                <h4>' . $this->translationMsg['PAYMENT_GATEWAY_SERVER_ERROR'] . '</h4>
                            </div>';
                    }
                }
            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '1</h4>
                        </div>';
            }
        }
    }

    public function onlinePaymentReceipt($paymentRequest, $connMain)
    {
        require_once("academia/onlinePayment.php");
        $tableName = 'online_payment';
        $txnId = $paymentRequest['txnId'];
        $onlinePaymentObj = new OnlinePayment();
        $onlinePaymentObj->setConnection($this->conn, $connMain);
        $where = ['id' => $paymentRequest['paymentId'], 'txnId' => $txnId];
        $onlinePaymentInfo = $this->queryBuilder->selectById($tableName, '*', $where);

        if ($onlinePaymentInfo) {
            if ($onlinePaymentInfo['formSubmissionStatus'] != 1 && isset($paymentRequest['txnId'])) {
                $orderInfo = $this->dokuObj->fetchOrder($onlinePaymentInfo);

                // Prepare update data for both success and error cases
                $updateData = [
                    'notificationResponse' => json_encode($orderInfo),
                    'formSubmissionStatus' => 1,
                    'paymentStatus' => isset($orderInfo['transactionState']) ? $orderInfo['transactionState'] : ($orderInfo['status'] == 'ERROR' ? 'FAILED' : 'UNKNOWN')
                ];
                $where = ['id' => $paymentRequest['paymentId']];
                $this->queryBuilder->update($tableName, $updateData, $where);

                if ($orderInfo['status'] == 'SUCCESS' && $orderInfo['transactionState'] == 'SUCCESS') {
                    $response = $onlinePaymentObj->createReceipt($onlinePaymentInfo['onlinePaymentId'], $txnId, $orderInfo['transactionState']);
                    if ($response == 'SUCCESS') {
                        $updateData = ['receiptStatus' => $response];
                        $where = ['id' => $paymentRequest['paymentId']];
                        $this->queryBuilder->update($tableName, $updateData, $where);
                        echo '<div class="col-md-12 text-center alert alert-success">
                               <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_GENERATED']) . '</h4>
                            </div>';
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-success">
                               <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                            </div>';
                    }
                } else {
                    $orderStatus = isset($orderInfo['transactionState']) ? $orderInfo['transactionState'] : ($orderInfo['status'] == 'ERROR' ? $orderInfo['message'] : 'NOT-FOUND');
                    echo '<div class="col-md-12 text-center alert alert-warning">
                           <h4>' . str_replace("[ORDER_STATUS]", $orderStatus, $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                        </div>';
                }
            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                       <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</h4>
                    </div>';
            }
        } else {
            echo '<div class="col-md-12 text-center alert alert-warning">
                   <h4>' . $this->translationMsg['TRANSACTION_DATA_NOT_FOUND'] . '</h4>
                </div>';
        }
    }

    public function declarationPaymentReceipt($paymentRequest, $connMain)
    {
        require_once("academia/declarationPayment.php");
        $tableName = 'declaration_payment';
        $txnId = $paymentRequest['txnId'];
        $declarationObj = new DeclarationPayment();
        $declarationObj->setConnection($this->conn, $connMain);
        $where = ['id' => $paymentRequest['paymentId'], 'txnId' => $txnId];
        $declarationInfo = $this->queryBuilder->selectById($tableName, '*', $where);

        if ($declarationInfo) {
            if ($declarationInfo['formSubmissionStatus'] != 1 && isset($paymentRequest['txnId'])) {
                $orderInfo = $this->dokuObj->fetchOrder($declarationInfo);

                // Prepare update data for both success and error cases
                $updateData = [
                    'notificationResponse' => json_encode($orderInfo),
                    'formSubmissionStatus' => 1,
                    'paymentStatus' => isset($orderInfo['transactionState']) ? $orderInfo['transactionState'] : ($orderInfo['status'] == 'ERROR' ? 'FAILED' : 'UNKNOWN')
                ];
                $where = ['id' => $paymentRequest['paymentId']];
                $this->queryBuilder->update($tableName, $updateData, $where);

                if ($orderInfo['status'] == 'SUCCESS' && $orderInfo['transactionState'] == 'SUCCESS') {
                    $declarationInfo['paymentStatus'] = $orderInfo['status'];
                    $response = $declarationObj->createReceipt($declarationInfo);
                    if (isset($response['status']) && $response['status'] == 'SUCCESS') {
                        $updateData = ['receiptStatus' => $response['status'], 'receiptId' => $response['receiptId']];
                        $where = ['id' => $paymentRequest['paymentId']];
                        $this->queryBuilder->update($tableName, $updateData, $where);
                        echo '<div class="col-md-12 text-center alert alert-success">
                            <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_GENERATED']) . '</h4>
                            </div>';
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-success">
                            <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                            </div>';
                    }
                } else {
                    if ($orderInfo['status'] == 'SUCCESS' || $orderInfo['status'] == 'ERROR') {
                        $updateData = [
                            'notificationResponse' => json_encode($orderInfo),
                            'formSubmissionStatus' => 1,
                            'paymentStatus' => $orderInfo['status']
                        ];
                        $where = ['id' => $paymentRequest['paymentId']];
                        $this->queryBuilder->update($tableName, $updateData, $where);
                    }
                    $orderStatus = isset($orderInfo['transactionState']) ? $orderInfo['transactionState'] : ($orderInfo['status'] == 'ERROR' ? $orderInfo['message'] : 'NOT-FOUND');
                    echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . str_replace("[ORDER_STATUS]", $orderStatus, $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                        </div>';
                }
            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</h4>
                    </div>';
            }
        } else {
            echo '<div class="col-md-12 text-center alert alert-warning">
                <h4>' . $this->translationMsg['TRANSACTION_DATA_NOT_FOUND'] . '</h4>
                </div>';
        }
    }

    public function sendPaymentLinkReceipt($paymentRequest, $connMain)
    {
        require_once("academia/sendPaymentLinkPayment.php");
        $tableName = 'online_payment';
        $txnId = $paymentRequest['txnId'];

        $sendPaymentLinkObj = new SendPaymentLinkPayment();
        $sendPaymentLinkObj->setConnection($this->conn, $connMain);

        $where = ['id' => $paymentRequest['paymentId'], 'txnId' => $txnId];
        $sendPaymentLinkInfo = $this->queryBuilder->selectById($tableName, '*', $where);

        if ($sendPaymentLinkInfo) {
            if ($sendPaymentLinkInfo['formSubmissionStatus'] != 1 && isset($paymentRequest['txnId'])) {
                $orderInfo = $this->dokuObj->fetchOrder($sendPaymentLinkInfo);

                // Always update after fetch (success or fail)
                $updateData = [
                    'notificationResponse' => json_encode($orderInfo),
                    'formSubmissionStatus' => 1,
                    'paymentStatus' => isset($orderInfo['transactionState'])
                        ? $orderInfo['transactionState']
                        : ($orderInfo['status'] == 'ERROR' ? 'FAILED' : 'UNKNOWN')
                ];
                $this->queryBuilder->update($tableName, $updateData, $where);

                if ($orderInfo['status'] == 'SUCCESS' && $orderInfo['transactionState'] == 'SUCCESS') {                    

                    $response = $sendPaymentLinkObj->createReceipt(
                        $sendPaymentLinkInfo['sendPaymentLinkId'],
                        $sendPaymentLinkInfo['onlinePaymentId'],
                        $txnId,
                        $orderInfo['status']
                    );                    
                    if ($response == 'SUCCESS') {
                        $updateData = [
                            'receiptStatus' => $response                            
                        ];
                        $this->queryBuilder->update($tableName, $updateData, $where);

                        echo '<div class="col-md-12 text-center alert alert-success">
                                <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_GENERATED']) . '</h4>
                            </div>';
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-success">
                                <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                            </div>';
                    }
                } else {
                    if ($orderInfo['status'] == 'SUCCESS' || $orderInfo['status'] == 'ERROR') {
                        $updateData = [
                            'notificationResponse' => json_encode($orderInfo),
                            'formSubmissionStatus' => 1,
                            'paymentStatus' => $orderInfo['status']
                        ];
                        $this->queryBuilder->update($tableName, $updateData, $where);
                    }

                    $orderStatus = isset($orderInfo['transactionState'])
                        ? $orderInfo['transactionState']
                        : ($orderInfo['status'] == 'ERROR' ? $orderInfo['message'] : 'NOT-FOUND');

                    echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>' . str_replace("[ORDER_STATUS]", $orderStatus, $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                        </div>';
                }
            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</h4>
                    </div>';
            }
        } else {
            echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>' . $this->translationMsg['TRANSACTION_DATA_NOT_FOUND'] . '</h4>
                </div>';
        }
    }

    public function advancePaymentReceipt($paymentRequest, $connMain)
    {
        require_once("academia/advancePayment.php");
        $tableName = 'advance_payment';
        $txnId = $paymentRequest['txnId'];

        $advancePaymentObj = new AdvancePayment();
        $advancePaymentObj->setConnection($this->conn, $connMain);

        $where = ['id' => $paymentRequest['paymentId'], 'txnId' => $txnId];
        $advancePaymentInfo = $this->queryBuilder->selectById($tableName, '*', $where);

        if ($advancePaymentInfo) {
            if ($advancePaymentInfo['formSubmissionStatus'] != 1 && isset($paymentRequest['txnId'])) {                
                $orderInfo = $this->dokuObj->fetchOrder($advancePaymentInfo);
                $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'formSubmissionStatus' => 1,
                        'paymentStatus' => $orderInfo['status']
                    ];
                $where = ['id' => $paymentRequest['paymentId']];
                $this->queryBuilder->update($tableName, $updateData, $where);             
                if (
                    $orderInfo['status'] == 'SUCCESS' &&  $orderInfo['transactionState'] == 'SUCCESS') {                 
                    $advancePaymentInfo['paymentStatus'] = $orderInfo['transactionState'];
                    $response = $advancePaymentObj->createReceipt($advancePaymentInfo);

                    if (isset($response['status']) && $response['status'] == 'SUCCESS') {
                        $updateData = [
                            'receiptStatus' => $response['status'],
                            'receiptId' => $response['receiptId']
                        ];
                        $this->queryBuilder->update($tableName, $updateData, $where);

                        echo '<div class="col-md-12 text-center alert alert-success">
                            <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_GENERATED']) . '</h4>
                        </div>';
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-success">
                            <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                        </div>';
                    }

                } else {                    
                    if ($orderInfo['status'] == 'SUCCESS' || $orderInfo['status'] == 'ERROR') {
                        $updateData = [
                            'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                            'formSubmissionStatus' => 1,
                            'paymentStatus' => $orderInfo['status'] ?? 'UNKNOWN'
                        ];
                        $this->queryBuilder->update($tableName, $updateData, $where);
                    }                    
                    $orderStatus = isset($orderInfo['transactionState'])
                        ? $orderInfo['transactionState']
                        : ($orderInfo['status'] == 'ERROR' ? $orderInfo['message'] : 'NOT-FOUND');

                    echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . str_replace("[ORDER_STATUS]", $orderStatus, $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                    </div>';
                }

            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '.</h4>
                </div>';
            }
        } else {
            echo '<div class="col-md-12 text-center alert alert-warning">
                <h4>' . $this->translationMsg['TRANSACTION_DATA_NOT_FOUND'] . '</h4>
            </div>';
        }
    }

    public function donationPaymentReceipt($paymentRequest, $connMain)
    {
        require_once("academia/donationPayment.php");
        $tableName = 'donation_payment';
        $txnId = $paymentRequest['txnId'];
        $donationObj = new DonationPayment();
        $donationObj->setConnection($this->conn, $connMain);
        $where = ['id' => $paymentRequest['paymentId'], 'txnId' => $txnId];
        $donationInfo = $this->queryBuilder->selectById($tableName, '*', $where);
        if ($donationInfo) {
            if ($donationInfo['formSubmissionStatus'] != 1 && isset($paymentRequest['txnId'])) {
                $orderInfo = $this->dokuObj->fetchOrder($donationInfo);
                $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'formSubmissionStatus' => 1,
                        'paymentStatus' => $orderInfo['status']
                    ];
                $where = ['id' => $paymentRequest['paymentId']];
                $this->queryBuilder->update($tableName, $updateData, $where);
                if ($orderInfo['status'] == 'SUCCESS' &&  $orderInfo['transactionState'] == 'SUCCESS') {                 
                    
                    $response = $donationObj->createReceipt($donationInfo, 'TXN_SUCCESS');
                    if ($response == 'SUCCESS') {
                        $updateData = ['receiptStatus' => $response];
                        $where = ['id' => $paymentRequest['paymentId']];
                        $result = $this->queryBuilder->update($tableName, $updateData, $where);
                        echo '<div class="col-md-12 text-center alert alert-success">
                                   <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_GENERATED']) . '</h4>
                            </div>';
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-success">
                                    <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                                </div>';
                    }
                } else {
                    if ($orderInfo['status'] == 'SUCCESS' || $orderInfo['status'] == 'ERROR') {
                        $updateData = [
                            'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                            'formSubmissionStatus' => 1,
                            'paymentStatus' => $orderInfo['status'] ?? 'UNKNOWN'
                        ];
                        $this->queryBuilder->update($tableName, $updateData, $where);
                    }
                    $orderStatus = isset($orderInfo['transactionState'])
                        ? $orderInfo['transactionState']
                        : ($orderInfo['status'] == 'ERROR' ? $orderInfo['message'] : 'NOT-FOUND');

                    echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . str_replace("[ORDER_STATUS]", $orderStatus, $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                    </div>';
                }
            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '.</h4>
                    </div>';
            }
        } else {
            echo '<div class="col-md-12 text-center alert alert-warning">
              <h4>' . $this->translationMsg['TRANSACTION_DATA_NOT_FOUND'] . '</h4>
          </div>';
        }
    }

    public function courseEnrollementPaymentReceipt($paymentRequest, $connMain)
    {
        require_once("academia/courseEnrollement.php");
        $tableName = 'enrollment_payment';
        $txnId = $paymentRequest['txnId'];
        $courseEnrollementPaymentObj = new CourseEnrollement();
        $courseEnrollementPaymentObj->setConnection($this->conn, $connMain);
        $where = ['id' => $paymentRequest['paymentId'], 'txnId' => $txnId];
        $courseEnrollementInfo = $this->queryBuilder->selectById($tableName, '*', $where);
        if ($courseEnrollementInfo) {
            if ($courseEnrollementInfo['formSubmissionStatus'] != 1 && isset($paymentRequest['txnId'])) {
                $orderInfo = $this->dokuObj->fetchOrder($courseEnrollementInfo);
                $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'formSubmissionStatus' => 1,
                        'paymentStatus' => $orderInfo['status']
                    ];
                $where = ['id' => $paymentRequest['paymentId']];
                $this->queryBuilder->update($tableName, $updateData, $where);
                if ($orderInfo['status'] == 'SUCCESS' &&  $orderInfo['transactionState'] == 'SUCCESS') {                    
                    $response = $courseEnrollementPaymentObj->createReceipt($courseEnrollementInfo['onlinePaymentId'], $txnId, $orderInfo['status']);
                    if ($response == 'SUCCESS') {
                        $updateData = ['receiptStatus' => $response];
                        $where = ['id' => $paymentRequest['paymentId']];
                        $result = $this->queryBuilder->update($tableName, $updateData, $where);
                        echo '<div class="col-md-12 text-center alert alert-success">
                                    <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_GENERATED']) . '</h4>
                            </div>';
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-success">
                                    <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                                </div>';
                    }
                } else {
                    if ($orderInfo['status'] == 'SUCCESS' || $orderInfo['status'] == 'ERROR') {
                        $updateData = [
                            'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                            'formSubmissionStatus' => 1,
                            'paymentStatus' => $orderInfo['status'] ?? 'UNKNOWN'
                        ];
                        $this->queryBuilder->update($tableName, $updateData, $where);
                    }
                    $orderStatus = isset($orderInfo['transactionState'])
                        ? $orderInfo['transactionState']
                        : ($orderInfo['status'] == 'ERROR' ? $orderInfo['message'] : 'NOT-FOUND');

                    echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . str_replace("[ORDER_STATUS]", $orderStatus, $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                    </div>';
                }
            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '.</h4>
                    </div>';
            }
        } else {
            echo '<div class="col-md-12 text-center alert alert-warning">
              <h4>' . $this->translationMsg['TRANSACTION_DATA_NOT_FOUND'] . '</h4>
          </div>';
        }
    }

    public function RevaluationReceipt($paymentRequest, $connMain)
    {
        require_once("academia/revaluationPayment.php");
        $tableName = 'reval_payment';
        $txnId = $paymentRequest['txnId'];
        $revalObj = new RevaluationPayment();
        $revalObj->setConnection($this->conn, $connMain);
        $where = ['id' => $paymentRequest['paymentId'], 'txnId' => $txnId];
        $revalInfo = $this->queryBuilder->selectById($tableName, '*', $where);
        if ($revalInfo) {
            if ($revalInfo['formSubmissionStatus'] != 1 && isset($paymentRequest['txnId'])) {
                $orderInfo = $this->dokuObj->fetchOrder($revalInfo);                
                $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'formSubmissionStatus' => 1,
                        'paymentStatus' => $orderInfo['status']
                    ];
                $where = ['id' => $paymentRequest['paymentId']];
                $this->queryBuilder->update($tableName, $updateData, $where);
                if ($orderInfo['status'] == 'SUCCESS' &&  $orderInfo['transactionState'] == 'SUCCESS') {                    
                    $response = $revalObj->createReceipt($revalInfo['id'], $revalInfo['amount'], $txnId, $orderInfo['status']);
                    if (isset($response) && isset($response['status']) && $response['status'] == 'SUCCESS') {
                        $updateData = ['receiptStatus' => $response['status']];
                        $where = ['id' => $paymentRequest['paymentId']];
                        $result = $this->queryBuilder->update($tableName, $updateData, $where);
                        echo '<div class="col-md-12 text-center alert alert-success">
                                    <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_GENERATED']) . '</h4>
                         </div>';
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-success">
                                    <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                                </div>';
                    }
                } else {
                    if ($orderInfo['status'] == 'SUCCESS' || $orderInfo['status'] == 'ERROR') {
                        $updateData = [
                            'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                            'formSubmissionStatus' => 1,
                            'paymentStatus' => $orderInfo['status'] ?? 'UNKNOWN'
                        ];
                        $this->queryBuilder->update($tableName, $updateData, $where);
                    }
                    $orderStatus = isset($orderInfo['transactionState'])
                        ? $orderInfo['transactionState']
                        : ($orderInfo['status'] == 'ERROR' ? $orderInfo['message'] : 'NOT-FOUND');

                    echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . str_replace("[ORDER_STATUS]", $orderStatus, $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                    </div>';
                }
            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '.</h4>
                    </div>';
            }
        } else {
            echo '<div class="col-md-12 text-center alert alert-warning">
              <h4>' . $this->translationMsg['TRANSACTION_DATA_NOT_FOUND'] . '</h4>
          </div>';
        }
    }

    public function examAssessmentReceipt($paymentRequest, $connMain)
    {
        require_once "academia/examinationPayment.php";
        $tableName = 'assessment_payment';
        $txnId = $paymentRequest['txnId'];
        $examObj = new ExaminationPayment();
        $examObj->setConnection($this->conn, $connMain);
        $where = ['id' => $paymentRequest['paymentId'], 'txnId' => $txnId];
        $examInfo = $this->queryBuilder->selectById($tableName, '*', $where);
        if ($examInfo) {
            if ($examInfo['formSubmissionStatus'] != 1 && isset($paymentRequest['txnId'])) {
                $orderInfo = $this->dokuObj->fetchOrder($examInfo);
                $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'formSubmissionStatus' => 1,
                        'paymentStatus' => $orderInfo['status']
                    ];
                $where = ['id' => $paymentRequest['paymentId']];
                $this->queryBuilder->update($tableName, $updateData, $where);
                if ($orderInfo['status'] == 'SUCCESS' &&  $orderInfo['transactionState'] == 'SUCCESS') {                    
                    $response = $examObj->createReceipt($examInfo['id'], $examInfo['academyLocationId'], $txnId, $examInfo['amount'], $examInfo['currency']);
                    if (isset($response['status']) && $response['status'] == 'SUCCESS') {
                        $updateData = ['receiptStatus' => $response['status']];
                        $where = ['id' => $paymentRequest['paymentId']];
                        $result = $this->queryBuilder->update($tableName, $updateData, $where);
                        $tableName2 = 'assessment_payment_detail';
                        $updateDataDetail = ['receiptId' => $response['receiptId']];
                        $updateWhere = ['examAssessmentPaymentId' => $paymentRequest['paymentId']];
                        $result2 = $this->queryBuilder->update($tableName2, $updateDataDetail, $updateWhere);
                        echo '<div class="col-md-12 text-center alert alert-success">
                                    <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_GENERATED']) . '</h4>
                                </div>';
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-success">
                            <h4>' . str_replace("[TRANSACTION_ID]", $txnId, $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                         </div>';
                    }
                } else {
                    if ($orderInfo['status'] == 'SUCCESS' || $orderInfo['status'] == 'ERROR') {
                        $updateData = [
                            'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                            'formSubmissionStatus' => 1,
                            'paymentStatus' => $orderInfo['status'] ?? 'UNKNOWN'
                        ];
                        $this->queryBuilder->update($tableName, $updateData, $where);
                    }
                    $orderStatus = isset($orderInfo['transactionState'])
                        ? $orderInfo['transactionState']
                        : ($orderInfo['status'] == 'ERROR' ? $orderInfo['message'] : 'NOT-FOUND');

                    echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . str_replace("[ORDER_STATUS]", $orderStatus, $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                    </div>';
                }
            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '.</h4>
                    </div>';
            }
        } else {
            echo '<div class="col-md-12 text-center alert alert-warning">
                 <h4>' . $this->translationMsg['TRANSACTION_DATA_NOT_FOUND'] . '</h4>
          </div>';
        }
    }
}
?>