<?php
require_once "payGatePaymentGateway.php";
require_once "./config/QueryBuilder.php";

class PaymentRequest
{
    private $conn;
    private $queryBuilder;
    private $paygateObj;
    private $translationMsg;
    public function __construct($conn)
    {
        $this->conn           = $conn;
        $this->queryBuilder   = new QueryBuilder($conn);
        $this->paygateObj     = new PayGatePaymentGateway();
        $this->translationMsg = json_decode(TRANSLATION_MSG, true);
    }

    public function paymentRequest($data, $screenName, $tableName, $merchantDetails)
    {
        // Check for existing gatewayConfig to prevent duplicates
        if (! empty($data['gatewayConfig'])) {
            echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>' . $this->translationMsg['TXN_ID_ALREADY_GENERATED'] . '</h4>
                  </div>';
            return;
        }
        $activeGateway = $data['paymentOption'];

        // Generate PayGate-specific gateway configuration
        if (isset($data['studentCode'])) {
            $data['code'] = $data['studentCode'];
        }
        $gatewayJSON = json_encode([
            'paygateId'     => $merchantDetails['paygateId'],
            'encryptionKey' => $merchantDetails['encryptionKey'],
            'currencyCode'  => $merchantDetails['currencyCode'],
            'checkoutUrl'   => $merchantDetails['checkoutUrl'],
            'country'       => $merchantDetails['customField1'],
            'reference'     => generateReference($data['code']),
        ]);

        // Update database with gateway config and transaction details
        $updateData = [
            'gatewayConfig'     => $gatewayJSON,
            'academyLocationId' => $data['academyLocationId'],
            'paymentOption'     => $activeGateway,
        ];
        $where  = ['id' => $data['id']];
        $result = $this->queryBuilder->update($tableName, $updateData, $where);

        if ($result != 1) {
            echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</h4>
                  </div>';
            return;
        }

        $paymentRequestColumnData = [
            'screen'          => $screenName,
            '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);

        // Retrieve updated payment details
        $where          = ['id' => $data['id']];
        $paymentDetails = $this->queryBuilder->selectById($tableName, '*', $where);

        if (! $paymentDetails || empty($paymentDetails['gatewayConfig'])) {
            echo '<div class="col-md-12 text-center alert alert-warning">
                     <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</h4>
                  </div>';
            return;
        }

        // Validate gateway configuration
        $gatewayInfoArr = json_decode($paymentDetails['gatewayConfig'], true);
        $isValidGateway = isset($gatewayInfoArr['paygateId']) && $gatewayInfoArr['paygateId'] &&
        isset($gatewayInfoArr['encryptionKey']) && $gatewayInfoArr['encryptionKey'] &&
        isset($gatewayInfoArr['currencyCode']) && $gatewayInfoArr['currencyCode'] &&
        isset($gatewayInfoArr['reference']) && $gatewayInfoArr['reference'];

        if (! $isValidGateway) {
            echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>' . $this->translationMsg['INVALID_PAYMENT_GATEWAY_CONFIGURATION'] . '</h4>
                  </div>';
            return;
        }

        $paymentDetails['paymentType'] = $data['paymentType'] ?? '';
        $paymentDetails['email']       = $data['email'] ?? '';

        $paymentRequest = $this->paygateObj->createOrder($paymentDetails);

        if (isset($paymentRequest['status']) && $paymentRequest['status'] === 'SUCCESS' && ! empty($paymentRequest['PAY_REQUEST_ID']) && ! empty($paymentRequest['CHECKSUM'])) {

            $updateData = ['paymentRequest' => json_encode($paymentRequest)];
            $where      = ['id' => $data['id']];
            $result     = $this->queryBuilder->update($tableName, $updateData, $where);

            $paymentRequestColumnData = ['txnId' => $paymentRequest['REFERENCE']];
            $where                    = ['paymentId' => $data['id'], 'screen' => $screenName];
            $updateResult             = $this->queryBuilder->update('payment_request', $paymentRequestColumnData, $where);

            if ($result && $updateResult > 0) {

                echo '<form action="' . $paymentRequest['action_url'] . '" method="post">';
                foreach ($paymentRequest['form_fields'] as $key => $value) {
                    echo '<input type="hidden" name="' . htmlspecialchars($key) . '" value="' . htmlspecialchars($value) . '">';
                }
                echo '<button type="submit" id="submit" type="hidden">Proceed to Payment</button>';
                echo '</form>';
                echo '<script type="text/javascript">
                        document.getElementById("submit").click();
                     </script>';

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

        }
    }

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

        if ($onlinePaymentInfo) {
            if ($onlinePaymentInfo['formSubmissionStatus'] != 1) {
                try {
                    $orderInfo  = $this->paygateObj->fetchOrder($onlinePaymentInfo);
                    $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'txnId'                => $orderInfo['txnID'],
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => $orderInfo['txnStatus'],
                    ];
                    $where = ['id' => $paymentRequest['paymentId']];

                    if ($orderInfo['Status'] === 'success') {
                        if ($orderInfo['reference'] === $reference && $orderInfo['txnStatus'] === 'Approved') {
                            $this->queryBuilder->update($tableName, $updateData, $where);
                            $response = $onlinePaymentObj->createReceipt(
                                $onlinePaymentInfo['onlinePaymentId'],
                                $orderInfo['txnID'],
                                $orderInfo['txnStatus']
                            );
                            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]", $orderInfo['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]", $orderInfo['txnID'], $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>

                                  </div>';
                            }
                        } else {
                            $this->queryBuilder->update($tableName, $updateData, $where);

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

                              </div>';
                        }
                    } else {
                        $this->queryBuilder->update($tableName, $updateData, $where);

                        echo '<div class="col-md-12 text-center alert alert-danger">
                            ' . str_replace("[REFERENCE]", $orderInfo['reference'], $this->translationMsg['PAYMENT_ERROR']) . '
                          </div>';
                    }
                } catch (Exception $e) {
                    error_log('Payment processing error: ' . $e->getMessage());
                    $updateData = [
                        'notificationResponse' => json_encode(['error' => $e->getMessage()]),
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => 'error',
                    ];
                    $this->queryBuilder->update($tableName, $updateData, $where);
                    echo '<div class="col-md-12 text-center alert alert-danger">
                         <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</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';
        $reference                   = $paymentRequest['txnId'];
        $courseEnrollementPaymentObj = new CourseEnrollement();
        $courseEnrollementPaymentObj->setConnection($this->conn, $connMain);
        $where                 = ['id' => $paymentRequest['paymentId']];
        $courseEnrollementInfo = $this->queryBuilder->selectById($tableName, '*', $where);

        if ($courseEnrollementInfo) {
            if ($courseEnrollementInfo['formSubmissionStatus'] != 1) {
                try {
                    $orderInfo  = $this->paygateObj->fetchOrder($courseEnrollementInfo);
                    $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'txnId'                => $orderInfo['txnID'],
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => $orderInfo['txnStatus'],
                    ];
                    $where = ['id' => $paymentRequest['paymentId']];

                    if ($orderInfo['Status'] === 'success') {
                        if ($orderInfo['reference'] === $reference && $orderInfo['txnStatus'] === 'Approved') {
                            $this->queryBuilder->update($tableName, $updateData, $where);
                            $response = $courseEnrollementPaymentObj->createReceipt(
                                $courseEnrollementInfo['onlinePaymentId'],
                                $orderInfo['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]", $orderInfo['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]", $orderInfo['txnID'], $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                                  </div>';
                            }
                        } else {
                            $this->queryBuilder->update($tableName, $updateData, $where);
                            echo '<div class="col-md-12 text-center alert alert-warning">
                                <h4>' . str_replace("[ORDER_STATUS]", $orderInfo['txnStatus'], $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                              </div>';
                        }
                    } else {
                        $this->queryBuilder->update($tableName, $updateData, $where);
                        echo '<div class="col-md-12 text-center alert alert-danger">
                            <h4>' . str_replace("[REFERENCE]", $orderInfo['reference'], $this->translationMsg['PAYMENT_ERROR']) . '</h4>
                          </div>';
                    }
                } catch (Exception $e) {
                    error_log('Payment processing error: ' . $e->getMessage());
                    $updateData = [
                        'notificationResponse' => json_encode(['error' => $e->getMessage()]),
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => 'error',
                    ];
                    $this->queryBuilder->update($tableName, $updateData, $where);
                    echo '<div class="col-md-12 text-center alert alert-danger">
                        <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</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';
        $reference             = $paymentRequest['txnId'];
        $declarationPaymentObj = new DeclarationPayment();
        $declarationPaymentObj->setConnection($this->conn, $connMain);
        $where                  = ['id' => $paymentRequest['paymentId']];
        $declarationPaymentInfo = $this->queryBuilder->selectById($tableName, '*', $where);

        if ($declarationPaymentInfo) {
            if ($declarationPaymentInfo['formSubmissionStatus'] != 1) {
                try {
                    $orderInfo  = $this->paygateObj->fetchOrder($declarationPaymentInfo);
                    $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'txnId'                => $orderInfo['txnID'],
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => $orderInfo['txnStatus'],
                    ];
                    $where = ['id' => $paymentRequest['paymentId']];

                    if ($orderInfo['Status'] === 'success') {
                        if ($orderInfo['reference'] === $reference && $orderInfo['txnStatus'] === 'Approved') {
                            $this->queryBuilder->update($tableName, $updateData, $where);
                            $declarationPaymentInfo['txnId'] = $orderInfo['txnID'];
                            $response                        = $declarationPaymentObj->createReceipt($declarationPaymentInfo);
                            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]", $orderInfo['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]", $orderInfo['txnID'], $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                                  </div>';
                            }
                        } else {
                            $this->queryBuilder->update($tableName, $updateData, $where);
                            echo '<div class="col-md-12 text-center alert alert-warning">
                                <h4>' . str_replace("[ORDER_STATUS]", $orderInfo['txnStatus'], $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                              </div>';
                        }
                    } else {
                        $this->queryBuilder->update($tableName, $updateData, $where);
                        echo '<div class="col-md-12 text-center alert alert-danger">
                            <h4>' . str_replace("[REFERENCE]", $orderInfo['reference'], $this->translationMsg['PAYMENT_ERROR']) . '</h4>
                          </div>';
                    }
                } catch (Exception $e) {
                    error_log('Payment processing error: ' . $e->getMessage());
                    $updateData = [
                        'notificationResponse' => json_encode(['error' => $e->getMessage()]),
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => 'error',
                    ];
                    $this->queryBuilder->update($tableName, $updateData, $where);
                    echo '<div class="col-md-12 text-center alert alert-danger">
                        <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</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';
        $reference = $paymentRequest['txnId'];
        $examObj   = new ExaminationPayment();
        $examObj->setConnection($this->conn, $connMain);
        $where    = ['id' => $paymentRequest['paymentId']];
        $examInfo = $this->queryBuilder->selectById($tableName, '*', $where);

        if ($examInfo) {
            if ($examInfo['formSubmissionStatus'] != 1) {
                try {
                    $orderInfo  = $this->paygateObj->fetchOrder($examInfo);
                    $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'txnId'                => $orderInfo['txnID'],
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => $orderInfo['txnStatus'],
                    ];
                    $where = ['id' => $paymentRequest['paymentId']];

                    if ($orderInfo['Status'] === 'success') {
                        if ($orderInfo['reference'] === $reference && $orderInfo['txnStatus'] === 'Approved') {
                            $this->queryBuilder->update($tableName, $updateData, $where);
                            $response = $examObj->createReceipt(
                                $examInfo['id'],
                                $examInfo['academyLocationId'],
                                $orderInfo['txnID'],
                                $examInfo['amount'],
                                $examInfo['currency']
                            );
                            if (isset($response['status']) && $response['status'] === 'SUCCESS') {
                                $updateData = ['receiptStatus' => $response['status']];
                                $this->queryBuilder->update($tableName, $updateData, $where);
                                $tableName2       = 'assessment_payment_detail';
                                $updateDataDetail = ['receiptId' => $response['receiptId']];
                                $updateWhere      = ['examAssessmentPaymentId' => $paymentRequest['paymentId']];
                                $this->queryBuilder->update($tableName2, $updateDataDetail, $updateWhere);
                                echo '<div class="col-md-12 text-center alert alert-success">
                                    <h4>' . str_replace("[TRANSACTION_ID]", $orderInfo['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]", $orderInfo['txnID'], $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                                  </div>';
                            }
                        } else {
                            $this->queryBuilder->update($tableName, $updateData, $where);
                            echo '<div class="col-md-12 text-center alert alert-warning">
                                <h4>' . str_replace("[ORDER_STATUS]", $orderInfo['transactionState'], $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                              </div>';
                        }
                    } else {
                        $this->queryBuilder->update($tableName, $updateData, $where);
                        echo '<div class="col-md-12 text-center alert alert-danger">
                            <h4>' . str_replace("[REFERENCE]", $orderInfo['payUReference'], $this->translationMsg['PAYMENT_ERROR']) . '</h4>
                          </div>';
                    }
                } catch (Exception $e) {
                    error_log('Payment processing error: ' . $e->getMessage());
                    $updateData = [
                        'notificationResponse' => json_encode(['error' => $e->getMessage()]),
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => 'error',
                    ];
                    $this->queryBuilder->update($tableName, $updateData, $where);
                    echo '<div class="col-md-12 text-center alert alert-danger">
                        <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</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';
        $reference = $paymentRequest['txnId'];
        $revalObj  = new RevaluationPayment();
        $revalObj->setConnection($this->conn, $connMain);
        $where     = ['id' => $paymentRequest['paymentId']];
        $revalInfo = $this->queryBuilder->selectById($tableName, '*', $where);
        if ($revalInfo) {
            if ($revalInfo['formSubmissionStatus'] != 1) {
                try {
                    $orderInfo  = $this->paygateObj->fetchOrder($revalInfo);
                    $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'txnId'                => $orderInfo['txnID'],
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => $orderInfo['txnStatus'],
                    ];
                    $where = ['id' => $paymentRequest['paymentId']];
                    $this->queryBuilder->update($tableName, $updateData, $where);
                    if ($orderInfo['Status'] === 'success') {
                        if ($orderInfo['reference'] === $reference && $orderInfo['txnStatus'] === 'Approved') {
                            $response = $revalObj->createReceipt(
                                $revalInfo['id'],
                                $revalInfo['amount'],
                                $orderInfo['txnID'],
                                $orderInfo['Status']
                            );
                            if (isset($response['status']) && $response['status'] === 'SUCCESS') {
                                $updateData = ['receiptStatus' => $response['status']];
                                $this->queryBuilder->update($tableName, $updateData, $where);
                                echo '<div class="col-md-12 text-center alert alert-success">
                                <h4>' . str_replace("[TRANSACTION_ID]", $orderInfo['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]", $orderInfo['txnID'], $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                              </div>';
                            }
                        } else {
                            echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>' . str_replace("[ORDER_STATUS]", $orderInfo['txnStatus'], $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                          </div>';
                        }
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-danger">
                        <h4>' . str_replace("[REFERENCE]", $orderInfo['reference'], $this->translationMsg['PAYMENT_ERROR']) . '</h4>
                      </div>';
                    }
                } catch (Exception $e) {
                    error_log('Payment processing error: ' . $e->getMessage());
                    $updateData = [
                        'notificationResponse' => json_encode(['error' => $e->getMessage()]),
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => 'error',
                    ];
                    $this->queryBuilder->update($tableName, $updateData, $where);
                    echo '<div class="col-md-12 text-center alert alert-danger">
                    <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</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';
        $reference          = $paymentRequest['txnId'];
        $sendPaymentLinkObj = new SendPaymentLinkPayment();
        $sendPaymentLinkObj->setConnection($this->conn, $connMain);
        $where               = ['id' => $paymentRequest['paymentId']];
        $sendPaymentLinkInfo = $this->queryBuilder->selectById($tableName, '*', $where);

        if ($sendPaymentLinkInfo) {
            if ($sendPaymentLinkInfo['formSubmissionStatus'] != 1) {
                try {
                    $orderInfo  = $this->paygateObj->fetchOrder($sendPaymentLinkInfo);
                    $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'txnId'                => $orderInfo['txnID'],
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => $orderInfo['txnStatus'],
                    ];
                    $where = ['id' => $paymentRequest['paymentId']];
                    $this->queryBuilder->update($tableName, $updateData, $where);

                    if ($orderInfo['Status'] === 'success') {
                        if ($orderInfo['reference'] === $reference && $orderInfo['txnStatus'] === 'Approved') {
                            $response = $sendPaymentLinkObj->createReceipt(
                                $sendPaymentLinkInfo['sendPaymentLinkId'],
                                $sendPaymentLinkInfo['onlinePaymentId'],
                                $orderInfo['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]", $orderInfo['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]", $orderInfo['txnID'], $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                              </div>';
                            }
                        } else {
                            echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>' . str_replace("[ORDER_STATUS]", $orderInfo['txnStatus'], $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                          </div>';
                        }
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-danger">
                        <h4>' . str_replace("[REFERENCE]", $orderInfo['reference'], $this->translationMsg['PAYMENT_ERROR']) . '</h4>
                      </div>';
                    }
                } catch (Exception $e) {
                    error_log('Payment processing error: ' . $e->getMessage());
                    $updateData = [
                        'notificationResponse' => json_encode(['error' => $e->getMessage()]),
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => 'error',
                    ];
                    $this->queryBuilder->update($tableName, $updateData, $where);
                    echo '<div class="col-md-12 text-center alert alert-danger">
                    <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</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';
        $reference         = $paymentRequest['txnId'];
        $advancePaymentObj = new AdvancePayment();
        $advancePaymentObj->setConnection($this->conn, $connMain);
        $where              = ['id' => $paymentRequest['paymentId']];
        $advancePaymentInfo = $this->queryBuilder->selectById($tableName, '*', $where);        
        if ($advancePaymentInfo) {
            if ($advancePaymentInfo['formSubmissionStatus'] != 1) {
                try {
                    $orderInfo  = $this->paygateObj->fetchOrder($advancePaymentInfo);
                    $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'txnId'                => $orderInfo['txnID'],
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => $orderInfo['txnStatus'],
                    ];
                    $where = ['id' => $paymentRequest['paymentId']];
                    $this->queryBuilder->update($tableName, $updateData, $where);

                    if ($orderInfo['Status'] === 'success') {
                        if ($orderInfo['reference'] === $reference && $orderInfo['txnStatus'] === 'Approved') {
                            $advancePaymentInfo['txnId'] = $orderInfo['txnID'];
                            $advancePaymentInfo['txnStatus'] = $orderInfo['txnStatus'];
                            $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]", $orderInfo['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]", $orderInfo['txnID'], $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                              </div>';
                            }
                        } else {
                            echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>' . str_replace("[ORDER_STATUS]", $orderInfo['txnStatus'], $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                          </div>';
                        }
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-danger">
                        <h4>' . str_replace("[REFERENCE]", $orderInfo['reference'], $this->translationMsg['PAYMENT_ERROR']) . '</h4>
                      </div>';
                    }
                } catch (Exception $e) {
                    error_log('Payment processing error: ' . $e->getMessage());
                    $updateData = [
                        'notificationResponse' => json_encode(['error' => $e->getMessage()]),
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => 'error',
                    ];
                    $this->queryBuilder->update($tableName, $updateData, $where);
                    echo '<div class="col-md-12 text-center alert alert-danger">
                    <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</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");
        $reference         = $paymentRequest['txnId'];
        $tableName = 'donation_payment';
        $donationObj = new DonationPayment();
        $donationObj->setConnection($this->conn, $connMain);
        $where               = ['id' => $paymentRequest['paymentId']];
        $donationInfo = $this->queryBuilder->selectById($tableName, '*', $where);        
        if ($donationInfo) {
            if ($donationInfo['formSubmissionStatus'] != 1) {
               try{               
                $orderInfo  = $this->paygateObj->fetchOrder($donationInfo);
                $updateData = [
                        'notificationResponse' => json_encode($orderInfo['jsonResponse']),
                        'txnId'                => $orderInfo['txnID'],
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => $orderInfo['txnStatus'],
                    ];
                $where = ['id' => $paymentRequest['paymentId']];
                $this->queryBuilder->update($tableName, $updateData, $where);
                if ($orderInfo['Status'] === 'success') {                    
                    if ($orderInfo['reference'] === $reference && $orderInfo['txnStatus'] === 'Approved') {
                           $donationInfo['txnId'] = $orderInfo['txnID'];         
                             $response = $donationObj->createReceipt($donationInfo, 'TXN_SUCCESS');
                            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]", $orderInfo['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]", $orderInfo['txnID'], $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']) . '</h4>
                              </div>';
                            }
                        } else {
                            echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>' . str_replace("[ORDER_STATUS]", $orderInfo['txnStatus'], $this->translationMsg['TRANSACTION_NOT_SUCCESS']) . '</h4>
                          </div>';
                        }
                  
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-danger">
                        <h4>' . str_replace("[REFERENCE]", $orderInfo['reference'], $this->translationMsg['PAYMENT_ERROR']) . '</h4>
                      </div>';
                    }
                } catch (Exception $e) {
                    error_log('Payment processing error: ' . $e->getMessage());
                    $updateData = [
                        'notificationResponse' => json_encode(['error' => $e->getMessage()]),
                        'formSubmissionStatus' => 1,
                        'paymentStatus'        => 'error',
                    ];
                    $this->queryBuilder->update($tableName, $updateData, $where);
                    echo '<div class="col-md-12 text-center alert alert-danger">
                    <h4>' . $this->translationMsg['TRANSACTION_ERROR'] . '</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>';
        }
    }

}
