<?php
defined('ABSPATH') || exit;

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

final class Cetelem_cuotas_Blocks extends AbstractPaymentMethodType
{
    protected $name = 'cetelem_cuotas';
    private $gateway;

    public function initialize()
    {
        $this->settings = get_option('woocommerce_cetelem_cuotas_settings', []);
        $gateways = WC()->payment_gateways()->get_available_payment_gateways();
        $this->gateway = isset($gateways[$this->name]) ? $gateways[$this->name] : null;
    }

    public function is_active()
    {
        return $this->gateway && $this->gateway->is_available();
    }

    public function get_payment_method_script_handles()
    {
        wp_register_script(
            'wc-cetelem-cuotas-blocks',
            plugin_dir_url(__DIR__) . 'assets/js/checkout-cuotas.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-cuotas-blocks',
                'cetelem-payment',
                plugin_dir_path(__DIR__) . 'languages/'
            );
        }

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

    public function get_payment_method_data()
    {
        return [
            'title'       => $this->gateway->title,
            'description' => $this->gateway->description . '<div id="eCalculadoraCetelemEnCuotas"></div>',
            'icon'        => $this->gateway->icon,
        ];
    }
}


/**
 * Recarga la calculadora en checkout block (AJAX)
 */
function cetelem_cuotas_calculadora_bloque()
{
    if (
        ! isset($_REQUEST['cetelem_nonce']) ||
        ! wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['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 = maybe_unserialize(get_option('woocommerce_cetelem_cuotas_settings'));
    if (empty($configuracion)) {
        wp_die(); // No hay configuración
    }

    // Prepara datos
    $codcentro = isset($configuracion['codcentro']) ? $configuracion['codcentro'] : '';
    $server = ($configuracion['testing'] === 'no') ? 'https://ecommercecalculadora.cetelem.es' : 'https://test.cetelem.es';

    wp_register_script('cetelem-block-calculator', '', [], '1.0.0', true);
    wp_enqueue_script('cetelem-block-calculator');

    // Inline script seguro
    $inline_script = sprintf(
        '
            codCentro = %s;
            cantidad = %s;
            server = %s;

            var script = document.createElement("script");
            script.src = server + "/eCommerceCalculadora/resources/js/mix/eCalculadoraCetelemMix.js";
            script.async = true;
            document.head.appendChild(script);
        ',
        wp_json_encode($codcentro),
        wp_json_encode($total),
        wp_json_encode($server)
    );

    wp_add_inline_script('cetelem-block-calculator', $inline_script);

    echo '<div id="eCalculadoraCetelemEnCuotas"></div>';

    wp_die();
}
add_action('wp_ajax_nopriv_cetelem_cuotas_calculadora_bloque', 'cetelem_cuotas_calculadora_bloque');
add_action('wp_ajax_cetelem_cuotas_calculadora_bloque', 'cetelem_cuotas_calculadora_bloque');

/**
 * Agrega async al script externo si es necesario
 */
function cetelem_add_async_attribute($tag, $handle)
{
    if ('cetelem-calculadora-mix' === $handle) {
        return str_replace(' src', ' async src', $tag);
    }
    return $tag;
}
add_filter('script_loader_tag', 'cetelem_add_async_attribute', 10, 2);

/**
 * Encola script en checkout si se cumplen condiciones
 */
function cetepay_enqueue_cuotas_script()
{
    global $cetelem;

    if (! is_checkout()) {
        return;
    }

    $configuracion = maybe_unserialize(get_option('woocommerce_cetelem_cuotas_settings'));
    $total = WC()->cart->total;
    $minimo = isset($cetelem['encuotas']) ? (float) $cetelem['encuotas'] : 0;

    if (
        ! empty($configuracion) &&
        isset($configuracion['activar'], $configuracion['mostrar'], $configuracion['importe']) &&
        $configuracion['activar'] === 'yes' &&
        $configuracion['mostrar'] !== 'product' &&
        $total >= $minimo &&
        $total <= $configuracion['importe']
    ) {
        wp_enqueue_script(
            'cetepay-cuotas-calculadora',
            plugins_url('assets/js/cetepay-cuotas-calculadora.js', __FILE__),
            array('jquery'),
            '1.0.0',
            true
        );

        wp_localize_script('cetepay-cuotas-calculadora', 'cetepay_cuotas_data', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'total'    => $total,
            'nonce'    => wp_create_nonce('cetelem_nonce_action'),
        ));
    }
}
add_action('wp_enqueue_scripts', 'cetepay_enqueue_cuotas_script');
