<?php
/**
 * filters.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' => '',
//  )
//

$filters = array(
    'inc' => array(
        'action' => array(
            // process checkout (register_payment)
            array(
                'filter'        => 'pms_register_payment',
                'callback'      => function ($payment_gateway_data) {
                    if (! empty($_POST) && isset($_POST['action']) && 'pms_process_checkout' === $_POST['action']) {
                        $paymentID = (int)$payment_gateway_data['payment_id'];
                        if (! $paymentID) {
                            return;
                        }

                        foreach ($_POST as $key => $value) {
                            if ('pms_invoice_type' === $key || 'pms_sdi_type' === $key || 'pms_vat_number' === $key || 'pms_tax_code' === $key) {
                                pms_update_payment_meta($paymentID, $key, $value);
                            }
                        }

                        $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) {
                            $sanMarinoSupport = \WcElectronInvoice\Functions\sanMarinoSupport($customerInvoiceType,
                                $country);

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

                            // 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_';
                            }

                            // 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,
				                        $paymentID, $_POST );
			                        pms_update_payment_meta( $paymentID, 'nature_rc', $nature );
			                        if ( '' !== $refNormativeValue ) {
				                        $refNormativeValue = apply_filters( 'wc_el_inv-before_ref_norm_rc_pms_save',
					                        $refNormativeValue, $paymentID, $_POST );
				                        pms_update_payment_meta( $paymentID, 'ref_norm_rc', $refNormativeValue );
			                        }
		                        }
	                        }

	                        pms_update_payment_meta( $paymentID, 'order_vies_check', (bool) $vies );
                        }

                        $order         = \WcElectronInvoice\Providers\OrderQuery::instance()->getProviderOrder($paymentID, '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' => 1,
            ),
        ),
        'filter' => array(
            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', function ($filtersInc) use ($filters) {

    $filtersInc['inc']['action'] = array_merge($filtersInc['inc']['action'], $filters['inc']['action']);
    $filtersInc['inc']['filter'] = array_merge($filtersInc['inc']['filter'], $filters['inc']['filter']);

    return $filtersInc;
}, 10, 1);
