<?php
/**
 * filtersFront.php
 *
 * @author     alfiopiccione <alfio.piccione@gmail.com>

 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright (C) 2025 POP
 *
 * 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.
 */

use WcElectronInvoice\WooCommerce\Fields\InvoiceFields;

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

//
//  array(
//      'filter'        => '',
//      'callback'      => '',
//      'priority'      => '',
//      'accepted_args' => '',
//  )
//
$orderProvider    = new \WooPoPCozmosLabsPMS\Providers\OrdersProvider();
$productsProvider = new \WooPoPCozmosLabsPMS\Providers\ProductsProvider();
$taxesProvider    = new \WooPoPCozmosLabsPMS\Providers\TaxesProvider();

$filters = array(
    'front' => array(
        'action' => array(

            // registering orders provider for PMS
            // registering here for xml and pdf preview and export
            array(
                'filter'        => 'wc_el_inv-enqueue_orders_provider',
                'callback'      => array($orderProvider, 'enqueue'),
                'priority'      => 11,
                'accepted_args' => 1,
            ),

            // save discount total and tax rate in payment meta
            array(
                'filter'        => 'pms_payment_insert',
                'callback'      => array($orderProvider, 'on_payment_insert'),
                'priority'      => 100,
                'accepted_args' => 2,
            ),

            // registering the products provider for PMS
            // registering in the front filters for XML and PDF preview and export
            array(
                'filter'        => 'wc_el_inv-enqueue_products_provider',
                'callback'      => array($productsProvider, 'enqueue'),
                'priority'      => 10,
                'accepted_args' => 1,
            ),

            // registering the taxes provider for PMS
            // registering in the front filters for XML and PDF preview and export
            array(
                'filter'        => 'wc_el_inv-enqueue_taxes_provider',
                'callback'      => array($taxesProvider, 'enqueue'),
                'priority'      => 10,
                'accepted_args' => 1,
            ),

            // Frontend admin hint when PMS Tax & EU VAT is disabled and POP fiscal fields cannot render.
            array(
                'filter'        => array(
                    'pms_register_form_extra',
                    'pms_new_subscription_form_extra',
                    'pms_upgrade_subscription_form_extra',
                    'pms_change_subscription_form_extra',
                    'pms_renew_subscription_form_extra',
                    'pms_member_account_before_subscriptions_tab',
                    'pms_member_account_before_profile_tab',
                    'pms_member_account_before_payments_tab',
                ),
                'callback'      => function () {
                    static $printed = false;

                    if ( $printed || ! current_user_can( 'manage_options' ) ) {
                        return;
                    }

                    $taxModuleEnabled = function_exists( 'pms_in_tax_eu_vat_enabled' )
                        ? (bool) pms_in_tax_eu_vat_enabled()
                        : (bool) \WooPoPCozmosLabsPMS\Providers\TaxesProvider::get_tax_settings( 'enable_tax', false );

                    if ( $taxModuleEnabled ) {
                        return;
                    }

                    $printed = true;

                    echo '<div class="pop-notice notice-warning pms-notice"><p>' .
                         esc_html__(
                             'POP billing fields are hidden because the Paid Member Subscriptions module "Tax & EU VAT" is not active. Enable it to collect fiscal billing data on subscription forms.',
                             WC_EL_INV_TEXTDOMAIN
                         ) .
                         '</p></div>';
                },
                'priority'      => 5,
                'accepted_args' => 0,
            ),

            // validate vat number
            array(
                'filter'        => array(
                    'pms_payment_insert',
                    'pms_member_subscription_update',
                ),
                'callback'      => function ($payID, $data) {
                    $country              = \WcElectronInvoice\Functions\filterInput($_POST, 'pms_billing_country') ?: false;
                    $vatNumber            = \WcElectronInvoice\Functions\filterInput($_POST, 'pms_vat_number') ?: false;
                    $customerInvoiceType  = \WcElectronInvoice\Functions\filterInput($_POST, 'pms_invoice_type') ?: false;

                    if (! $country && ! $vatNumber) {
                        return false;
                    }

                    // Set prefix type used for retrieved nature or ref normative value
                    $prefix = null;
                    if (in_array($country, WcElectronInvoice\WooCommerce\Fields\GeneralFields::getEuCountries(),
                        true)) {
                        $prefix = 'ue_';
                    } elseif (! in_array($country, WcElectronInvoice\WooCommerce\Fields\GeneralFields::getEuCountries(),
                        true)) {
                        $prefix = 'extra_ue_';
                    }

                    $sanMarinoSupport = \WcElectronInvoice\Functions\sanMarinoSupport($customerInvoiceType, $country);

                    // Country IT return no SM
                    if ('SM' !== $sanMarinoSupport->shopCountry && 'IT' === $country) {
                        return;
                    }

                    // Set type
                    switch ($customerInvoiceType) {
                        case 'company':
                        case 'freelance':
                            $type = 'company';
                            break;
                        default:
                            $type = 'private';
                            break;
                    }

	                $vatNumber = str_replace($country, '', $vatNumber);

	                $vies = false;
	                if ( $vatNumber && in_array( $customerInvoiceType, [ 'company', 'freelance' ] ) ) {
		                $vies = InvoiceFields::viesCheck( $vatNumber, $country );
		                if ( false === $vies ) {
			                $type = "{$type}_no_vies";
		                }
	                }

                    if ($prefix) {
                        $nature            = WcElectronInvoice\WooCommerce\Fields\TaxFields::getReverseChargeNature("{$prefix}{$type}");
                        $refNormative      = WcElectronInvoice\WooCommerce\Fields\TaxFields::getReverseChargeRefNormative("{$prefix}{$type}");
                        $refNormativeValue = esc_html($refNormative);

                        if ('SM' === $sanMarinoSupport->shopCountry) {
                            $nature            = $sanMarinoSupport->nature;
                            $refNormativeValue = $sanMarinoSupport->refNormative;
                        }

                        if ('' !== $nature) {
                            $nature = apply_filters('wc_el_inv-before_nature_rc_pms_save', $nature, $payID, $data);
                            pms_update_payment_meta($payID, 'nature_rc', $nature);
                            if ('' !== $refNormativeValue) {
                                $refNormativeValue = apply_filters('wc_el_inv-before_ref_norm_rc_pms_save', $refNormativeValue, $payID, $data);
                                pms_update_payment_meta($payID, 'ref_norm_rc', $refNormativeValue);
                            }
                        }
                    }

                    pms_update_payment_meta($payID, 'order_vies_check', (bool) $vies);

                    $order         = \WcElectronInvoice\Providers\OrderQuery::instance()->getProviderOrder($payID, 'cozmoslabspms');
                    $numberInvoice = $order->get_meta('order_number_invoice') ?: null;
                    if ($order instanceof WooPoPCozmosLabsPMS\Providers\Order && ! $numberInvoice) {
                        $numerationType = $order->get_billing_choice_type() ?: 'invoice';
                        $number         = \WcElectronInvoice\Functions\getNextInvoiceNumber("number_next_{$numerationType}");
                        if ($number) {
                            // Set invoice number for order.
                            $order->update_meta('order_number_invoice', $number);
                            // Set formatted number
                            \WcElectronInvoice\Functions\setFormattedInvoiceNumber($order, $numerationType);
                            // Save
                            $order->save();
                        }
                    }
                },
                'priority'      => 99,
                'accepted_args' => 2,
            ),
        ),
        'filter' => array(
            array(
                'filter'        => 'pms_get_tax_extra_fields',
                'callback'      => array($orderProvider, 'tax_extra_fields'),
                'priority'      => 99,
                'accepted_args' => 1,
            ),
            array(
                'filter'        => 'wc_el_inv-scripts_list',
                'callback'      => function ($scripts) {
                    $isSdiContext = \WcElectronInvoice\Integrations::isSdiContext();
                    $activeJsCfCheck = \WcElectronInvoice\Admin\Settings\OptionPage::init()->getOptions('invoice_active_js_cf_check');
                    $loadCfScript = $isSdiContext && 'on' === $activeJsCfCheck;
                    $scriptPath = \WooPoPCozmosLabsPMS\Plugin::getPluginDirPath('assets/js/invoiceFields.js');
                    $scriptFile = \WooPoPCozmosLabsPMS\Plugin::getPluginDirUrl('assets/js/invoiceFields.js');
                    if (file_exists(\WooPoPCozmosLabsPMS\Plugin::getPluginDirPath('assets/js/invoiceFields.min.js'))) {
                        $scriptPath = \WooPoPCozmosLabsPMS\Plugin::getPluginDirPath('assets/js/invoiceFields.min.js');
                        $scriptFile = \WooPoPCozmosLabsPMS\Plugin::getPluginDirUrl('assets/js/invoiceFields.min.js');
                    }
                    $scriptVer = file_exists($scriptPath) ? filemtime($scriptPath) : WC_EL_INV_VERSION;

                    $enqueueOnPmsRegister = false;
                    if (function_exists('pms_get_page')) {
                        $registerPageId = (int) pms_get_page('register');
                        $enqueueOnPmsRegister = $registerPageId > 0 && is_page($registerPageId);
                    }

                    return array_merge($scripts, array(
                        array(
                            'handle'    => 'wc_el_inv_cf',
                            'file'      => \WcElectronInvoice\Plugin::getPluginDirUrl('assets/js/cf/codice-fiscale.js'),
                            'deps'      => array(),
                            'ver'       => WC_EL_INV_VERSION,
                            'in_footer' => true,
                            'enqueue'   => $loadCfScript &&
                                           ($enqueueOnPmsRegister || isset($_GET['subscription_plan']) || isset($_GET['pms-action'])),
                        ),
                        array(
                            'handle'    => 'wc_el_inv_invoice',
                            'file'      => $scriptFile,
                            'deps'      => array(),
                            'ver'       => $scriptVer,
                            'in_footer' => true,
                            'enqueue'   => $enqueueOnPmsRegister || isset($_GET['subscription_plan']) || isset($_GET['pms-action']),
                        ),
                    ));
                },
                'priority'      => 99,
                'accepted_args' => 1,
            ),
            array(
                'filter'        => 'wc_el_inv-scripts_localize_list',
                'callback'      => function ($scripts) {
                    $scripts['wc_el_inv_invoice'] = array_merge($scripts['wc_el_inv_invoice'], array(
                        'pop_invalid_tax_code'   => __('Please enter a valid Tax Code.', WC_EL_INV_TEXTDOMAIN),
                        'pop_invalid_vat_number' => __('Please enter a valid VAT number.', WC_EL_INV_TEXTDOMAIN),
                        'pop_invalid_sdi_pec'    => __('Enter a valid SDI code or PEC address.', WC_EL_INV_TEXTDOMAIN),
                    ));

                    return $scripts;
                },
                'priority'      => 99,
                'accepted_args' => 1,
            ),
            array(
                'filter'        => 'wc_el_inv-next_number_already_assigned',
                'callback'      => 'WooPoPCozmosLabsPMS\\Functions\\Utils::cozmosNextNumberAlreadyAssigned',
                'priority'      => 20,
                'accepted_args' => 3,
            ),
            array(
                'filter'        => 'wc_el_inv-next_number_last_assigned_candidate_for_series',
                'callback'      => 'WooPoPCozmosLabsPMS\\Functions\\Utils::cozmosLastAssignedCandidateForSeries',
                'priority'      => 20,
                'accepted_args' => 2,
            ),
            array(
                'filter'        => 'wc_el_inv-next_number_last_assigned_for_series',
                'callback'      => 'WooPoPCozmosLabsPMS\\Functions\\Utils::cozmosLastAssignedNumberForSeries',
                'priority'      => 20,
                'accepted_args' => 3,
            ),
        ),
    ),
);

add_filter('wc_el_inv-filters_front', function ($filtersFront) use ($filters) {
    $filtersFront['front']['action'] = array_merge($filtersFront['front']['action'], $filters['front']['action']);
    $filtersFront['front']['filter'] = array_merge($filtersFront['front']['filter'], $filters['front']['filter']);

    return $filtersFront;
}, 10, 1);
