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

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

$queryBuilder = new QueryBuilder($conn);
$gatewayConfig = new GatewayConfig();


if ((count($_REQUEST) == 0) || (!isset($_REQUEST['id'])) || (isset($_REQUEST['id']) && $_REQUEST['id'] == 0)) {
  echo '<div class="col-md-12 text-center alert alert-warning">
            <h4>'.$translationMsg['TRANSACTION_ERROR'].'</h4>
            </div>';
} else {
  $tableName = 'reval_payment';
  $where = ['id' => $_REQUEST['id']];
  $result = $queryBuilder->selectById($tableName, '*', $where);
  if ($result) {
    $activeGateways = $gatewayConfig->getActiveGateway($result['academyLocationId']); // Get the active gateways
    $tableName2 = 'reval_payment_detail';
    $where2 = ['examRevalPaymentId' => $result['id']];
    $result2 = $queryBuilder->selectById($tableName2, '*', $where2);
    if ($result2) {
      // 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
          $result['paymentOption'] = $selectedGateway['value']; // Store selected gateway value
          $revalObj = new RevaluationPayment();
          $result['academyLocationId'] = $revalObj->getStudentDetails($result2['studentId']);
          if(isset($result['currency']) && $result['currency'] == 'R' && $selectedGateway['value'] == 'payu' || $selectedGateway['value'] == 'paygate')
          {
              $result['currency'] = 'ZAR';
          }
          $merchantDetails = $revalObj->getStandardMerchantDetailsByAl($selectedGateway['value'], $result['academyLocationId'],$result['currency']);

          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, 'revaluation-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'] . '">
                  <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>';
    }
  } else {
    echo '<div class="col-md-12 text-center alert alert-warning">
    <h4>'.$translationMsg['TRANSACTION_DATA_NOT_FOUND'].'</h4>
    </div>';
  }
}

require_once("footer.php");
