<?php
/**
 * Class AP_Banner file.
 *
 * @package Addonpayments
 */

use ComerciaGlobalPayments\AddonPayments\SDK\Api\EPGJs;

defined( 'ABSPATH' ) || exit;

/**
 * Callback Controller
 */
class AP_Banner {

	/**
	 * Addonpayments Gateway.
	 *
	 * @var \WC_Gateway_EasyPaymentGateway
	 */
	private $gateway;

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'init', array( $this, 'init' ) );
	}

	/**
	 * Set Addonpayments Gateway property and register hooks.
	 *
	 * @return void
	 */
	public function init() {
		$payment_gateways = WC()->payment_gateways()->get_available_payment_gateways();

		if ( ! isset( $payment_gateways[ ID_EPG ] ) ) {
			return;
		}

		$this->gateway = $payment_gateways[ ID_EPG ];

		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'woocommerce_after_cart_totals', array( $this, 'banner_div' ) );
		add_action( 'wp_ajax_nopriv_get-authorization', array( $this, 'get_authorization' ) );
		add_action( 'wp_ajax_get-authorization', array( $this, 'get_authorization' ) );

		if ( ! isset( $this->gateway->settings['banner_position'] ) || 1 === (int) $this->gateway->settings['banner_position'] ) {
			add_action( 'woocommerce_single_product_summary', array( $this, 'banner_div' ), 11 );
		} else {
			add_action( 'woocommerce_after_add_to_cart_form', array( $this, 'banner_div' ) );
		}
	}

	/**
	 * Enqueue styles and scripts.
	 *
	 * @return void
	 */
	public function enqueue_scripts() {
		if ( is_cart() || is_product() ) {
			if ( ! isset( $this->gateway ) ) {
				return;
			}
			if ( empty( $this->gateway->settings['merchant_id'] ) &&
				empty( $this->gateway->settings['api_key'] ) &&
				empty( $this->gateway->settings['password'] ) &&
				empty( $this->gateway->settings['product_id'] ) ) {
				return;
			}

			global $woocommerce;

			if ( is_product() ) {
				$price = $this->get_single_product_price();
			}

			$endpoints = EPGJs::getEndpoints( 'yes' === $this->gateway->settings['live_mode'] );
			$amount    = is_cart() ? $woocommerce->cart->total : $price;
			$auth      = $this->gateway->get_authorization();

			wp_enqueue_script( 'nemuru-widget-js', esc_url( $endpoints['nemuru-widget'] ), array( 'jquery' ), ADDONPAYMENTS_VERSION, true );
			wp_enqueue_script( 'addonpayments-front', esc_url( plugins_url( 'assets/js/front.js', ADDONPAYMENTS_PLUGIN_FILE ) ), array( 'jquery' ), ADDONPAYMENTS_VERSION, true );
			wp_enqueue_style( 'addonpayments-front', esc_url( plugins_url( 'assets/css/front.css', ADDONPAYMENTS_PLUGIN_FILE ) ), false, ADDONPAYMENTS_VERSION );
			$style_color = $this->gateway->settings['banner_style_color'] ? $this->gateway->settings['banner_style_color'] : '#34aeeb';

			wp_localize_script(
				'addonpayments-front',
				'addonpayments',
				array(
					'url'        => admin_url( 'admin-ajax.php' ),
					'nonce'      => wp_create_nonce( 'addonpayments-nonce' ),
					'action'     => 'get-authorization',
					'baseUrl'    => $endpoints['base'],
					'locale'     => str_replace( '_', '-', get_user_locale() ),
					'customerId' => $this->gateway->get_customer_id(),
					'amount'     => $amount,
					'currency'   => get_woocommerce_currency(),
					'authToken'  => $auth,
					'banner'     => array(
						'product'       => $this->gateway->settings['type_financing'],
						'styleColor'    => $style_color,
						'styleVariant'  => $this->gateway->settings['banner_style_variant'],
						'styleBranding' => $this->gateway->settings['banner_style_branding'],
						'position'      => $this->gateway->settings['banner_position'],
					),
				)
			);
		}
	}

	/**
	 * Show banner div.
	 *
	 * @return void
	 */
	public function banner_div() {
		$data = '';
		if ( is_cart() ) {
			global $woocommerce;
			$total = $woocommerce->cart->get_totals()['total'];
			$data  = "data-amount={$total}";
		}

		if ( is_product() ) {
			$price = $this->get_single_product_price();
			$data  = "data-amount={$price}";
		}
		echo wp_kses(
			'<div id="addon-payments-widget" ' . $data . '></div>',
			array(
				'div' => array(
					'id' => array(),
					'data-amount' => array()
				),
			)
		);
	}

	/**
	 * Return single product price.
	 *
	 * @return float|int|string
	 */
	public function get_single_product_price() {
		global $product;
		$price   = 0;
		$product = wc_get_product();

		if ( $product->is_type( 'simple' ) ) {
			$price = wc_get_price_including_tax( $product );

		} elseif ( $product->is_type( 'grouped' ) ) {
			$less_price = 0;
			$children   = $product->get_children();
			foreach ( $children as $value ) {
				$_product = wc_get_product( $value );
				$price    = wc_get_price_including_tax( $_product );

				if ( 0 === $less_price || $price < $less_price ) {
					$less_price = $price;
				}
			}
			$price = $less_price;
		} elseif ( $product->is_type( 'variable' ) ) {
			$price = $product->get_variation_sale_price( 'min', true );
		}

		return $price;
	}

	/**
	 * Get authorization token
	 *
	 * @return void
	 */
	public function get_authorization() {
		if ( ! isset( $this->gateway ) ) {
			return;
		}
		$auth = $this->gateway->get_authorization();
		wp_send_json( $auth );
		wp_die();
	}

}
