<?php
namespace SabaiApps\Directories\Component\PaymentGateway\Gateway;

use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Payment\IOrder;
use SabaiApps\Directories\Component\Payment\IPlan;
use SabaiApps\Directories\Context;

class ManualPaymentGateway extends AbstractGateway {

	protected function _paymentGatewayInfo() {
		return array(
			'label'            => __( 'Manual Payment', 'directories-pro' ),
			'default_settings' => array(
				'checkout_btn_label' => __( 'Place order', 'directories-pro' ),
				'instructions'       => null,
			),
			'plan_types'       => array( 'base', 'addon' ),
		);
	}

	public function paymentGatewaySettingsForm( array $settings, array $parents ) {
		return array(
			'checkout_btn_label' => array(
				'#title'         => __( 'Checkout button label', 'directories-pro' ),
				'#type'          => 'textfield',
				'#default_value' => $settings['checkout_btn_label'],
				'#placeholder'   => $this->paymentGatewayInfo( 'default_settings' )['checkout_btn_label'],
			),
			'instructions'       => array(
				'#title'                 => __( 'Payment instructions', 'directories-pro' ),
				'#type'                  => 'textarea',
				'#default_value'         => $settings['instructions'],
				'#rows'                  => 5,
				'#description'           => $this->_application->System_Util_availableTags( array( '%order_amount%', '%order_date%', '%order_id%' ) ),
				'#description_no_escape' => true,
			),
		);
	}

	public function paymentGatewayCheckoutForm( Context $context, $planOrOrder, ?IEntity $entity = null, $action = null, array $parents = array(), $discountCodesFormFieldName = null ) {
		$settings     = $this->_getSettings();
		$button_id    = 'drts-payment-checkout-manual-payment-button';
		$redirect_url = $this->_getCheckoutActionUrl( 'order', $context );
		return array(
			'#type'     => 'item',
			'#markup'   => '<div class="' . DRTS_BS_PREFIX . 'd-grid"><button class="' . DRTS_BS_PREFIX . 'btn ' . DRTS_BS_PREFIX . 'btn-lg ' . DRTS_BS_PREFIX . 'btn-primary" id="' . $button_id . '">'
				. $this->_application->H( $settings['checkout_btn_label'] )
				. '</button></div>',
			'#js_ready' => '
document.getElementById("' . $button_id . '").addEventListener("click", function(e) {
    var $this = $(this);
    e.preventDefault();
    $this.prop("disabled", true);
    var form = document.createElement("form");
    form.method = "POST";
    form.action = "' . $redirect_url . '";
    $this.closest("form").find("[name=\'' . $discountCodesFormFieldName . '[]\']").map(function() {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = "' . $discountCodesFormFieldName . '[]";
        input.value = $(this).val();
        form.appendChild(input);
    });
    document.body.appendChild(form);
    form.submit();
});',
		);
	}

	public function paymentGatewayOnCheckoutAction( Context $context, $checkoutAction, $planOrOrder = null, ?IEntity $entity = null, $action = null, array $discountCodes = array() ) {
		switch ( $checkoutAction ) {
			case 'order':
				if ( $planOrOrder instanceof IOrder ) {
					$order = $planOrOrder->getOrder();
				} elseif ( $planOrOrder instanceof IPlan ) {
					if ( ! $order = $this->_createOrder( $planOrOrder, $entity, $action, $discountCodes ) ) {
						return false;
					}
				} else {
					return false;
				}

				$context->paymentgateway_checkout_order_id = $order->getId();
				return true;
		}
	}

	public function paymentGatewayOrderNotices( IEntity $order ) {
		if ( $order->getSingleFieldValue( 'paymentgateway_order', 'status' ) !== 'pending_payment' ) {
			return;
		}

		$settings = $this->_getSettings();
		if ( ! isset( $settings['instructions'] ) || ! strlen( $settings['instructions'] ) ) {
			return;
		}

		$instructions = $settings['instructions'];
		if ( strpos( $instructions, '%' ) ) {
			$instructions = strtr(
				$instructions,
				array(
					'%order_amount%' => $this->_application->PaymentGateway_Order_totalAmount( $order ),
					'%order_date%'   => $this->_application->System_Date( $order->getTimestamp() ),
					'%order_id%'     => $order->getId(),
				)
			);
		}

		return array(
			'instructions' => array(
				'level'   => 'info',
				'message' => $instructions,
			),
		);
	}
}
