<?php

defined('ABSPATH') || exit;

class WC_Gateway_iPag_Credito_Blocks extends WC_Gateway_Abstract_iPag_Blocks
{
    protected $name = 'ipag-gateway';

    /**
     * Generate formatted installment options for the payment form
     *
     * @param array $data Payment fields data from prepare_payment_fields_data()
     * @return array Array of installment options
     */
    private function generateInstallmentOptions($data)
    {
        $options = [];

        $pass_interest = $data['pass_interest'] ?? '';
        $pass_installments = $data['pass_installments'] ?? null;
        $maximum_installment = $data['maximum_installment'] ?? 1;
        $interest_free_installment = $data['interest_free_installment'] ?? 1;
        $total = $data['total'] ?? 0;
        $interest_rate = $data['interest_rate'] ?? 0;
        $parcelas_juros = $data['parcelas_juros'] ?? [];

        if ($pass_interest === 'yes' && !empty($pass_installments)) {
            foreach ($pass_installments as $inst) {
                $instNumber = $inst['installment'];
                $instAmount = floatval($inst['installmentAmount']);
                $totalAmount = floatval($inst['amount']);
                $hasFee = $inst['interest'];

                $text = $instNumber . 'x de R$ ' . number_format($instAmount, 2, ',', '.');
                $text .= $hasFee ? ' com juros' : ' sem juros';
                $text .= ' • R$ ' . number_format($totalAmount, 2, ',', '.');

                $options[] = [
                    'value' => (string) $instNumber,
                    'label' => $text
                ];
            }
        } elseif (!empty($data['subscription_enabled'])) {
            // For subscriptions, only allow single payment
            $options[] = [
                'value' => '1',
                'label' => '1x de R$ ' . number_format($total, 2, ',', '.') . ' sem juros • R$ ' . number_format($total, 2, ',', '.')
            ];
        } else {
            for ($i = 1; $i <= $maximum_installment; $i++) {
                if ($i <= $interest_free_installment) {
                    $installmentValue = $total / $i;
                    $text = $i . 'x de R$ ' . number_format($installmentValue, 2, ',', '.') . ' sem juros - R$ ' . number_format($total, 2, ',', '.');
                } else {
                    $installmentValue = $parcelas_juros[$i - 1] ?? 0;
                    $totalValue = $installmentValue * $i;
                    $text = $i . 'x de R$ ' . number_format($installmentValue, 2, ',', '.') . ' com juros de ' . $interest_rate . '% a.m - R$ ' . number_format($totalValue, 2, ',', '.');
                }
                $options[] = [
                    'value' => (string) ($i - 1), //NOTE: para deixar complient com o código legado.
                    'label' => $text
                ];
            }
        }

        return $options;
    }

    public function get_payment_method_script_handles()
    {
        wp_register_script(
            'ipag-masks',
            WC_iPag_Gateway::plugin_url() . "/js/masks.js?v=" . WC_iPag_Gateway::IPAG_VERSION,
            [],
            WC_iPag_Gateway::IPAG_VERSION,
            false
        );

        wp_enqueue_script('ipag-masks');

        wp_register_script(
            'ipag-cpf-cnpj',
            WC_iPag_Gateway::plugin_url() . "/js/cpf_cnpj.js?v=" . WC_iPag_Gateway::IPAG_VERSION,
            [],
            WC_iPag_Gateway::IPAG_VERSION,
            false
        );

        wp_enqueue_script('ipag-cpf-cnpj');

        return array_merge(
            parent::get_payment_method_script_handles(),
            ['ipag-masks', 'ipag-cpf-cnpj']
        );
    }

    public function get_payment_method_data()
    {
        // Get payment data once and reuse it
        $payment_data = $this->gateway->prepare_payment_fields_data();

        $data = array_merge(
            parent::get_payment_method_data(),
            [
                'title' => $this->gateway->get_title(),
                'images_url' => WC_iPag_Gateway::plugin_url() . '/images/',
                'installmentOptions' => $this->generateInstallmentOptions($payment_data),
                'subscription_enabled' => $payment_data['subscription_enabled'] ?? false,
                'new_card_label' => __('Novo Cartão', 'ipag-gateway'),
                'saved_cards_label' => __('Cartões Salvos', 'ipag-gateway'),
                'save_card_checkbox_label' => __('Salvar cartão para próximas compras.', 'ipag-gateway'),
                'saved_cards_empty_message' => __('Nenhum cartão salvo encontrado.', 'ipag-gateway'),
            ],
            $payment_data
        );

        // Add brand logo to payment method display if enabled
        if (!empty($payment_data['brand']) && $payment_data['brand'] === 'yes') {
            $data['image'] = WC_iPag_Gateway::plugin_url() . '/images/ipag.png';
        }

        return $data;
    }
}

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

add_action('woocommerce_store_api_checkout_update_order_from_request', function ($order, $request) {
    if ($order->get_payment_method() !== 'ipag-gateway') {
        return;
    }

    if (!isset($request['payment_data']) || !is_array($request['payment_data'])) {
        return;
    }

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

    $sanitize_value = function ($value) use (&$sanitize_value) {
        if (is_array($value)) {
            $sanitized = [];
            foreach ($value as $key => $item) {
                $sanitized[$key] = $sanitize_value($item);
            }
            return $sanitized;
        }

        return sanitize_text_field($value);
    };

    $set_nested_value = function (&$target, $segments, $value) {
        $current =& $target;
        $last_index = count($segments) - 1;

        foreach ($segments as $index => $segment) {
            if ($segment === '') {
                continue;
            }

            $is_last = $index === $last_index;

            if ($is_last) {
                $current[$segment] = $value;
                continue;
            }

            if (!isset($current[$segment]) || !is_array($current[$segment])) {
                $current[$segment] = [];
            }

            $current =& $current[$segment];
        }
    };

    foreach ($request['payment_data'] as $item) {
        if (!isset($item['key']) || strpos($item['key'], 'ipag_') !== 0) {
            continue;
        }

        $raw_key = rawurldecode($item['key']);
        $value = $sanitize_value($item['value'] ?? '');

        $_POST[$raw_key] = $value;

        $dash_pos = strpos($raw_key, '-');
        if ($dash_pos !== false) {
            $base = substr($raw_key, 0, $dash_pos);
            $remainder = substr($raw_key, $dash_pos + 1);

            if ($base !== '' && $remainder !== '') {
                $segments = explode('-', $remainder);

                if (!isset($_POST[$base]) || !is_array($_POST[$base])) {
                    $_POST[$base] = [];
                }

                $set_nested_value($_POST[$base], $segments, $value);
            }
        }
    }
}, 10, 2);

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') {
        return $result;
    }

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

    return $result;
}, 10, 3);
