<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

add_action( 'plugins_loaded', 'cryptoniq_payment_gateway_init' );

function cryptoniq_payment_gateway_init() {
	if ( ! class_exists( 'WC_Payment_Gateway' ) ) return;

	class Cryptoniq_Gateway extends WC_Payment_Gateway {
		public function __construct() {
			$this->id = CRYPTONIQ_PAY_ID;
			$this->method_title = 'Cryptoniq';
			$this->method_description = __( 'Pay with cryptocurrencies.', 'cryptoniq' );
			$this->has_fields = false;
			$this->icon = CRYPTONIQ_DIR_URL . 'assets/images/cryptoniq.logo.png';

			$this->init_form_fields();
			$this->init_settings();

			$this->title = 'Cryptoniq';
			$this->description = class_exists( 'Redux' ) && Redux::get_option( CRYPTONIQ_OPTION, 'description' )
				? Redux::get_option( CRYPTONIQ_OPTION, 'description' )
				: __( 'Pay with cryptocurrencies.', 'cryptoniq' );

			$this->is_enabled();

			add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, [ $this, 'process_admin_options' ] );
		}

		public function init_form_fields() {
			$this->form_fields = [
				'enabled' => [
					'title'   => __( 'Enable Cryptoniq Gateway', 'cryptoniq' ),
					'type'    => 'checkbox',
					'label'   => __( 'Enable Cryptoniq payment method', 'cryptoniq' ),
					'default' => 'no',
				],
			];
		}

		public function admin_options() {
			echo '<h3>Cryptoniq</h3>';
			echo '<table class="form-table">';
			echo $this->generate_settings_html();
			echo '</table>';
		}

		public function payment_fields() {
			if ( ! function_exists( 'cryptoniq_get_payment_coins' ) ) return;

			$coins = cryptoniq_get_payment_coins();
			if ( empty( $coins ) ) return;

			echo '<div id="cryptoniq-pgateway" class="cryptoniq-border-box">';
			echo '<div class="cryptoniq-pgateway-selectors">';
			
			$line_break = cryptoniq_get_option('coins_type_break');

			$coin_counts = [
				'USDT' => 0,
				'USDC' => 0,
			];

			foreach ( $coins as $coin => $enabled ) {
				if ( ! $enabled ) continue;

				$coin_data = cryptoniq_get_coin_data( $coin, 'name' );
				$price     = cryptoniq_get_price( $coin, WC()->cart->get_total( 'edit' ), '', false, false );

				$css_classes = [
					'cryptoniq-pgateway-input-item',
					'cryptoniq-pgateway-input-item-' . strtolower( $coin ),
				];

				foreach ( ['USDT', 'USDC'] as $stable) {
					if ( str_contains( $coin, $stable ) ) {
						$coin_counts[$stable]++;
						$css_classes[] = 'cryptoniq-pgateway-type-stables';
						$css_classes[] = 'cryptoniq-pgateway-type-stable-' . strtolower($stable);
						if ( $coin_counts[$stable] === 1 && $line_break ) {
							echo '<div class="cryptoniq-pgateway-input-breaker"></div>';
						}
					}
				}

				$css = esc_attr( implode( ' ', $css_classes ) );
				$coin_attr = esc_attr( $coin );
				$name_attr = esc_attr( $coin_data );
				$price_attr = esc_attr( $price );

				printf(
					'<input type="radio" id="cryptoniq-coin-%1$s" class="cryptoniq-pgateway-input" name="cryptoniq_coin_ticker" value="%1$s" />',
					$coin_attr
				);
				printf(
					'<label for="cryptoniq-coin-%1$s" class="%2$s" data-coin-name="%3$s" data-price="%4$s"></label>',
					$coin_attr, $css, $name_attr, $price_attr
				);
			}

			echo '</div>';
			echo '<div id="cryptoniq-pgateway-coin-price"></div>';

			if ( $this->description ) {
				echo '<p class="cryptoniq-pgateway-descr">' . esc_html( $this->description ) . '</p>';
			}

			echo '</div>'; // Close cryptoniq-pgateway
			?>

			<script>
			(function ($) {
				$(document).ready(function () {
					var $price = $('#cryptoniq-pgateway-coin-price');
					$('.cryptoniq-pgateway-input-item').on('click', function () {
						const name = $(this).data('coin-name');
						const price = $(this).data('price');
						$price.text(name + ': ' + price);
					}).first().click();
				});
			})(jQuery);
			</script>

			<?php
		}

		public function process_payment( $order_id ) {
			$order = wc_get_order( $order_id );
			if ( ! $order ) return;

			WC()->cart->empty_cart();

			$redirect = $order->get_checkout_payment_url( true );

			return [
				'result'   => 'success',
				'redirect' => $redirect,
			];
		}

		public function is_enabled() {
			if ( class_exists( 'Redux' ) ) {
				Redux::set_option(
					CRYPTONIQ_OPTION,
					'cryptoniq_panel_activate',
					$this->get_option( 'enabled' ) === 'yes' ? 'yes' : 'no'
				);
			}
		}
	}

	add_filter( 'woocommerce_payment_gateways', function( $methods ) {
		$methods[] = 'Cryptoniq_Gateway';
		return $methods;
	} );
}