<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
?>
<?php $cryptoPaymentEnable = false; ?>
<div class="layout_middle">
  <div class="generic_layout_container layout_core_content">  
    <?php if( $this->status == 'pending' ): // Check for pending status ?>
      <?php echo $this->translate("Your subscription is pending payment. You will receive an email when the payment completes."); ?>
    <?php else: ?>
      <?php 
          $settings = Engine_Api::_()->getApi('settings', 'core'); 
          $currentCurrency = $settings->getSetting('payment.currency', 'USD');
      ?>
      <div class="payment_process_gateway">
        <form method="post" action="<?php echo $this->escape($this->url(array('action' => 'process'))) ?>" enctype="application/x-www-form-urlencoded">
          <h3><?php echo $this->translate('Subscription Plan Confirmation') ?></h3>
          <div class="payment_process_gateway_content">  
            <?php if( $this->package->recurrence ): ?>
            <p class="form-description">
              <?php echo $this->translate('You have selected an account type that requires ' .
                'recurring subscription payments. You will be taken to a secure ' .
                'checkout area where you can setup your subscription. Remember to ' .
                'continue back to our site after your purchase to sign in to your ' .
                'account.') ?>
            </p>
            <?php endif; ?>
            <p>
              <?php $stripCheck = true; ?>
              <?php if( $this->package->recurrence ): ?>
                <?php $stripCheck = $this->package->isPackageRecurrence(); ?>
                <?php echo $this->translate('Please setup your subscription to continue:') ?>
              <?php else: ?>
                <?php echo $this->translate('Please pay a one-time fee to continue:') ?>
              <?php endif; ?>
              <span>
                <?php echo $this->package->getPackageDescription() ?>
              </span>
            </p>
            <div class="payment_process_options payment_process_gateway_buttons">
              <?php $currencyData = Engine_Api::_()->getDbTable('currencies', 'payment')->getCurrency(Engine_Api::_()->payment()->getCurrentCurrency()); 
              $allowedGateways = json_decode($currencyData->gateways);
              ?>
              <?php if(engine_count($allowedGateways) > 0) { ?>
                <?php foreach( $this->gateways as $gatewayInfo ):
                  $gateway = $gatewayInfo['gateway'];
                  $plugin = $gatewayInfo['plugin'];
                  $config = (array) $gateway['config'];
                  $gatewayObject = $gateway->getGateway();
                  $supportedCurrencies = $gatewayObject->getSupportedCurrencies();
                  if(!engine_in_array($currentCurrency,$supportedCurrencies))
                    continue;
                  if(!engine_in_array($gateway->gateway_id , $allowedGateways))
                    continue;
									if( $this->package->recurrence && empty($gateway->is_recurring)) continue;
                  if($gatewayInfo['plugin'] instanceof Sesadvpmnt_Gateways_Stripe) continue;
									if($gatewayInfo['plugin'] instanceof Engine_Payment_Gateway_Coinpayment){
										$cryptoPaymentEnable = true;
										$cryptoConfig = $config;
									?>
									<input type="hidden" name="currency" id="crypto_currency" />
									<?php 
									}
									?>
                <div class="payment_process_gateway_list">
                  <?php if($gateway->plugin == 'Payment_Plugin_Gateway_Wallet') { ?>
                    <?php if($this->user && $this->user->wallet_amount > 0 && $this->user->wallet_amount >= $this->package->price) { ?>
                    	<label class="payment_process_item" for="payment_btn_<?php echo $gateway->gateway_id; ?>" type="button" data-bs-toggle="modal" data-bs-target="#wallet_modal">
                    <?php } else { ?>
											<label for="payment_btn_<?php echo $gateway->gateway_id; ?>" class="payment_process_item payment_process_gateway_btn" type="button" name="execute" onclick="checkGatewayId(<?php echo $gateway->gateway_id ?>,this);">
                    <?php } ?>
                  <?php } else { ?>
                  <label for="payment_btn_<?php echo $gateway->gateway_id; ?>" class="payment_process_item payment_process_gateway_btn" type="button" name="execute" <?php echo $cryptoPaymentEnable ? "data-coinpayment='true'" : "" ?> onclick="checkGatewayId(<?php echo $gateway->gateway_id ?>,this);">
                  <?php } ?>
										<?php if(isset($config['icon']) && !empty($config['icon'])) { ?>
											<?php $path = Engine_Api::_()->core()->getFileUrl($config['icon'], true); ?>
											<img class="payment_process_icon" src="<?php echo $path['image']; ?>" alt="<?php echo $path['alt_text'] ? $path['alt_text'] : 'img'; ?>">
										<?php } else if(isset($gateway->default_icon) && !empty($gateway->default_icon)) { ?>
											<i class="payment_process_icon">
												<?php echo $gateway->default_icon; ?>
											</i>
										<?php } ?>
                    <div class="payment_process_item_inner">
                      <span><?php echo $this->translate('Pay with %1$s', $this->translate($gateway->title)) ?></span>
                      <div class="payment_toggle_btn">
                        <input id="payment_btn_<?php echo $gateway->gateway_id; ?>" type="radio" name="gateway_select" value="<?php echo $gateway->gateway_id; ?>">
                      </div>
                    </div>
									</label>
                  <button id="gatewayButton" type="submit" name="gatewayButton" style="display:none;"></button>
                </div>
                <?php endforeach; ?>
              <?php } ?>
              <button class="payment_process_submit payment_process_gateway_button_submit"><?php echo $this->translate("Continue"); ?></button>
            </div>
          </div>
          <input type="hidden" name="gateway_id" id="gateway_id" value="" />
        </form>
      </div>
			<script type="text/javascript">
				function checkGatewayId(gatewayId,obj) {					
					scriptJquery('#gateway_id').val(gatewayId);
          cryptoPayment();
						return;
					// if(scriptJquery("#crypto_currency_select").children().length == 1){
					// 	cryptoPayment();
					// 	return;
					// }

					// scriptJquery(".coinpayment").show();
					
					// if(scriptJquery(obj).attr("data-coinpayment")) {
					// 	// show option
					// 	scriptJquery("#openCryptoPopup").trigger("click");
					// 	return;
					// }
					// scriptJquery('#gatewayButton').trigger('click');
				}
			</script>
    <?php endif; ?>
  </div>
