<?php
/**
 * pageSettingsFields.php
 *
 * @since      1.0.0
 * @author     alfiopiccione <alfio.piccione@gmail.com>
 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright (C) 2025 alfiopiccione <alfio.piccione@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

/**
 * Extend setting fields
 */
add_action('wc_el_inv-page_setting_section_invoice', function ($section, $sectionArgs, $fieldsArgs) {
    $page = \WcElectronInvoice\Admin\Settings\OptionPage::init();

    if ('IT' === \WcElectronInvoice\WooCommerce\Fields\GeneralFields::getGeneralInvoiceOptionCountryState()) {
        foreach ($fieldsArgs as $arg) {
            if ($arg['field_id'] === 'add_stamp_duty_options_fields') {
                $this->fieldsArgs[] = array(
                    'field_id'       => 'add_stamp_duty_paid_customer_options_fields',
                    'field_title'    => esc_html__('Stamp duty charged to the customer', WC_EL_INV_TEXTDOMAIN),
                    'field_callback' => array(
                        new \WcElectronInvoice\Admin\Settings\Fields\Checkbox(array(
                            'id'          => 'wc_el_inv-settings-stamp_duty_paid_customer',
                            'name'        => 'wc_el_inv-settings-stamp_duty_paid_customer',
                            'label'       => esc_html__('Add virtual stamp (paid by the customer)',
                                WC_EL_INV_TEXTDOMAIN),
                            'description' => esc_html__('The stamp duty will be added to the cart and paid by the customer',
                                WC_EL_INV_TEXTDOMAIN),
                        ), $this, $page),
                        'field',
                    ),
                    'field_page'     => $this->sectionArgs['wc_el_inv_settings']['section_page'],
                    'field_section'  => 'setting_section_invoice',
                    'field_args'     => array('class' => 'add_stamp_duty_paid_customer'),
                );
                $this->fieldsArgs[] = array(
                    'field_id'       => 'hr_doc_stamp_duty_bottom',
                    'field_title'    => '',
                    'field_callback' => function () {
                        echo '<hr>';
                    },
                    'field_page'     => $this->sectionArgs['wc_el_inv_settings']['section_page'],
                    'field_section'  => 'setting_section_invoice',
                );
            }
        }
    }

    switch ($section) {
        // Invoice / Documents
        case 'setting_section_invoice':
            if ('IT' === \WcElectronInvoice\WooCommerce\Fields\GeneralFields::getGeneralInvoiceOptionCountryState()) {
                // Rivalsa inps
                $this->fieldsArgs[] = array(
                    'field_id'       => 'hr_rivalsa_inps',
                    'field_title'    => sprintf('<h4>%s</h4>', esc_html__('INPS compensation', WC_EL_INV_TEXTDOMAIN)),
                    'field_callback' => function () {
                    },
                    'field_page'     => $this->sectionArgs['wc_el_inv_settings']['section_page'],
                    'field_section'  => 'setting_section_invoice',
                );
                $this->fieldsArgs[] = array(
                    'field_id'       => 'add_rivalsa_inps_options_fields',
                    'field_title'    => esc_html__('Add the INPS Compensation to the invoices', WC_EL_INV_TEXTDOMAIN),
                    'field_callback' => array(
                        new \WcElectronInvoice\Admin\Settings\Fields\Checkbox(array(
                            'id'          => 'wc_el_inv-settings-add_rivalsa_inps',
                            'name'        => 'wc_el_inv-settings-add_rivalsa_inps',
                            'label'       => esc_html__('Add INPS Compensation', WC_EL_INV_TEXTDOMAIN),
                            'description' => sprintf(esc_html__('Add the Rivalsa INPS (%1$s) to all invoices.',
                                WC_EL_INV_TEXTDOMAIN), apply_filters('wc_el_inv-rivalsa_inps-aliquota-text', '4%')),
                        ), $this, $page),
                        'field',
                    ),
                    'field_page'     => $this->sectionArgs['wc_el_inv_settings']['section_page'],
                    'field_section'  => 'setting_section_invoice',
                    'field_args'     => array('class' => 'add_rivalsa_inps'),
                );
                $this->fieldsArgs[] = array(
                    'field_id'       => 'hr_doc_rivalsa_inps_bottom',
                    'field_title'    => '',
                    'field_callback' => function () {
                        echo '<hr>';
                    },
                    'field_page'     => $this->sectionArgs['wc_el_inv_settings']['section_page'],
                    'field_section'  => 'setting_section_invoice',
                );
            }
            // Product
            $this->fieldsArgs[] = array(
                'field_id'       => 'hr_product_desc_meta',
                'field_title'    => sprintf('<h4>%s</h4>', esc_html__('WooCommerce Product', WC_EL_INV_TEXTDOMAIN)),
                'field_callback' => function () {
                },
                'field_page'     => $this->sectionArgs['wc_el_inv_settings']['section_page'],
                'field_section'  => 'setting_section_invoice',
            );
            $this->fieldsArgs[] = array(
                'field_id'       => 'invoice_description_type_options_fields',
                'field_title'    => esc_html__('Product description on the invoice', WC_EL_INV_TEXTDOMAIN),
                'field_callback' => array(
                    new \WcElectronInvoice\Admin\Settings\Fields\Checkbox(array(
                        'id'          => 'wc_el_inv-settings-invoice_description_type',
                        'name'        => 'wc_el_inv-settings-invoice_description_type',
                        'label'       => esc_html__('Show Product Title and Description on invoices (default title only)',
                            WC_EL_INV_TEXTDOMAIN),
                        'description' => sprintf('%s',
                            esc_html__('Enabling the option will add the short description of the product.',
                                WC_EL_INV_TEXTDOMAIN)
                        ),
                    ), $this, $page),
                    'field',
                ),
                'field_page'     => $this->sectionArgs['wc_el_inv_settings']['section_page'],
                'field_section'  => 'setting_section_invoice',
                'field_args'     => array('class' => 'invoice_description_type'),
            );
            $this->fieldsArgs[] = array(
                'field_id'       => 'invoice_product_meta_options_fields',
                'field_title'    => esc_html__('Product metadata on invoice', WC_EL_INV_TEXTDOMAIN),
                'field_callback' => array(
                    new \WcElectronInvoice\Admin\Settings\Fields\Checkbox(array(
                        'id'          => 'wc_el_inv-settings-invoice_product_meta',
                        'name'        => 'wc_el_inv-settings-invoice_product_meta',
                        'label'       => esc_html__('Show metadata with product description on invoices',
                            WC_EL_INV_TEXTDOMAIN),
                        'description' => sprintf('%s',
                            esc_html__('Enabling the option will add metadata to the product description',
                                WC_EL_INV_TEXTDOMAIN)
                        ),
                    ), $this, $page),
                    'field',
                ),
                'field_page'     => $this->sectionArgs['wc_el_inv_settings']['section_page'],
                'field_section'  => 'setting_section_invoice',
                'field_args'     => array('class' => 'invoice_product_meta'),
            );
            break;
        default:
            $this->sectionArgs  = array();
            $this->fieldsArgs[] = array();
            break;
    }
}, 10, 3);

