<?php

defined('ABSPATH') || exit;

class WC_Gateway_iPag_Pix_Blocks extends WC_Gateway_Abstract_iPag_Blocks
{
    protected $name = 'ipag-gateway_pix';

    public function get_payment_method_data()
    {
        $default_message = 'Confirm your order to view the qrcode.';
        $checkout_message = $this->gateway->get_option('checkout_message');

        if ($checkout_message === $default_message) {
            $checkout_message = __($default_message, 'ipag-gateway');
        }

        return array_merge(
            parent::get_payment_method_data(),
            [
                'title' => $this->gateway->get_title(),
                'description' => $checkout_message,
            ]
        );
    }
}

add_action(
    'woocommerce_blocks_payment_method_type_registration',
    function ($payment_method_registry) {
        $payment_method_registry->register(
            new \WC_Gateway_iPag_Pix_Blocks()
        );
    }
);

add_filter('rest_pre_dispatch', function ($result, $server, $request) {
    if (!method_exists($request, 'get_route') || !method_exists($request, 'get_method')) {
        return $result;
    }

    if ($request->get_route() !== '/wc/store/v1/checkout' || $request->get_method() !== 'POST') {
        return $result;
    }

    $params = $request->get_json_params();
    $payment_method = is_array($params) ? ($params['payment_method'] ?? '') : '';

    if ($payment_method !== 'ipag-gateway_pix') {
        return $result;
    }

    if (function_exists('wc_clear_notices')) {
        wc_clear_notices();
    }

    return $result;
}, 10, 3);