<?php

namespace WKO\Controllers\Checkout;

class CheckoutFieldManager
{
    public function __construct()
    {
        if (get_option('wc_koin_settings_override_number_fields') !== 'yes') {
            add_filter('woocommerce_checkout_fields', [$this, 'add_number_field']);
        }

        if (get_option('wc_koin_settings_override_document_fields') !== 'yes') {
            add_filter('woocommerce_checkout_fields', [$this, 'add_custom_checkout_fields']);
            add_action('woocommerce_after_checkout_validation', [$this, 'validate_custom_checkout_fields']);
            add_filter('woocommerce_get_country_locale', [$this, 'manage_country_locale']);
            add_filter('woocommerce_form_field', [$this, 'remove_optional']);
            add_filter('woocommerce_form_field_radio', [$this, 'custom_radio_field_style'], 10, 4);
        }

        add_action('woocommerce_checkout_update_order_meta', [$this, 'save_custom_checkout_fields']);
    }

    private function get_custom_checkout_fields()
    {
        return [
            'billing_persontype' => [
                'type'     => 'select',
                'label'    => __('Person Type', 'wc-koin-official'),
                'options'  => [
                    '1'   => __('Individual', 'wc-koin-official'),
                    '2' => __('Legal Entity', 'wc-koin-official'),
                ],
                'id'       => 'wc_koin_person_type',
                'class'    => ['form-row-wide'],
                'priority' => 40,
            ],
            'billing_document_type_br' => [
                'type'     => 'radio',
                'label'    => __('Document Type', 'wc-koin-official'),
                'options'  => [
                    'CPF'   => __('CPF', 'wc-koin-official'),
                    'PASSPORT' => __('Passport', 'wc-koin-official'),
                ],
                'id'       => 'wc_koin_document_type_br',
                'class'    => ['form-row-wide'],
                'priority' => 40,
            ],
            'billing_cpf' => [
                'label'    => 'CPF',
                'id'       => 'wc_koin_cpf',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_company' => [
                'label'    => __('Company Name', 'wc-koin-official'),
                'id'       => 'wc_koin_company',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_cnpj' => [
                'label'    => 'CNPJ',
                'id'       => 'wc_koin_cnpj',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_passport_br' => [
                'label'    => __('Passport', 'wc-koin-official'),
                'id'       => 'wc_koin_passport_br',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_dni_ar' => [
                'label'         => __('National Identity Document', 'wc-koin-official'),
                'id'            => 'wc_koin_dni_ar',
                'class'         => ['form-row-wide'],
                'clear'         => true,
                'priority'      => 41,
            ],
            'billing_ci_mx' => [
                'label'    => __('Voter ID Card', 'wc-koin-official'),
                'id'       => 'wc_koin_ci_mx',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_cc' => [
                'label'    => __('Citizenship Card', 'wc-koin-official'),
                'id'       => 'wc_koin_cc',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_ci' => [
                'label'    => __('Identity Card', 'wc-koin-official'),
                'id'       => 'wc_koin_ci',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_dni_pe' => [
                'label'    => __('National Identity Document', 'wc-koin-official'),
                'id'       => 'wc_koin_dni_pe',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_doctype_ar' => [
                'type'     => 'select',
                'label'    => __('Document Type', 'wc-koin-official'),
                'options'  => [
                    'DNI'   => 'DNI',
                    'PASSPORT' => __('Passport', 'wc-koin-official'),
                ],
                'id'       => 'wc_koin_doctype_ar',
                'class'    => ['form-row-wide'],
                'priority' => 40,
            ],
            'billing_passport_ar' => [
                'label'    => __('Passport', 'wc-koin-official'),
                'id'       => 'wc_koin_passport_ar',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_doctype_mx' => [
                'type'     => 'select',
                'label'    => __('Document Type', 'wc-koin-official'),
                'options'  => [
                    'INE'   => 'INE',
                    'CURP' => 'CURP',
                    'RFC' => 'RFC',
                    'PASSPORT' => __('Passport', 'wc-koin-official'),
                ],
                'id'       => 'wc_koin_doctype_mx',
                'class'    => ['form-row-wide'],
                'priority' => 40,
            ],
            'billing_curp' => [
                'label'    => __('Unique Population Registry Code', 'wc-koin-official'),
                'id'       => 'wc_koin_curp',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_rfc' => [
                'label'    => __('Federal Taxpayers Registry', 'wc-koin-official'),
                'id'       => 'wc_koin_rfc',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_passport_mx' => [
                'label'    => __('Passport', 'wc-koin-official'),
                'id'       => 'wc_koin_passport_mx',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_doctype_co' => [
                'type'     => 'select',
                'label'    => __('Document Type', 'wc-koin-official'),
                'options'  => [
                    'CC'   => 'CC',
                    'CE' => 'CE',
                    'PASSPORT' => __('Passport', 'wc-koin-official'),
                ],
                'id'       => 'wc_koin_doctype_co',
                'class'    => ['form-row-wide'],
                'priority' => 40,
            ],
            'billing_ce_co' => [
                'label'    => __('Foreign ID Card', 'wc-koin-official'),
                'id'       => 'wc_koin_ce_co',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_passport_co' => [
                'label'    => __('Passport', 'wc-koin-official'),
                'id'       => 'wc_koin_passport_co',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_doctype_cl' => [
                'type'     => 'select',
                'label'    => __('Document Type', 'wc-koin-official'),
                'options'  => [
                    'CI'   => 'CI',
                    'RUT' => 'RUT',
                    'PASSPORT' => __('Passport', 'wc-koin-official'),
                ],
                'id'       => 'wc_koin_doctype_cl',
                'class'    => ['form-row-wide'],
                'priority' => 40,
            ],
            'billing_rut' => [
                'label'    => __('Unique Tax Roll', 'wc-koin-official'),
                'id'       => 'wc_koin_rut',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_passport_cl' => [
                'label'    => __('Passport', 'wc-koin-official'),
                'id'       => 'wc_koin_passport_cl',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_doctype_pe' => [
                'type'     => 'select',
                'label'    => __('Document Type', 'wc-koin-official'),
                'options'  => [
                    'DNI'   => 'DNI',
                    'CE' => 'CE',
                    'PASSPORT' => __('Passport', 'wc-koin-official'),
                ],
                'id'       => 'wc_koin_doctype_pe',
                'class'    => ['form-row-wide'],
                'priority' => 40,
            ],
            'billing_ce_pe' => [
                'label'    => __('Foreign ID Card', 'wc-koin-official'),
                'id'       => 'wc_koin_ce_pe',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_passport_pe' => [
                'label'    => __('Passport', 'wc-koin-official'),
                'id'       => 'wc_koin_passport_pe',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_doctype_uy' => [
                'type'     => 'select',
                'label'    => __('Document Type', 'wc-koin-official'),
                'options'  => [
                    'CI'   => 'CI',
                    'PASSPORT' => __('Passport', 'wc-koin-official'),
                ],
                'id'       => 'wc_koin_doctype_uy',
                'class'    => ['form-row-wide'],
                'priority' => 40,
            ],
            'billing_passport_uy' => [
                'label'    => __('Passport', 'wc-koin-official'),
                'id'       => 'wc_koin_passport_uy',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
            'billing_ci_uy' => [
                'label'    => __('Identity Card', 'wc-koin-official'),
                'id'       => 'wc_koin_ci_uy',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
            ],
        ];
    }

    public function add_custom_checkout_fields($fields)
    {
        $new_fields = $this->get_custom_checkout_fields();
        foreach ($new_fields as $key => $field) {
            $fields['billing'][$key] = isset($fields['billing'][$key])
                ? array_merge($fields['billing'][$key], $field)
                : $field;
        }
        return $fields;
    }

    public function validate_custom_checkout_fields($posted)
    {
        $country = $posted['billing_country'] ?? '';
        $personType = $posted['billing_persontype'] ?? '';
        $documentTypeBr = $posted['billing_document_type_br'] ?? '';

        $requiredFields = [
            'BR' => [
                ['field' => 'billing_cpf', 'personType' => '1', 'documentType' => 'CPF', 'label' => __('CPF', 'wc-koin-official')],
                ['field' => 'billing_passport_br', 'personType' => '1', 'documentType' => 'PASSPORT', 'label' => __('Passport', 'wc-koin-official')],
                ['field' => 'billing_cnpj', 'personType' => '2', 'label' => __('CNPJ', 'wc-koin-official')],
                ['field' => 'billing_company', 'personType' => '2', 'label' => __('Company Name', 'wc-koin-official')],
            ],
            'AR' => [
                ['field' => 'billing_dni_ar', 'label' => __('National Identity Document', 'wc-koin-official')],
            ],
            'MX' => [
                ['field' => 'billing_ci_mx', 'label' => __('Identity Card', 'wc-koin-official')],
            ],
            'CO' => [
                ['field' => 'billing_cc', 'label' => __('Citizenship ID Card', 'wc-koin-official')],
            ],
            'CL' => [
                ['field' => 'billing_ci', 'label' => __('Identity Card', 'wc-koin-official')],
            ],
            'PE' => [
                ['field' => 'billing_dni_pe', 'label' => __('National Identity Document', 'wc-koin-official')],
            ],
            'UY' => [
                ['field' => 'billing_ci_uy', 'label' => __('Identity Card', 'wc-koin-official')],
            ],
        ];

        if (!empty($requiredFields[$country])) {
            foreach ($requiredFields[$country] as $req) {
                $isRequired = false;
                
                if ($country === 'BR' && isset($req['personType'])) {
                    if ($req['personType'] === '1') {
                        // Individual - check documentType
                        $isRequired = isset($req['documentType']) && $documentTypeBr === $req['documentType'];
                    } else {
                        // Legal Entity
                        $isRequired = $personType === $req['personType'];
                    }
                } elseif (isset($req['personType'])) {
                    $isRequired = $personType === $req['personType'];
                } else {
                    $isRequired = true;
                }
                
                if ($isRequired && empty($posted[$req['field']])) {
                    wc_add_notice(
                        sprintf(
                            /* translators: %s: Field label */
                            __('<strong>%s</strong> is a required field.', 'wc-koin-official'),
                            $req['label']
                        ),
                        'error'
                    );
                }
            }
        }
    }

    public function add_number_field($fields)
    {
        $number_field = [
            'billing_number' => [
                'label'    => __('Number', 'wc-koin-official'),
                'id'       => 'wc_koin_billing_number',
                'class'    => ['form-row-wide'],
                'clear'    => true,
                'priority' => 41,
                'required' => true,
            ]
        ];

        foreach ($number_field as $key => $field) {
            $fields['billing'][$key] = isset($fields['billing'][$key])
                ? array_merge($fields['billing'][$key], $field)
                : $field;
        }

        return $fields;
    }

    public function remove_optional($field)
    {
        $fields_to_remove_optional = [
            'wc_koin_person_type',
            'wc_koin_document_type_br',
            'wc_koin_company',
            'wc_koin_cpf',
            'wc_koin_cnpj',
            'wc_koin_passport_br',
            'wc_koin_dni_ar',
            'wc_koin_doctype_ar',
            'wc_koin_passport_ar',
            'wc_koin_ci_mx',
            'wc_koin_doctype_mx',
            'wc_koin_curp',
            'wc_koin_rfc',
            'wc_koin_passport_mx',
            'wc_koin_cc',
            'wc_koin_doctype_co',
            'wc_koin_ce_co',
            'wc_koin_passport_co',
            'wc_koin_ci',
            'wc_koin_doctype_cl',
            'wc_koin_rut',
            'wc_koin_passport_cl',
            'wc_koin_dni_pe',
            'wc_koin_doctype_pe',
            'wc_koin_ce_pe',
            'wc_koin_passport_pe',
            'wc_koin_ci_uy',
            'wc_koin_doctype_uy',
            'wc_koin_passport_uy'
        ];

        foreach ($fields_to_remove_optional as $field_id) {
            if (strpos($field, $field_id) !== false) {
                $field = preg_replace('/<span class="optional">(.*?)<\/span>/', '', $field);
            }
        }

        return $field;
    }

    public function save_custom_checkout_fields($order_id)
    {
        $fields = [
            '_billing_document_type_br',
            '_billing_cnpj',
            '_billing_passport_br',
            '_billing_dni_ar',
            '_billing_doctype_ar',
            '_billing_passport_ar',
            '_billing_ci_mx',
            '_billing_doctype_mx',
            '_billing_curp',
            '_billing_rfc',
            '_billing_passport_mx',
            '_billing_cc',
            '_billing_doctype_co',
            '_billing_ce_co',
            '_billing_passport_co',
            '_billing_ci',
            '_billing_doctype_cl',
            '_billing_rut',
            '_billing_passport_cl',
            '_billing_dni_pe',
            '_billing_doctype_pe',
            '_billing_ce_pe',
            '_billing_passport_pe',
            '_billing_ci_uy',
            '_billing_doctype_uy',
            '_billing_passport_uy',
        ];

        foreach ($fields as $field) {
            if (!empty($_POST[$field])) {
                update_post_meta($order_id, $field, sanitize_text_field($_POST[$field]));
            }
        }
    }

    /**
     * Manage the locale settings for a specific country during checkout.
     *
     * @param array $locale The current locale settings.
     * @return array The modified locale settings.
     */
    public function manage_country_locale($locale)
    {
        $locale['CL']['postcode']['required'] = true;
        $locale['CO']['postcode']['required'] = true;
        $locale['CL']['postcode']['hidden'] = false;
        return $locale;
    }

    /**
     * Add custom styling to radio fields to display options horizontally.
     *
     * @param string $field The field HTML.
     * @param string $key The field key.
     * @param array $args The field arguments.
     * @param string $value The field value.
     * @return string The modified field HTML.
     */
    public function custom_radio_field_style($field, $key, $args, $value)
    {
        if ($key === 'billing_document_type_br') {
            $field = str_replace(
                '<p class="form-row',
                '<p class="form-row" style="display: flex; align-items: center; gap: 10px;"',
                $field
            );
            $field = str_replace(
                '<span class="woocommerce-input-wrapper"',
                '<span class="woocommerce-input-wrapper" style="display: flex; gap: 15px; align-items: center;"',
                $field
            );
        }
        return $field;
    }
}