/**
 * Reverse Charge nav
 */
add_action('wc_el_inv-page_setting_provider_integration_nav', function () {
    if (\WcElectronInvoice\Functions\haveAnActiveProvider() &&
        in_array(\WcElectronInvoice\WooCommerce\Fields\GeneralFields::getGeneralInvoiceOptionCountryState(),
            \WcElectronInvoice\WooCommerce\Fields\GeneralFields::getEuCountries()
        )
    ) {
        echo sprintf('<li><a href="#reverse-charge">%s</a></li>',
            esc_html__('Reverse Charge', WC_EL_INV_TEXTDOMAIN)
        );
    }
});

/**
 * Reverse Charge fields
 */
add_action('wc_el_inv-page_setting_provider_integration_fields', function () {
    $shopCountry = \WcElectronInvoice\WooCommerce\Fields\GeneralFields::getGeneralInvoiceOptionCountryState();
    $paidOnlyBadge = sprintf(
        ' <span class="pop-premium-badge">%s</span>',
        esc_html__('Paid only', WC_EL_INV_TEXTDOMAIN)
    );
    echo '<div class="ReverseChargeData_output_fields">';
    if ('ES' === $shopCountry) {
        $nature = include \WcElectronInvoice\Plugin::getPluginDirPath('/inc/wc/nature-es.php');
    } else {
        $nature = include \WcElectronInvoice\Plugin::getPluginDirPath('/inc/wc/nature.php');
    }
    if (\WcElectronInvoice\Functions\haveAnActiveProvider() &&
        in_array($shopCountry, \WcElectronInvoice\WooCommerce\Fields\GeneralFields::getEuCountries()
        )
    ) {

        $level = \WcElectronInvoice\Wizard::popGetUserLevel();
        $premiumDisabled = ! \WcElectronInvoice\Wizard::isUserLevelGte($level, 'basic');
        $premiumCustomAttributes = $premiumDisabled ? array(
            'disabled' => 'disabled',
            'readonly' => 'readonly',
        ) : array();
        // Reverse Charge help Link for woocommerce
        echo sprintf('<div class="pop-notice notice-info"><p><span class="dashicons dashicons-info"></span> ' .
                     esc_html__('Follow the guide to set up %1$s the reverse charge %2$s',
                         WC_EL_INV_TEXTDOMAIN) . '</p></div>',
            '<a target="_blank" href="https://docs.popapi.io/it/guides/configuration/reverse-charge/">',
            '</a>',
        );

        $taxProviderWC = \WcElectronInvoice\Providers\TaxesQuery::instance()->getTaxProvider('woocommerce');
        $taxEnabled    = ! empty($taxProviderWC) && $taxProviderWC->is_tax_enabled();
        $taxClasses    = \WcElectronInvoice\Functions\isWooCommerceActive() ? \WC_Tax::get_tax_classes() : [];

        $taxClassesOptions = array();
        if ($taxEnabled && ! empty($taxClasses)) {
            foreach ($taxClasses as $key => $className) {
                $taxClass = \WC_Tax::get_rates_for_tax_class($className);
                foreach ($taxClass as $id => $class) {
                    if (! empty($taxClass) && floatval($class->tax_rate) === 0.00) {
                        $taxClassesOptions[$className] = $className;
                    }
                }
            }
        } else {
            $taxClassesOptions[''] = __('Zero rate');
        }

        $taxInvoiceFields  = apply_filters('wc_el_inv-reverse_charge_inputs_args', array(
                array(
                    'title_html' => sprintf(
                        '%s%s',
                        esc_html__('Reverse Charge', WC_EL_INV_TEXTDOMAIN),
                        $premiumDisabled ? $paidOnlyBadge : ''
                    ),
                    'type'       => 'title',
                    'desc'       => '',
                    'id'         => 'reverse_charge_invoice',
                ),
                // Active globally
                array(
                    'id'                => 'wc_el_inv-global_active_reverse_charge',
                    'type'              => 'checkbox',
                    'title'             => esc_html__('Activate reverse charge (globally)',
                        WC_EL_INV_TEXTDOMAIN),
                    'desc'              => sprintf('<small>%s</small>',
                        esc_html__('Activate globally or activate from individual products', WC_EL_INV_TEXTDOMAIN)),
                    'desc_tip'          => false,
                    'class'             => '',
                    'default'           => '',
                    'custom_attributes' => $premiumCustomAttributes,
                ),
                // Active Vies
                array(
                    'id'                => 'wc_el_inv-invoice_vies_check',
                    'type'              => 'checkbox',
                    'title'             => esc_html__('Activate VIES validation', WC_EL_INV_TEXTDOMAIN),
                    'desc'              => sprintf('<small><u>%s</u></small>',
                        esc_html__('NB: Activate the VIES validation to activate the reverse charge functionality',
                            WC_EL_INV_TEXTDOMAIN)),
                    'desc_tip'          => false,
                    'class'             => '',
                    'default'           => '',
                    'custom_attributes' => $premiumCustomAttributes,
                ),
                // Zero rate tax class
                array(
                    'id'                => 'wc_el_inv-reverse_charge_tax_class',
                    'type'              => 'select',
                    'title'             => esc_html__('Tax classes:', WC_EL_INV_TEXTDOMAIN),
                    'desc'              => empty($taxClassesOptions) ?
                        sprintf('<small><span style="color:red;font-weight:700;">%s</span></small>',
                            esc_html__('(*) Enable Taxes in WooCommerce to enable tax class selection for reverse charge.',
                                WC_EL_INV_TEXTDOMAIN)) :
                        sprintf('<small>%s<small>',
                            esc_html__('Select zero rate tax classes for (Reverse charge) - usually "Zero rate"',
                                WC_EL_INV_TEXTDOMAIN)),
                    'options'           => ! empty($taxClassesOptions) ? array_merge(array(
                        '' => esc_html__('Select', WC_EL_INV_TEXTDOMAIN),
                    ), $taxClassesOptions) : array(),
                    'class'             => 'wc-enhanced-select',
                    'default'           => '',
                    'custom_attributes' => $premiumCustomAttributes,
                ),

                ...\WcElectronInvoice\WooCommerce\Fields\ReverseChargeSettings::getSettingsMappingFields(
                    ! empty($nature) ? $nature : array(),
                    $premiumCustomAttributes,
                    $shopCountry
                ),

                array(
                    'type' => 'sectionend',
                    'id'   => 'tax_invoice',
                ),
            ));
        // Reverse Charge fields
        \WcElectronInvoice\Admin\Settings\TableFields::output((array)$taxInvoiceFields);
    }
    echo '</div>';
});
