<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once("header.php");
include("./academia/declarationPayment.php");
require_once("./config/QueryBuilder.php");
require_once("./config/gatewayConfig.php");

$queryBuilder = new QueryBuilder($conn);
$gatewayConfig = new GatewayConfig();
$translationMsg = json_decode(TRANSLATION_MSG, true);
if ((count($_REQUEST) == 0) || (!isset($_REQUEST['id']) || !isset($_REQUEST['academyLocationIds']))) {
    
    echo '<div class="col-md-12 text-center alert alert-warning">
                   <h4>'.$translationMsg['TRANSACTION_ERROR'].'</h4>
                </div>';
}
else{
    $tableName = 'declaration_payment';
    $where = ['id'=>$_REQUEST['id']];
    $result = $queryBuilder->selectById($tableName,'*',$where);

    if ($result) {
        $activeGateways = $gatewayConfig->getActiveGateway($_REQUEST['academyLocationIds']);
        // If the form is submitted
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['paymentGateway'])) {
            // Get the selected gateway from the POST request
            $selectedGatewayValue = $_POST['paymentGateway'];

            // Get the gateway details by its code
            $selectedGateway = null;
            foreach ($activeGateways as $gateway) {
                if ($gateway['value'] == $selectedGatewayValue) {
                    $selectedGateway = $gateway;
                    break;
                }
            }

            if ($selectedGateway) {
                // Proceed with the payment process using the selected gateway
                $gatewayConfig->set_session($selectedGatewayValue);  
                $result['academyLocationId'] = $_REQUEST['academyLocationIds'];
                $result['paymentOption'] = $selectedGateway['value']; // Store selected gateway value
                $costCenter = $result['feeHead'];  // Get Cost Center Id From feeHeadField and Pass it to   getStandardMerchantDetailsByAl()  
                $costCenterArr = is_string($costCenter) ? json_decode($costCenter, true) : $costCenter;
                $costCenterId = isset($costCenterArr['costCentreId']) ? $costCenterArr['costCentreId'] : '';
                if(isset($result['currency']) && $result['currency'] == 'R' && $selectedGateway['value'] == 'payu' || $selectedGateway['value'] == 'paygate')
                {
                    $result['currency'] = 'ZAR';
                }
                $declarationPaymentObj = new DeclarationPayment();
                $merchantDetails = $declarationPaymentObj->getStandardMerchantDetailsByAl($selectedGateway['value'],$result['academyLocationId'],$result['currency'] , $costCenterId);
              
                if($merchantDetails == 'ACCESS_TOKEN')
                {
                    echo '<div class="col-md-12 text-center alert alert-warning">
                                <h4>'.$translationMsg['SERVER_ERROR'].'</h4>
                            </div>';
                }
                else if($merchantDetails == 'No_DATA')
                {
                    echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>'.$translationMsg['MERCHANT_DETAILS_NOT_CONFIGURED'].'</h4>
                        </div>';
                }else{                 
                    
                    require_once('./config/paymentGatewayLoader.php');
                    try {
                        $gatewayLoader = new PaymentGatewayLoader();
                        $gatewayLoader->loadPaymentGateway(strtolower($selectedGateway['value']), $conn, 'declaration-payment', $result, $tableName,$merchantDetails[strtolower($selectedGateway['value'])]);
                    } catch (Exception $e) {
                        echo '<div class="col-md-12 text-center alert alert-warning">
                                <h4>'.$translationMsg['TRANSACTION_ERROR'].'</h4>
                              </div>';
                    }
                }
                // Now, call the payment gateway loader or other functions to process the payment
            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>'.$translationMsg['INVALID_PAYMENT_GATEWAY_SELECTED'].'</h4>
                      </div>';
            }
        } else {
            // Check if there's only one active gateway
             if (count($activeGateways) === 1) {
                 $singleGateway = reset($activeGateways); // Get the first (and only) gateway
                 if ($singleGateway['activeStatus'] && strtolower($singleGateway['value']) !== 'grayquest') {
                     echo '<form id="autoSubmitForm" method="POST" action="' . $_SERVER['PHP_SELF'] . '?id=' . $_REQUEST['id'] . '&academyLocationIds=' . $_REQUEST['academyLocationIds'] . '">';
                     echo '<input type="hidden" name="paymentGateway" value="' . $singleGateway['value'] . '">';
                     echo '</form>';
 
                     // Add JavaScript to auto-submit the form
                     echo '<script>document.getElementById("autoSubmitForm").submit();</script>';
                     exit; // End the script to prevent rendering the rest of the form
                 }
             }
            
             if(count($activeGateways) > 1){
                 echo '<div class="container d-flex justify-content-center align-items-center min-vh-100">
                     <div class="card main-card-apyment p-4" style="max-width: 600px;width: 100%;margin:auto;padding: 3rem;margin-top:5%;border:1px solid #eee;">
                     <h3 class="text-center mb-4" style="margin-top:0;">Select Payment Gateway</h3>
                     <form method="POST" action="' . $_SERVER['PHP_SELF'] . '?id=' . $_REQUEST['id'] . '&academyLocationIds=' . $_REQUEST['academyLocationIds'] . '">
                         <div class="row payment-row">';
                         foreach ($activeGateways as $gateway) {
                             if ($gateway['activeStatus'] && strtolower($gateway['value']) !== 'grayquest') {
                                 echo '<div class="col-md-6">
                                     <label class="payment-option">
                                     <input required type="radio" name="paymentGateway" value="'.$gateway['value'].'" id="gateway' . $gateway['id'] . '">
                                     <span>'.ucfirst($gateway['value']).'</span>
                                     <img src="assets/image/'.$gateway['value'].'.png" alt="'.$gateway['value'].'">
                                     </label>
                                 </div>';
                             }
                         }
                      
                        
                         echo '</div>
                         <div class="text-center mt-4">
                         <button type="submit" class="btn btn-primary">Proceed with Payment</button>
                         </div>
                     </form>
                     </div>
                 </div>';
             }
 
         }
     } else {
         echo '<div class="col-md-12 text-center alert alert-warning">
                      <h4>'.$translationMsg['TRANSACTION_ERROR'].'</h4>
                 </div>';
     }
 }
require_once("footer.php");
