<?php
//Igual no deberías poder abrirme
defined( 'ABSPATH' ) || exit;

use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;

/**
 * Bank Transfer (BACS) payment method integration
 *
 * @since 3.0.0
 */
final class Cetelem_Blocks extends AbstractPaymentMethodType {
    /**
	 * Payment method name/id/slug (matches id in WC_Gateway_BACS in core).
	 *
	 * @var string
	 */
	protected $name = 'cetelem';

	/**
	 * An instance of the Asset Api
	 *
	 * @var Api
	 */
	private $asset_api;
    
    /**
	 * The gateway instance.
	 *
	 * @var WC_Gateway_Dummy
	 */
    private $gateway;

    /**
	 * Initializes the payment method type.
	 */
	public function initialize() {
        $this->settings = get_option( 'woocommerce_cetelem_settings', [] );
        $gateways       = WC()->payment_gateways->payment_gateways();
		$this->gateway  = $gateways[ $this->name ];
	}

	/**
	 * Returns if this payment method should be active. If false, the scripts will not be enqueued.
	 *
	 * @return boolean
	 */
	public function is_active() {
		return $this->gateway->is_available();
	}

	/**
	 * Returns an array of scripts/handles to be registered for this payment method.
	 *
	 * @return array
	 */
	public function get_payment_method_script_handles() {
		wp_register_script(
			'wc-cetelem-blocks',
			plugin_dir_url( __DIR__ ) . 'assets/js/checkout.js',
            [
                'wc-blocks-registry',
                'wc-settings',
                'wp-element',
                'wp-html-entities',
                'wp-i18n',
            ],
            '3.2.0',
            true
		);
        
		if ( function_exists( 'wp_set_script_translations' ) ) {
			wp_set_script_translations( 'wc-cetelem-blocks', 'cetelem-payment-gateway', WP_PLUGIN_DIR . "/" . dirname( DIRECCION_cetelem ) . '/languages/' );
		}

        return [ 'wc-cetelem-blocks' ];
	}

	/**
	 * Returns an array of key=>value pairs of data made available to the payment methods script.
	 *
	 * @return array
	 */
	public function get_payment_method_data() {
        return [
            'title'         => $this->gateway->title,
            'description'   => $this->gateway->description . '<div id="eCalculadoraCetelemDiv"></div>',
            'icon'          => $this->gateway->icon,
		];
	}
}

/*
Recarga la calculadora en checkout block
*/
function cetelem_enqueue_calculadora_script() {
	$configuracion = get_option( 'woocommerce_cetelem_settings', [] );

	$activo  = isset( $configuracion['activo'] ) ? $configuracion['activo'] : 'no';
	$testing = isset( $configuracion['testing'] ) ? $configuracion['testing'] : 'no';
	$tipo    = isset( $configuracion['tipo'] ) ? sanitize_text_field( $configuracion['tipo'] ) : 'A';

	if ( $activo === 'no' ) {
		$base_url   = $testing === 'no' ? 'https://ecommercecalculadora.cetelem.es' : 'https://test.cetelem.es';
		$script_url = sprintf( '%s/eCommerceCalculadora/resources/js/eCalculadoraCetelem%s.js', $base_url, $tipo );
		wp_enqueue_script( 'cetelem-calculadora', esc_url( $script_url ), [], '3.2.0', true );
	}
}
add_action( 'wp_enqueue_scripts', 'cetelem_enqueue_calculadora_script' );


function cetelem_calculadora_bloque() {
	$cetelem_nonce = isset($_REQUEST['cetelem_nonce']) ? sanitize_text_field(wp_unslash($_REQUEST['cetelem_nonce'])) : '';
	if ( empty($cetelem_nonce) || ! wp_verify_nonce($cetelem_nonce, 'cetelem_nonce_action') ) {
		wp_die('<strong>' . esc_html__('Acceso no autorizado', 'cetelem-payment') . '</strong>');
	}
	$total         = isset($_REQUEST['total']) ? sanitize_text_field(wp_unslash($_REQUEST['total'])) : '';
	$configuracion = get_option( 'woocommerce_cetelem_settings', [] );
	if ( ! empty( $configuracion ) ) {
		$inline_js = sprintf(
			'codCentro="%s"; cantidad="%s"; color="%s"; fontSize="%s"; codPromocion="%s"; listadoMeses="%s"; server="%s";',
			esc_js($configuracion['codcentro']),
			esc_js($total),
			esc_js($configuracion['color']),
			esc_js($configuracion['fuente']),
			esc_js($configuracion['codigo']),
			esc_js(!empty($configuracion['meses']) ? $configuracion['meses'] : '3,6,12,18,24,36,42,48,60,120'),
			esc_js(($configuracion['testing'] ?? 'no') == 'no' ? 'https://ecommercecalculadora.cetelem.es' : 'https://test.cetelem.es')
		);
		wp_add_inline_script('cetelem-calculadora', $inline_js);
		// Respuesta vacía o mensaje en HTML si lo deseas
		echo '<div id="eCalculadoraCetelemDiv"></div>';
		exit;
	}
}
add_action( 'wp_ajax_nopriv_cetelem_calculadora_bloque', 'cetelem_calculadora_bloque' );
add_action( 'wp_ajax_cetelem_calculadora_bloque', 'cetelem_calculadora_bloque' );

/*
Carga la calculadora en checkout block
*/
function cetelem_carga_calculadora() {
	global $cetelem;
	$configuracion = get_option( 'woocommerce_cetelem_settings', [] );

	if ( ! empty( $configuracion )
		&& $configuracion['activar'] === 'yes'
		&& $configuracion['mostrar'] !== 'product'
		&& (float) WC()->cart->total >= $cetelem['importe']
		&& (float) WC()->cart->total <= $cetelem['maximo']
	) {
		wp_enqueue_script( 'jquery' );

		$ajax_url = esc_url( admin_url( 'admin-ajax.php' ) );
		$total    = esc_js( (float) WC()->cart->total );

		$inline_script  = 'jQuery(function($){' . "\n";
		$inline_script .= '  $(".entry-content").append(\'<div id="cetelem_calculadora" style="display: none;"></div>\');' . "\n";
		$inline_script .= '  $(document).on("change", "#radio-control-wc-payment-method-options-cetelem", function(){' . "\n";
		$inline_script .= '    if($(this).is(":checked")){' . "\n";
		$inline_script .= '      $.ajax({' . "\n";
		$inline_script .= '        type: "POST",' . "\n";
		$inline_script .= '        url: "' . $ajax_url . '",' . "\n";
		$inline_script .= '        data: {' . "\n";
		$inline_script .= '          action: "cetelem_calculadora_bloque",' . "\n";
		$inline_script .= '          total: "' . $total . '"' . "\n";
		$inline_script .= '        },' . "\n";
		$inline_script .= '        success: function(response){' . "\n";
		$inline_script .= '          $("#eCalculadoraCetelemDiv").html("");' . "\n";
		$inline_script .= '          $("#cetelem_calculadora").html(response);' . "\n";
		$inline_script .= '        }' . "\n";
		$inline_script .= '      });' . "\n";
		$inline_script .= '    }' . "\n";
		$inline_script .= '  });' . "\n";
		$inline_script .= '});';

		wp_add_inline_script( 'jquery', $inline_script );
	}
}
add_action( 'wp_footer', 'cetelem_carga_calculadora' );