</div>

<?php if($cryptoPaymentEnable){ ?>
  <?php include_once APPLICATION_PATH . "/application/modules/Coinpayments/views/scripts/_paymentPopUp.tpl"; ?>
<?php } ?>

<!-- wallet Modal Poup -->
<div id="wallet_modal_data">
  <div class="modal fade wallet_modal" id="wallet_modal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"  aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content position-relative" id="pay_wallet_form">
        <?php if($this->user) { ?>
          <form action="<?php echo $this->escape($this->url(array('module'=> 'user','controller' => 'subscription', 'action' => 'choose', 'user_id' => $this->user->getIdentity()),'default',true)) ?>" method="post" id="wallet_payment" enctype="multipart/form-data">
        <?php } else { ?>
          <form action="<?php echo $this->escape($this->url(array('module'=> 'user','controller' => 'subscription', 'action' => 'choose'),'default',true)) ?>" method="post" id="wallet_payment" enctype="multipart/form-data">
        <?php } ?>
          <div class="modal-header">
            <h5 class="modal-title fs-5"><?php echo $this->translate('Subscription Plan Confirmation') ?></h5>
          </div>
          <div class="modal-body">
            <p class="mb-3" id="modal_description"><?php echo $this->translate('Are you sure you want to subscribe to the selected plan? Please click "Proceed to Pay" button to continue and complete your payment.') ?></p>
            <div style="display:none;" id="error_message" class="failed_msg mt-2"></div>
          </div>
          <div class="modal-footer">
            <input type="hidden" name="selected_package_id" id="selected_package_id" value="<?php echo $this->package->getIdentity(); ?>" />
            <button type="button" id="wallet_cancel" class="btn btn-link" data-bs-dismiss="modal"><?php echo $this->translate("Cancel"); ?></button>
            <button type="submit" id="submit" class="btn btn-primary"><?php echo $this->translate('Proceed to Pay'); ?></button>
          </div>
        </form>
        <div class="core_loading_cont_overlay" id="core_loading_cont_overlay" style="display:none;"></div>
      </div>
    </div>
  </div>
</div>

<script type='text/javascript'>
  AttachEventListerSE('submit', '#wallet_payment', function(e) {
    e.preventDefault();
    scriptJquery("#core_loading_cont_overlay").show();
    scriptJquery.ajax({
      dataType: 'json',
      url: en4.core.baseUrl + 'payment/subscription/choose',
      method: 'post',
      data: {
        format: 'json',
        user_id: '<?php echo $this->user ? $this->user->getIdentity() : 0; ?>',
        package_id: scriptJquery('#selected_package_id').val(),
				using_wallet: true,
      },
      success: function(response) {
        scriptJquery("#core_loading_cont_overlay").hide();
        if(response.status) {
          scriptJquery('#wallet_payment').hide();
          scriptJquery('#pay_wallet_form').append("<div id='success_msg' class='success_msg success_msg m-2'><span>"+response.message+"</span></div>");
          setTimeout(() => {
            scriptJquery('#wallet_cancel').trigger('click');
            scriptJquery('#pay_wallet_form').hide();
            window.proxyLocation.reload("full");
          }, 2000);
        } else {
          scriptJquery('#error_message').show().html(response.message);
          setTimeout(() => {
            if(response.url) {
              loadAjaxContentApp(response.url);
            }
          }, 2000);
        } 
      }
    });
  });

  en4.core.runonce.add(function() {

    scriptJquery(scriptJquery('#wallet_modal_data').html()).appendTo('#append-script-data');
    scriptJquery('#wallet_modal_data').remove();

    //Reload modal window
    scriptJquery(scriptJquery('#reload_modal_data').html()).appendTo('#append-script-data');
    scriptJquery('#reload_modal_data').remove();

    scriptJquery("#wallet_modal").on('hide.bs.modal', function(){
      scriptJquery('#error_message').hide();
      scriptJquery('#selected_package_id').val('');
    });
  });

	AttachEventListerSE('click', '.payment_process_gateway_button_submit', function(e) {
		e.preventDefault();
		var gatewayId = scriptJquery('#gateway_id').val();
		
		if (!gatewayId) {
			return;
		}

		if(gatewayId != 3000) { 
			if(scriptJquery("#crypto_currency_select").children().length == 1){
				cryptoPayment();
				return;
			}

			scriptJquery(".coinpayment").show();
			
			if(scriptJquery(this).attr("data-coinpayment")) {
				// show option
				scriptJquery("#openCryptoPopup").trigger("click");
				return;
			}
		}
		
		if(gatewayId == 3000) { 
			loadAjaxContentApp("<?php echo $this->url(array('module' => 'user', 'controller' => 'wallet', 'action' => 'gateway'), 'default', true); ?>",false,"full");
		} else {
			scriptJquery('#gatewayButton').trigger('click');
		}
	});
</script>