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

use WcElectronInvoice\Integrations;

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

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

$billingFields = include \WcElectronInvoice\Plugin::getPluginDirPath('/inc/billingFields.php');
$wcTabs        = new \WcElectronInvoice\WooCommerce\Product\Tabs();
$optionPage    = \WcElectronInvoice\Admin\Settings\OptionPage::init();
$invoiceFields = new \WcElectronInvoice\WooCommerce\Fields\InvoiceFields((array)$billingFields, $optionPage);
$quickEdit     = new \WcElectronInvoice\WooCommerce\Product\QuickEditProduct();

//
//  array(
//      'filter'        => ''
//      'callback'      => ''
//      'priority'      => ''
//      'accepted_args' => ''
//  )
//
$filters = array(
    'admin' => array(
        'action' => array(
            /**
             * WooCommerce
             *
             * - set _date_processing_set              @since 6.0.4
             * - set invoice number on order completed @since 1.0.0
             * - set invoice number on order refund    @since 1.0.0
             * - set initial invoice number            @since 1.0.0
             * - extra billing fields                  @since 1.0.0
             * - edit invoice meta                     @since 1.0.0
             * - save invoice meta                     @since 1.0.0
             * - remove sent invoice attachment        @since 1.0.0
             */
            array(
                'filter'        => 'woocommerce_order_status_changed',
                'callback'      => function ($orderID, $from, $to) {
                    if ('processing' === $to) {
                        $order          = wc_get_order($orderID);
                        $processingDate = $order->get_meta('_date_processing_set');
                        if (is_null($processingDate) || $processingDate === '') {
                            $order->update_meta_data('_date_processing_set', current_time('mysql'));
                            $order->save();
                        }
                    }
                },
                'priority'      => 1,
                'accepted_args' => 3,
            ),
            array(
                'filter'        => 'woocommerce_order_status_changed',
                'callback'      => 'WcElectronInvoice\\Functions\\setInvoiceNumberOnOrderCompleted',
                'priority'      => 20,
                'accepted_args' => 3,
            ),
            array(
                'filter'        => 'woocommerce_order_status_changed',
                'callback'      => 'WcElectronInvoice\\Xml\\CreateXml::createXMLOnOrderCompleted',
                'priority'      => PHP_INT_MAX,
                'accepted_args' => 3,
            ),
            array(
                'filter'   => 'woocommerce_refund_created',
                'callback' => 'WcElectronInvoice\\Functions\\setInvoiceNumberOnOrderRefund',
                'priority' => 20,
            ),
            array(
                'filter'   => 'woocommerce_refund_created',
                'callback' => 'WcElectronInvoice\\Xml\\CreateXml::createXMLOnOrderCompleted',
                'priority' => 20,
            ),
            array(
                'filter'   => 'woocommerce_admin_order_data_after_billing_address',
                'callback' => array($invoiceFields, 'viewBillingFieldsFilter'),
                'priority' => 20,
            ),
            array(
                'filter'   => 'woocommerce_admin_order_data_after_order_details',
                'callback' => array($invoiceFields, 'editGeneralFieldsFilter'),
                'priority' => 20,
            ),
            array(
                'filter'   => 'woocommerce_admin_order_items_after_refunds',
                'callback' => array($invoiceFields, 'editInvoiceDataOrderRefund'),
                'priority' => 20,
            ),
            array(
                'filter'   => 'woocommerce_admin_order_totals_after_refunded',
                'callback' => array($invoiceFields, 'refundedPaymentMethod'),
                'priority' => 20,
            ),
            array(
                'filter'   => 'woocommerce_process_shop_order_meta',
                'callback' => array($invoiceFields, 'saveOrderMetaBox'),
                'priority' => 20,
            ),
            array(
                'filter'   => 'woocommerce_process_shop_order_meta',
                'callback' => array($invoiceFields, 'saveRefundMetaBox'),
                'priority' => 20,
            ),

            /**
             * Add product panel data @since 3.0.0
             */
            array(
                'filter'   => 'woocommerce_product_data_panels',
                'callback' => array($wcTabs, 'wooCommerceProductDataPanel'),
                'priority' => 20,
            ),

            /**
             * Store product meta data @since 3.0.0
             */
            array(
                'filter'   => 'woocommerce_process_product_meta',
                'callback' => array($wcTabs, 'storeProductData'),
                'priority' => 20,
            ),

            /**
             * Quick Edit
             *
             * Quick Edit Featured display @since 2.5.2
             * Quick Edit Featured store   @since 2.5.2
             */
            array(
                'filter'        => 'manage_product_posts_custom_column',
                'callback'      => 'WcElectronInvoice\\WooCommerce\\Product\\QuickEditProduct::customColumn',
                'priority'      => 20,
                'accepted_args' => 2,
            ),

            array(
                'filter'        => 'quick_edit_custom_box',
                'callback'      => array($quickEdit, 'display'),
                'priority'      => 10,
                'accepted_args' => 2,
            ),
            array(
                'filter'        => 'bulk_edit_custom_box',
                'callback'      => array($quickEdit, 'displayBulk'),
                'priority'      => 10,
                'accepted_args' => 2,
            ),
            array(
                'filter'        => 'save_post',
                'callback'      => array($quickEdit, 'store'),
                'priority'      => 10,
                'accepted_args' => 2,
            ),

            /**
             * Add orders column @since 3.0.0
             */
            array(
                'filter'        => 'manage_woocommerce_page_wc-orders_custom_column',
                'callback'      => function ($column, $item) use ($invoiceFields) {
                    if ('billing_address' === $column) {
                        $invoiceFields->editGeneralFieldsFilter($item, false, false);

                        do_action('wc_el_inv-after_billing_address_wc-orders_custom_column', $item);
                    }
                },
                'priority'      => 20,
                'accepted_args' => 2,
            ),

            // Order notice
            array(
                'filter'   => 'admin_notices',
                'callback' => function () {
                    $screen = get_current_screen();

                    if (! isset($screen->post_type) || $screen->post_type !== 'shop_order') {
                        return;
                    }

                    // Controlla se i prezzi sono salvati IVA inclusa
                    if (get_option('woocommerce_prices_include_tax') === 'yes') {
                        echo sprintf(
                            '<div class="notice notice-warning" style="margin-top:15px;"><p><strong>%s</strong> %s<br>%s<br><a href="%s" target="_blank">%s</a></p></div>',
                            _x('Warning:', 'iva_included_notice', WC_EL_INV_TEXTDOMAIN),
                            _x('Product prices are set as <u>tax inclusive</u>.', 'iva_included_notice', WC_EL_INV_TEXTDOMAIN),
                            _x('Invoice totals may not match the order totals.', 'iva_included_notice', WC_EL_INV_TEXTDOMAIN),
                            esc_url('https://docs.popapi.io/it/guides/configuration/woocommerce-tax-settings/'),
                            _x('Learn why', 'iva_included_notice', WC_EL_INV_TEXTDOMAIN)
                        );
                    }
                },
                'priority' => 10,
            ),
            array(
                'filter'   => 'admin_notices',
                'callback' => function () {
                    if (! function_exists('get_current_screen')) {
                        return;
                    }

                    $screen = get_current_screen();
                    if (! $screen) {
                        return;
                    }

                    $screenId   = isset($screen->id) ? (string)$screen->id : '';
                    $postType   = isset($screen->post_type) ? (string)$screen->post_type : '';
                    $requestPage = \WcElectronInvoice\Functions\filterInput($_GET, 'page', FILTER_UNSAFE_RAW);

                    $isWooOrderScreen = 'shop_order' === $postType
                        || 'woocommerce_page_wc-orders' === $screenId
                        || 'wc-orders' === $requestPage;

                    if (! $isWooOrderScreen) {
                        return;
                    }

                    $state = \WcElectronInvoice\Functions\getPopApiOverquotaState();
                    if (! is_array($state)) {
                        return;
                    }

                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    echo \WcElectronInvoice\Functions\buildPopApiOverquotaAdminNoticeHtml($state);
                },
                'priority' => 15,
            ),

            /**
             * Delete meta xml/pdf url and file on order update
             */
            array(
                'filter'        => 'woocommerce_update_order',
                'callback'      => function ($orderID) {
                    if (! $orderID) {
                        return;
                    }

                    if (! isset($_POST['action']) || 'edit_order' !== $_POST['action']) {
                        return;
                    }

                    $orderAction = isset($_POST['wc_order_action']) ? sanitize_key((string)wp_unslash($_POST['wc_order_action'])) : '';
                    if (in_array($orderAction, [
                        'send_order_details',
                        'send_order_details_admin',
                    ], true)) {
                        return;
                    }

                    // Get order obj
                    $order = \WcElectronInvoice\Providers\OrderQuery::instance()->getProviderOrder($orderID,
                        'woocommerce');

                    $meta_keys = [
                        'pop_invoice_file_xml',
                        'pop_credit_note_file_xml',
                        'pop_invoice_file_xml_stylized',
                        'pop_credit_note_file_xml_stylized',
                        'pop_invoice_file_pdf',
                        'pop_credit_note_file_pdf',
                        'pop_invoice_file_zugferd_hybrid_pdf',
                        'pop_credit_note_file_zugferd_hybrid_pdf',
                    ];

                    $deleted = false;

                    foreach ($meta_keys as $meta_key) {
                        $file_path = $order->get_meta($meta_key);

                        if ($file_path && file_exists(ABSPATH . $file_path) && is_file(ABSPATH . $file_path)) {
                            if (unlink(ABSPATH . $file_path)) { // Delete file
                                $order->delete_meta($meta_key); // Delete meta
                                $deleted = true;
                            }
                        }
                    }

                    if ($deleted) {
                        $order->save();
                    }
                },
                'priority'      => 10,
                'accepted_args' => 1,
            ),

            /**
             * SDI via POP
             * Cron Jobs on order status change
             */
            array(
                'filter'        => 'woocommerce_order_status_changed',
                'callback'      => function ($orderID, $from, $to) {
                    if (! \WcElectronInvoice\Integrations::isInvoiceChannelActive(\WcElectronInvoice\Integrations::CHANNEL_SDIPOP)) {
                        return;
                    }

                    \WcElectronInvoice\InvoiceApi::changeStatus($orderID, $from, $to);
                },
                'priority'      => 10,
                'accepted_args' => 3,
            ),

            /**
             * PEPPOL via POP
             * Cron Jobs on order status change
             */
            array(
                'filter'        => 'woocommerce_order_status_changed',
                'callback'      => function ($orderID, $from, $to) {
                    if (! \WcElectronInvoice\Integrations::isInvoiceChannelActive(\WcElectronInvoice\Integrations::CHANNEL_PEPPOL)) {
                        return;
                    }

                    \WcElectronInvoice\PeppolApi::changeStatus($orderID, $from, $to);
                },
                'priority'      => 10,
                'accepted_args' => 3,
            ),

            /**
             * Zoho via POP
             * Cron Jobs on order status change
             */
            array(
                'filter'        => 'woocommerce_order_status_changed',
                'callback'      => function ($orderID, $from, $to) {
                    if (! \WcElectronInvoice\Integrations::isInvoiceChannelActive(\WcElectronInvoice\Integrations::CHANNEL_ZOHO)) {
                        return;
                    }

                    \WcElectronInvoice\ZohoApi::changeStatus($orderID, $from, $to);
                },
                'priority'      => 10,
                'accepted_args' => 3,
            ),

            /**
             * POP to Webhook
             * Cron Jobs on order status change
             */
            array(
                'filter'        => 'woocommerce_order_status_changed',
                'callback'      => function ($orderID, $from, $to) {
                    \WcElectronInvoice\Functions\webHookScheduledCron($orderID, $from, $to);
                },
                'priority'      => 10,
                'accepted_args' => 3,
            ),

            /**
             * Refund action for SdI via POP and Webhook
             */
            array(
                'filter'   => 'wc_el_inv-after_refund_order_item_td',
                'callback' => function ($refundID) {
                    $output = '</<tr><tr class="refund wc_el_inv__refund-invoice pop_sdi_and_webhook_actions"><td></td><td colspan="7">';
                    $output .= Integrations::appendConfiguredActions('', $refundID);
                    $output .= '</td>';

                    echo $output;
                },
                'priority' => 30,
            ),
        ),
        'filter' => array(
            /**
             * WooCommerce
             *
             * - customer fields                  @since 1.0.0
             * - billing fields                   @since 1.0.0
             * - ajax customer fields             @since 1.0.0
             * - general setting invoice fields   @since 1.0.0
             * - general setting invoice sanitize @since 1.0.0
             * - wc general notice                @since 1.0.0
             */
            array(
                'filter'   => 'woocommerce_customer_meta_fields',
                'callback' => array($invoiceFields, 'customerFieldsFilter'),
                'priority' => 20,
            ),
            array(
                'filter'   => 'woocommerce_admin_billing_fields',
                'callback' => array($invoiceFields, 'editBillingFieldsFilter'),
                'priority' => 20,
            ),
            array(
                'filter'        => 'woocommerce_ajax_get_customer_details',
                'callback'      => array($invoiceFields, 'foundCustomerMeta'),
                'priority'      => 20,
                'accepted_args' => 3,
            ),

            /**
             * Add product tab @since 1.0.0
             */
            array(
                'filter'   => 'woocommerce_product_data_tabs',
                'callback' => 'WcElectronInvoice\\WooCommerce\\Product\\Tabs::wooCommerceTabsFilter',
                'priority' => 20,
            ),

            /**
             * Add product column @since 3.0.0
             */
            array(
                'filter'   => 'manage_edit-product_columns',
                'callback' => 'WcElectronInvoice\\WooCommerce\\Product\\QuickEditProduct::reverseChargeColumn',
                'priority' => 20,
            ),
        ),
    ),
);

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

    $filtersAdmin['admin']['action'] = array_merge($filtersAdmin['admin']['action'], $filters['admin']['action']);
    $filtersAdmin['admin']['filter'] = array_merge($filtersAdmin['admin']['filter'], $filters['admin']['filter']);

    return $filtersAdmin;
}, 10, 1);
