<?php
/**
 * filters.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.
}

// if WooCommerce isn't active, do not add any filters
if (! \WcElectronInvoice\Functions\isWooCommerceActive()) {
    return;
}

$ordersProvider   = new \WcElectronInvoice\WooCommerce\Providers\OrdersProvider();
$productsProvider = new \WcElectronInvoice\WooCommerce\Providers\ProductsProvider();
$taxesProvider    = new \WcElectronInvoice\WooCommerce\Providers\TaxesProvider();
$billingFields    = include \WcElectronInvoice\Plugin::getPluginDirPath('/inc/billingFields.php');
$invoiceFields    = new \WcElectronInvoice\WooCommerce\Fields\InvoiceFields((array)$billingFields,
    \WcElectronInvoice\Admin\Settings\OptionPage::init());

//
//  array(
//      'filter'        => ''
//      'callback'      => ''
//      'priority'      => ''
//      'accepted_args' => ''
//  )
//
$wcFilters = array(
    'inc' => array(
        'action' => array(
            /**
             * Remove Tax from order @since 3.0.0
             */
            array(
                'filter'   => 'woocommerce_checkout_update_order_review',
                'callback' => 'WcElectronInvoice\\WooCommerce\\Fields\\InvoiceFields::removeTaxFromOrder',
                'priority' => 100,
            ),
            // Store Api
            array(
                'filter'   => 'woocommerce_before_calculate_totals',
                'callback' => function ($postData) {
                    if (\WcElectronInvoice\Functions\isStoreApiRequest()) {
                        \WcElectronInvoice\WooCommerce\Fields\InvoiceFields::removeTaxFromOrder($postData);
                    }
                },
                'priority' => 100,
            ),
            array(
                'filter'   => 'woocommerce_store_api_checkout_update_order_from_request',
                'callback' => 'WcElectronInvoice\\WooCommerce\\Fields\\InvoiceFields::removeTaxFromOrder',
                'priority' => 100,
            ),

            /**
             * Add: stamp duty fee @since 4.6.2
             */
            array(
                'filter'   => 'woocommerce_cart_calculate_fees',
                'callback' => 'WcElectronInvoice\\WooCommerce\\Fields\\InvoiceFields::addStampDutyFee',
                'priority' => 100,
            ),

            /**
             * Add: rivalsa INPS fee @since {SIZE}
             */
            array(
                'filter'   => 'woocommerce_cart_calculate_fees',
                'callback' => 'WcElectronInvoice\\WooCommerce\\Fields\\InvoiceFields::addRivalsaInpsFee',
                'priority' => 100,
            ),

            /**
             * Create order item line (add custom meta) @since 3.0.0
             */
            array(
                'filter'        => 'woocommerce_checkout_create_order_line_item',
                'callback'      => 'WcElectronInvoice\\WooCommerce\\Fields\\InvoiceFields::addMetaCartItemLine',
                'priority'      => 10,
                'accepted_args' => 4,
            ),

            // registering orders provider for WooCommerce
            array(
                'filter'        => 'wc_el_inv-enqueue_orders_provider',
                'callback'      => array($ordersProvider, 'enqueue'),
                'priority'      => 11,
                'accepted_args' => 1,
            ),

            // registering product provider for WooCommerce
            array(
                'filter'        => 'wc_el_inv-enqueue_products_provider',
                'callback'      => array($productsProvider, 'enqueue'),
                'priority'      => 10,
                'accepted_args' => 1,
            ),

            // registering product provider for WooCommerce
            array(
                'filter'        => 'wc_el_inv-enqueue_taxes_provider',
                'callback'      => array($taxesProvider, 'enqueue'),
                'priority'      => 10,
                'accepted_args' => 1,
            ),

            // Remove temp Pdf files after sent completed email @since 1.0.0
            array(
                'filter'        => 'woocommerce_email_sent',
                'callback'      => function ($return, $emilID, $emailObj) {
                    $pdf = new \WcElectronInvoice\Pdf\CreatePdf();
                    $pdf->removeSentInvoice($return, $emilID, $emailObj);
                },
                'priority'      => PHP_INT_MAX,
                'accepted_args' => 3,
            ),
            array(
                'filter'        => 'woocommerce_email_customer_details',
                'callback'      => array($invoiceFields, 'renderTaxInformationInEmail'),
                'priority'      => 30,
                'accepted_args' => 4,
            ),

            /**
             * Cron Jobs Import UBL (PEPPOL)
             */
            array(
                'filter'        => array(
                    'PoPToPEPPOLJobsScheduledImport',
                ),
                'callback'      => function ($orderID, $provider) {
                    $_POST = [
                        'id'       => $orderID,
                        'provider' => $provider,
                        'action'   => 'createAndSendUblInvoice',
                        'method'   => 'cronjob',
                    ];
                    \WcElectronInvoice\PeppolApi::createAndSendUblInvoice();
                },
                'priority'      => 10,
                'accepted_args' => 2,
            ),

            /**
             * Cron Jobs Import KSeF
             */
            array(
                'filter'        => array(
                    'PoPToKSeFJobsScheduledImport',
                ),
                'callback'      => function ($orderID, $provider) {
                    $_POST = [
                        'id'       => $orderID,
                        'provider' => $provider,
                        'action'   => 'createAndSendKsefInvoice',
                        'method'   => 'cronjob',
                    ];
                    \WcElectronInvoice\KsefApi::createAndSendKsefInvoice();
                },
                'priority'      => 10,
                'accepted_args' => 2,
            ),

            /**
             * Cron Jobs Import Zoho
             */
            array(
                'filter'        => array(
                    'PoPToZohoJobsScheduledImport',
                ),
                'callback'      => function ($orderID, $provider) {
                    $_POST = [
                        'id'       => $orderID,
                        'provider' => $provider,
                        'action'   => 'createAndSendZohoInvoice',
                        'method'   => 'cronjob',
                    ];
                    \WcElectronInvoice\ZohoApi::createAndSendZohoInvoice();
                },
                'priority'      => 10,
                'accepted_args' => 2,
            ),

            /**
             * Cron Jobs Import XML (FatturaPA)
             */
            array(
                'filter'        => array(
                    'PoPToSDIJobsScheduledImport',
                ),
                'callback'      => function ($orderID, $provider) {
                    $_POST = [
                        'id'       => $orderID,
                        'provider' => $provider,
                        'action'   => 'createAndSendInvoice',
                        'method'   => 'cronjob',
                    ];
                    \WcElectronInvoice\InvoiceApi::createAndSendInvoice();
                },
                'priority'      => 10,
                'accepted_args' => 2,
            ),

            /**
             * Cron Jobs Notify
             */
            array(
                'filter'        => array(
                    'PoPToSDIJobsScheduledNotify',
                ),
                'callback'      => function ($orderID, $uuid, $provider) {
                    $_POST = [
                        'id'       => $orderID,
                        'uuid'     => $uuid,
                        'provider' => $provider,
                        'action'   => 'notificationsInvoice',
                        'method'   => 'cronjob',
                    ];
                    \WcElectronInvoice\InvoiceApi::notificationsInvoice();
                },
                'priority'      => 10,
                'accepted_args' => 3,
            ),

            /**
             * Webhook Cron Jobs Import
             */
            array(
                'filter'        => array(
                    'PoPToWebhookJobsScheduledImport',
                ),
                'callback'      => function ($orderID, $provider) {
                    $_POST = [
                        'id'       => $orderID,
                        'provider' => $provider,
                        'action'   => 'sendWebhook',
                        'method'   => 'cronjob',
                    ];
                    \WcElectronInvoice\Functions\sendWebhook();
                },
                'priority'      => 10,
                'accepted_args' => 2,
            ),

            // Vies check for checkout block
            array(
                'filter'   => array('wp_ajax_popCheckoutViesCheck', 'wp_ajax_nopriv_popCheckoutViesCheck'),
                'callback' => function () {
                    \WcElectronInvoice\Functions\popCheckoutViesCheck();
                },
                'priority' => 10,
            ),

            // Fix workaround - remove Duplicate Meta
            array(
                'filter'        => 'woocommerce_order_status_changed',
                'callback'      => function($orderID, $from, $to) {
                    $status1Check = apply_filters('wc_el_inv-set_invoice_number_status1_check', 'completed');
                    $status2Check = apply_filters('wc_el_inv-set_invoice_number_status2_check', 'processing');

                    if (($status1Check === $from)
                        ||
                        (
                            $status1Check !== $to
                            &&
                            $status2Check !== $to
                        )
                    ) {
                        return;
                    }

                    \WcElectronInvoice\Functions\removeDuplicateMeta($orderID);
                },
                'priority'      => 1000,
                'accepted_args' => 3,
            ),

        ),
        'filter' => array(

            /**
             * POP Emails
             */
            array(
                'filter'   => 'woocommerce_email_classes',
                'callback' => function ($emails) {
                    /**
                     * Support: Edit emails template elementor
                     * - not include custom emails whit elementor action
                     */
                    $actionGet  = \WcElectronInvoice\Functions\filterInput($_GET, 'action');
                    $actionPost = \WcElectronInvoice\Functions\filterInput($_POST, 'action');
                    if ('elementor' === $actionGet ||
                        ('elementor_ajax' === $actionPost &&
                         defined('DOING_AJAX') && DOING_AJAX)
                    ) {
                        // Default WC emails
                        return $emails;
                    }

                    // Merge custom Emails
                    return \WcElectronInvoice\WooCommerce\Emails\WooPopEmails::emailClasses($emails);
                },
                'priority' => 10,
            ),
            array(
                'filter'   => 'woocommerce_email_actions',
                'callback' => 'WcElectronInvoice\\WooCommerce\\Emails\\WooPopEmails::emailActions',
                'priority' => 10,
            ),

            /**
             * Automatically set the order's status to complete and set invoice number
             *
             * @since 4.1.5
             */
            array(
                'filter'        => 'woocommerce_payment_complete_order_status',
                'callback'      => function ($status, $orderID, $order) {
                    // Set the invoice number if necessary
                    \WcElectronInvoice\Functions\setInvoiceNumberOnOrderAutoCompleted($orderID);

                    return $status;
                },
                'priority'      => PHP_INT_MAX,
                'accepted_args' => 3,
            ),

            /**
             * Dependencies:
             * - WooCommerce
             * Remove products with a zero total
             */
            array(
                'filter'   => 'wc_el_inv-shop_items_remove_product_zero_total',
                'callback' => function () {
                    return \WcElectronInvoice\Functions\removeProductTotalZeroOption();
                },
                'priority' => 10,
            ),

            // wc mail completed attachments    @since 1.0.0
            array(
                'filter'        => 'woocommerce_email_attachments',
                'callback'      => function ($attachments, $emailID, $order) {
                    $pdf         = new \WcElectronInvoice\Pdf\CreatePdf();
                    $attachments = $pdf->attachmentsPdfToEmail($attachments, $emailID, $order);

                    return is_array($attachments) ? $attachments : array();
                },
                'priority'      => PHP_INT_MAX,
                'accepted_args' => 3,
            ),
        ),
    ),
);

add_filter('wc_el_inv-filters', function ($filters) use ($wcFilters) {

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

    return $filters;
}, 10, 1);
