<?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 WooPoPToFattureInCloud\Api;

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

$resources = new \WooPoPToFattureInCloud\Resources();

//
//  array(
//      'filter'        => '',
//      'callback'      => '',
//      'priority'      => '',
//      'accepted_args' => '',
//  )
//
return apply_filters('wfc-filters_admin', array(
    'admin' => array(
        'action' => array(
            /**
             * Reset Login data
             */
            array(
                'filter'   => 'admin_init',
                'callback' => 'WooPoPToFattureInCloud\\Functions\\resetApi',
                'priority' => 10,
            ),

            /**
             * Fattureincloud Actions Login
             */
            array(
                'filter'   => 'wc_el_inv-before_closing_settings_form',
                'callback' => 'WooPoPToFattureInCloud\\Filters::loginAction',
                'priority' => 10,
            ),

            /**
             * Admin enqueue scripts
             */
            array(
                'filter'   => 'admin_enqueue_scripts',
                'callback' => array($resources, 'enqueue'),
                'priority' => 20,
            ),
            array(
                'filter'   => 'admin_enqueue_scripts',
                'callback' => array($resources, 'register'),
                'priority' => 30,
            ),
            array(
                'filter'   => 'admin_enqueue_scripts',
                'callback' => array($resources, 'localizeScript'),
                'priority' => 40,
            ),

            /**
             * Ajax Modal dialog container
             */
            array(
                'filter'   => 'admin_footer',
                'callback' => function () {
                    echo "<!-- wfc modal -->\n<div class='wfc_ajax_modal close'><div class='modal_content'><div class='modal_card close'></div><span class='close'></span></div></div>\n<!-- /wfc modal -->";
                },
                'priority' => PHP_INT_MAX,
            ),

            /**
             * Print vat type json obj
             */
            array(
                'filter'   => 'admin_head',
                'callback' => function () {
                    $localized = json_encode(Api::getVatTypes());
                    echo "<script type='text/javascript'>\n/* <![CDATA[ */\n";
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    echo "wfcVatTypes" . " = {$localized}\n";
                    echo "/* ]]> */</script>\n";
                },
                'priority' => PHP_INT_MAX,
            ),

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

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

            /**
             * Fattureincloud Actions in column billing_address
             */
            array(
                'filter'   => 'wc_el_inv-after_billing_address_wc-orders_custom_column',
                'callback' => 'WooPoPToFattureInCloud\\Filters::actionsInOrder',
                'priority' => 30,
            ),
        ),
        'filter' => array(
            /**
             * Fattureincloud Actions Title
             */
            array(
                'filter'        => 'wc_el_inv-xml_order_list_table_actions',
                'callback'      => function ($output) {
                    $text = __('Fatture in cloud', WP_FATT_CLOUD_TEXTDOMAIN);

                    return $output . "<h4 class='pop_to_fic_title'>{$text}:</h4>";
                },
                'priority'      => 5,
                'accepted_args' => 3,
            ),

            /**
             * Fattureincloud Actions Import
             */
            array(
                'filter'        => 'wc_el_inv-xml_order_list_table_actions',
                'callback'      => 'WooPoPToFattureInCloud\\Filters::importAction',
                'priority'      => 20,
                'accepted_args' => 3,
            ),

            /**
             * Fattureincloud Actions in order
             */
            array(
                'filter'   => 'woocommerce_admin_order_data_after_order_details',
                'callback' => 'WooPoPToFattureInCloud\\Filters::actionsInOrder',
                'priority' => 30,
            ),

            /**
             * Fattureincloud Actions in refund order
             */
            array(
                'filter'   => 'wc_el_inv-after_refund_order_item_td',
                'callback' => 'WooPoPToFattureInCloud\\Filters::refundActions',
                'priority' => 30,
            ),

            /**
             * Allow core document-data section to render for receipt orders at any status
             */
            array(
                'filter'        => 'wc_el_inv-edit_order_disabled_invoice_fields',
                'callback'      => function ($disabled, $order) {
                    if (! $disabled) {
                        return false;
                    }
                    $choiceType = $order->get_meta('_billing_choice_type') ?: 'invoice';
                    if ('receipt' !== $choiceType) {
                        return $disabled;
                    }

                    return false;
                },
                'priority'      => 10,
                'accepted_args' => 2,
            ),

            /**
             * Include receipt trigger status in the invoice list query when receipt auto-send is active
             */
            array(
                'filter'        => 'wc_el_inv-xml_list_query_args',
                'callback'      => function ($args) {
                    if ('on' !== get_option('wfc_scheduled_receipt_events')) {
                        return $args;
                    }
                    $receiptStatus = get_option('wfc_scheduled_receipt_order_status', 'completed');
                    if (! in_array($receiptStatus, (array) $args['status'], true)) {
                        $args['status'][] = $receiptStatus;
                    }

                    return $args;
                },
                'priority'      => 10,
                'accepted_args' => 1,
            ),

            /**
             * Fattureincloud set invoice number action
             */
            array(
                'filter'        => 'wc_el_inv-list-table-invoice-number',
                'callback'      => function ($number, $order, $prefix) {
                    $numberFic = \WcElectronInvoice\Functions\getPostMeta('wfc-issued_invoice_number', null, $order->get_id(), true, 'order', $order->get_provider() ?: 'woocommerce');
                    $docID     = \WcElectronInvoice\Functions\getPostMeta('wfc-issued_document_id', null, $order->get_id(), true, 'order', $order->get_provider() ?: 'woocommerce');
                    $id        = $order->get_id();

                    if ('shop_order_refund' === $order->get_type()) {
                        $refundOrder   = wc_get_order($id);
                        $refundOrderID = $refundOrder->get_id();
                        $parentOrderID = $refundOrder->get_parent_id();
                        $numberFic     = \WcElectronInvoice\Functions\getPostMeta("wfc-issued_credit_note_{$refundOrderID}_invoice_number", null, $parentOrderID, true, 'order', $order->get_provider() ?: 'woocommerce');
                        $docID         = \WcElectronInvoice\Functions\getPostMeta("wfc-issued_credit_note_{$refundOrderID}_document_id", null, $parentOrderID, true, 'order', $order->get_provider() ?: 'woocommerce');
                    }

                    if ($numberFic && $docID) {
                        // Invoice and Number exist
                        return sprintf(
                            '<span class="fic_number">(#%s)</span>',
                            esc_html($numberFic . $prefix)
                        );
                    } elseif ($docID && ! $numberFic) {
                        // Invoice created but non exist number
                        return sprintf(
                            '<a title="%1$s" href="#" data-id="%2$d" data-docid="%3$s" class="api-action sync_number" id="api_sync_%2$d"><span class="dashicons dashicons-update"></span></a>',
                            esc_attr__('Click to sync with Invoices in Cloud', WP_FATT_CLOUD_TEXTDOMAIN),
                            (int) $id,
                            esc_attr((string) $docID)
                        );
                    } else {
                        // Default - invoice to be created
                        return sprintf(
                            '<span title="%s" class="sync_number dashicons dashicons-hidden"></span>',
                            esc_attr__('Upload to Invoices in the Cloud to synchronize the invoice number', WP_FATT_CLOUD_TEXTDOMAIN)
                        );
                    }
                },
                'priority'      => 30,
                'accepted_args' => 3,
            ),
        ),
    ),
));
