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

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

$jobs = new \WooPoPToFattureInCloud\Jobs();

//
//  array(
//      'filter'        => '',
//      'callback'      => '',
//      'priority'      => '',
//      'accepted_args' => '',
//  )
//
return apply_filters('wfc-filters', array(
    'inc' => array(
        'action' => array(
            /**
             * ExchangeCode
             */
            array(
                'filter'   => 'template_redirect',
                'callback' => 'WooPoPToFattureInCloud\\Functions\\getExchangeCode',
                'priority' => 10,
            ),

            /**
             * Twice daily Cron Jobs Import
             */
            array(
                'filter'   => 'init',
                'callback' => 'WooPoPToFattureInCloud\\Jobs::twiceDailyCreateInvoice',
                'priority' => PHP_INT_MAX,
            ),

            /**
             * Cron Jobs Import
             */
            array(
                'filter'        => array(
                    'WooPoPToFattureInCloudJobsScheduledImport',
                ),
                'callback'      => function($id, $provider) {
                    \WooPoPToFattureInCloud\Jobs::createInvoice($id, $provider);
                },
                'priority'      => 10,
                'accepted_args' => 2,
            ),

            /**
             * Set meta for Sending Pro Forma
             */
            array(
                'filter'        => 'woocommerce_email_sent',
                'callback'      => function ($return, $emilID, $emailObj) {
                    // FIC Addon.
                    // Send attachments via email ?
                    $activeSendInvoiceEmail = \WcElectronInvoice\Admin\Settings\OptionPage::init()->getOptions('invoice_via_email') ?: 'off';
                    if (class_exists('WooPoPToFattureInCloud\Plugin') && 'off' !== $activeSendInvoiceEmail) {
                        if ($emailObj instanceof WC_Email && 'customer_invoice' === $emilID) {
                            $order      = $emailObj->object;
                            $documentID = \WcElectronInvoice\Functions\getPostMeta("wfc-issued_document_id", null,
                                $order->get_id());
                            if (is_a($order, 'WC_Order') && $documentID) {
                                $order->update_meta_data('wfc-sending_proforma', true);
                                // Save
                                $order->save();
                            }
                        }
                    }
                },
                'priority'      => PHP_INT_MAX,
                'accepted_args' => 3,
            ),

            /**
             * Allowed customer email invoice
             */
            array(
                'filter'        => 'wc_el_inv-allowed_email_id_for_attachment',
                'callback'      => function ($allowedEmailID, $orderID) {
                    $order      = wc_get_order($orderID);
                    $useFicPdf  = get_option('wfc_use_fic_pdf');
                    $documentID = \WcElectronInvoice\Functions\getPostMeta("wfc-issued_document_id", null, $orderID);

                    if ($order->has_status('completed') && ! $documentID && 'on' === $useFicPdf) {
                        $allowedEmailID = array();
                    }

                    if ($documentID) {
                        $allowedEmailID = array(
                            'customer_invoice',
                        );
                    }

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

            /**
             * Filter use external attachments pdf for email
             * Filter attachments pdf for email
             */
            array(
                'filter'        => 'wc_el_inv-use_external_attachments',
                'callback'      => function () {
                    $useFicPdf = get_option('wfc_use_fic_pdf');

                    return ('on' === $useFicPdf);
                },
                'priority'      => 20,
                'accepted_args' => 3,
            ),

            /**
             * Invoice notes
             */
            array(
                'filter'        => 'wfc-invoice_body_data_notes',
                'callback'      => function ($notes, $orderID) {
                    $invoiceNotes = get_option('wfc_invoice_notes');
                    if ('on' === $invoiceNotes) {
                        $order = wc_get_order($orderID);
                        // Check WC_Order instance
                        $wcOrderClass = \WooPoPToFattureInCloud\Functions\wcOrderClassName($order, '\WC_Order');

                        if ($order instanceof $wcOrderClass) {
                            return \WcElectronInvoice\Functions\plainTextFromHtml($order->get_customer_note(), true) ?: '';
                        }
                    }

                    return $notes;
                },
                'priority'      => 20,
                'accepted_args' => 2,
            ),

            array(
                'filter'        => 'wc_el_inv-attachments_invoice_pdf_output',
                'callback'      => function ($pdfOutput, $orderID) {
                    $useFicPdf = get_option('wfc_use_fic_pdf');
                    if ('on' === $useFicPdf) {
                        // Fic PDF
                        $documentID     = \WcElectronInvoice\Functions\getPostMeta("wfc-issued_document_id", null,
                            $orderID) ?? null;
                        $documentPdfUrl = \WcElectronInvoice\Functions\getPostMeta('wfc-issued_document_pdf_url', null,
                            $orderID) ?? null;
                        if ($documentID && $documentPdfUrl) {
                            if (! ini_get('allow_url_fopen')) {
                                @ini_set('allow_url_fopen', '1');
                            }
                            $pdfRemote = wp_remote_fopen(esc_url_raw($documentPdfUrl));
                            if ($pdfRemote) {
                                $pdfOutput = $pdfRemote;
                            }
                        }
                    }

                    return $pdfOutput;
                },
                'priority'      => 10,
                'accepted_args' => 2,
            ),
        ),
        'filter' => array(
            array(
                'filter'   => 'wc_el_inv-diagnostic_logs',
                'callback' => function ($logs) {
                    $config                 = \WooPoPToFattureInCloud\Functions\getLogConfig();
                    $logs[$config['key']] = $config;

                    return $logs;
                },
                'priority' => 10,
            ),

            /**
             * WFC Options
             */
            array(
                'filter'   => 'allowed_options',
                'callback' => function ($allowedOptions) {
                    $data       = ! empty($_POST['wc_el_inv_options']) ? $_POST['wc_el_inv_options'] : array();
                    $wfcOptions = \WooPoPToFattureInCloud\Functions\filterInput($_POST, 'wfc_options',
                        FILTER_UNSAFE_RAW);

                    if (isset($wfcOptions) && '1' === $wfcOptions) {

                        // Active Cron Job (for status)
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_scheduled_order_status']) &&
                            '' !== $data['wc_el_inv-settings-wfc_scheduled_order_status']
                        ) {
                            update_option('wfc_scheduled_order_status',
                                $data['wc_el_inv-settings-wfc_scheduled_order_status']);
                        } else {
                            // Default "completed"
                            update_option('wfc_scheduled_order_status', 'completed');
                        }

                        // Receipt/corrispettivo trigger status
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_scheduled_receipt_order_status']) &&
                            '' !== $data['wc_el_inv-settings-wfc_scheduled_receipt_order_status']
                        ) {
                            update_option('wfc_scheduled_receipt_order_status',
                                $data['wc_el_inv-settings-wfc_scheduled_receipt_order_status']);
                        } else {
                            update_option('wfc_scheduled_receipt_order_status', 'completed');
                        }

                        // Receipt/corrispettivo auto-send (single event, immediate)
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_scheduled_receipt_events']) &&
                            'on' === $data['wc_el_inv-settings-wfc_scheduled_receipt_events']
                        ) {
                            update_option('wfc_scheduled_receipt_events', 'on');
                        } else {
                            update_option('wfc_scheduled_receipt_events', 'off');
                        }

                        // Active Cron Job (single event)
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_scheduled_events']) &&
                            'on' === $data['wc_el_inv-settings-wfc_scheduled_events']
                        ) {
                            if (get_option('wfc_scheduled_events') !== 'on') {
                                update_option('wfc_scheduled_events', 'on');
                            }
                        } else {
                            update_option('wfc_scheduled_events', 'off');
                        }

                        // Active Cron Job (twice daily)
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_scheduled_twicedaily_events']) &&
                            'on' === $data['wc_el_inv-settings-wfc_scheduled_twicedaily_events']
                        ) {
                            if (get_option('wfc_scheduled_twicedaily_events') !== 'on') {
                                update_option('wfc_scheduled_twicedaily_events', 'on');
                            }
                        } else {
                            update_option('wfc_scheduled_twicedaily_events', 'off');
                        }

                        // Disables the automatic sending of invoices to the SDI
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_disabled_sending_sdi']) &&
                            'on' === $data['wc_el_inv-settings-wfc_disabled_sending_sdi']
                        ) {
                            if (get_option('wfc_disabled_sending_sdi') !== 'on') {
                                update_option('wfc_disabled_sending_sdi', 'on');
                            }
                        } else {
                            update_option('wfc_disabled_sending_sdi', 'off');
                        }

                        // Event scheduled time
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_scheduled_events_time']) &&
                            '' !== $data['wc_el_inv-settings-wfc_scheduled_events_time']
                        ) {
                            update_option('wfc_scheduled_events_time',
                                $data['wc_el_inv-settings-wfc_scheduled_events_time']);
                        } else {
                            update_option('wfc_scheduled_events_time', '');
                        }

                        // Send an email for failure to create document
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_error_sending_invoice']) &&
                            'on' === $data['wc_el_inv-settings-wfc_error_sending_invoice']
                        ) {
                            if (get_option('wfc_error_sending_invoice') !== 'on') {
                                update_option('wfc_error_sending_invoice', 'on');
                            }
                        } else {
                            update_option('wfc_error_sending_invoice', 'off');
                        }

                        // Use the "Fatture in Cloud" PDF document as an attachment to the Invoice email
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_use_fic_pdf']) &&
                            'on' === $data['wc_el_inv-settings-wfc_use_fic_pdf']
                        ) {
                            if (get_option('wfc_use_fic_pdf') !== 'on') {
                                update_option('wfc_use_fic_pdf', 'on');
                            }
                        } else {
                            update_option('wfc_use_fic_pdf', 'off');
                        }

                        // Invoice notes
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_invoice_notes']) &&
                            'on' === $data['wc_el_inv-settings-wfc_invoice_notes']
                        ) {
                            if (get_option('wfc_invoice_notes') !== 'on') {
                                update_option('wfc_invoice_notes', 'on');
                            }
                        } else {
                            update_option('wfc_invoice_notes', 'off');
                        }

                        // Invoice shipping address
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_invoice_shipping_address']) &&
                            'on' === $data['wc_el_inv-settings-wfc_invoice_shipping_address']
                        ) {
                            if (get_option('wfc_invoice_shipping_address') !== 'on') {
                                update_option('wfc_invoice_shipping_address', 'on');
                            }
                        } else {
                            update_option('wfc_invoice_shipping_address', 'off');
                        }

                        // Revenue center
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_revenue_center']) &&
                            '' !== $data['wc_el_inv-settings-wfc_revenue_center']
                        ) {
                            update_option('wfc_revenue_center',
                                $data['wc_el_inv-settings-wfc_revenue_center']);
                        } else {
                            update_option('wfc_revenue_center', '');
                        }

                        // Vat kind
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_data_vat_kind']) &&
                            '' !== $data['wc_el_inv-settings-wfc_data_vat_kind']
                        ) {
                            update_option('wfc_data_vat_kind',
                                $data['wc_el_inv-settings-wfc_data_vat_kind']);
                        } else {
                            update_option('wfc_data_vat_kind', '');
                        }

                        // Slack integration
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_slack_integration']) &&
                            'on' === $data['wc_el_inv-settings-wfc_slack_integration']
                        ) {
                            if (get_option('wfc_slack_integration') !== 'on') {
                                update_option('wfc_slack_integration', 'on');
                                \WooPoPToFattureInCloud\Functions\slack(
                                    WP_FATT_CLOUD_NAME . ' - ' . __('Slack integration is active!',
                                        WP_FATT_CLOUD_TEXTDOMAIN),
                                    false,
                                    ':white_check_mark:'
                                );
                            }
                        } else {
                            update_option('wfc_slack_integration', 'off');
                        }
                        // Slack API token
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_slack_integration_token']) &&
                            '' !== $data['wc_el_inv-settings-wfc_slack_integration_token']
                        ) {
                            update_option('wfc_slack_integration_token',
                                $data['wc_el_inv-settings-wfc_slack_integration_token']);
                        } else {
                            update_option('wfc_slack_integration_token', '');
                        }
                        // Slack Channel
                        if (! empty($data) &&
                            isset($data['wc_el_inv-settings-wfc_slack_integration_channel']) &&
                            '' !== $data['wc_el_inv-settings-wfc_slack_integration_channel']
                        ) {
                            update_option('wfc_slack_integration_channel',
                                $data['wc_el_inv-settings-wfc_slack_integration_channel']);
                        } else {
                            update_option('wfc_slack_integration_channel', '');
                        }
                    }

                    return $allowedOptions;
                },
                'priority' => PHP_INT_MAX,
            ),

            /**
             * Filter N4 vat type id
             */
            array(
                'filter'   => 'wfc-vat_type_N4_fic_id',
                'callback' => function ($vatID) {
                    if (function_exists('\WcElectronInvoice\Functions\getN4RefNormative')) {
                        return \WcElectronInvoice\Functions\getN4RefNormative(true);
                    }
                },
                'priority' => 10,
            ),

            /**
             * Revenue center
             */
            array(
                'filter'   => 'wfc-invoice_body_data_rc_center',
                'callback' => function () {
                    return get_option('wfc_revenue_center') ?? '';
                },
                'priority' => 10,
            ),

            /**
             * Vat kind
             */
            array(
                'filter'   => 'wfc-invoice_body_ei_data_vat_kind',
                'callback' => function () {
                    $vatKind = get_option('wfc_data_vat_kind');

                    return $vatKind && '' !== $vatKind ? $vatKind : null;
                },
                'priority' => 10,
            ),

            /**
             * Fattureincloud set invoice number for xml and pdf
             */
            array(
                'filter'        => array(
                    'wc_el_inv-create-xml-invoice-number',
                    'wc_el_inv-create-pdf-invoice-number',
                ),
                'callback'      => function ($number, $order, $prefix) {
                    $numberFic = \WcElectronInvoice\Functions\getPostMeta('wfc-issued_invoice_number', null,
                        $order->get_id());

                    if ($numberFic) {
                        return "{$numberFic}{$prefix}";
                    }

                    return $number;
                },
                'priority'      => 30,
                'accepted_args' => 3,
            ),

            /**
             * Receipt scheduling gate — allows changeStatus() to schedule receipt jobs
             * beyond the invoice-status guard.
             */
            array(
                'filter'        => 'wfc-change_status_schedule_allowed',
                'callback'      => function ($allowed, $order, $from, $to, $provider) {
                    if ($allowed) {
                        return true;
                    }
                    if ('on' !== get_option('wfc_scheduled_receipt_events')) {
                        return false;
                    }
                    if ('receipt' !== $order->get_billing_choice_type()) {
                        return false;
                    }
                    $receiptStatus = get_option('wfc_scheduled_receipt_order_status', 'completed');

                    return \WooPoPToFattureInCloud\Jobs::hasReachedAutomationStatus((string)$to, (string)$receiptStatus);
                },
                'priority'      => 10,
                'accepted_args' => 5,
            ),

            /**
             * Receipt execution gate — allows the scheduled job to proceed for receipt orders.
             */
            array(
                'filter'        => 'wfc-create_invoice_job_status_allowed',
                'callback'      => function ($allowed, $order, $valueOrderStatus, $orderStatus, $provider) {
                    if ($allowed) {
                        return true;
                    }
                    if ('receipt' !== $order->get_billing_choice_type()) {
                        return false;
                    }
                    $receiptStatus = get_option('wfc_scheduled_receipt_order_status', 'completed');

                    return \WooPoPToFattureInCloud\Jobs::hasReachedAutomationStatus((string)$orderStatus, (string)$receiptStatus);
                },
                'priority'      => 10,
                'accepted_args' => 5,
            ),

            /**
             * Receipt status gate — allows createInvoice() (manual and job) for receipt orders.
             */
            array(
                'filter'        => 'wfc-create_invoice_status_allowed',
                'callback'      => function ($allowed, $order, $choiceType, $orderType, $jobEvent, $provider) {
                    if ($allowed) {
                        return true;
                    }
                    if ('receipt' !== $choiceType) {
                        return false;
                    }
                    // Manual upload: always allow regardless of status.
                    if (! $jobEvent) {
                        return true;
                    }
                    // Scheduled job: check configured receipt trigger status.
                    $receiptStatus = get_option('wfc_scheduled_receipt_order_status', 'completed');

                    return \WooPoPToFattureInCloud\Jobs::hasReachedAutomationStatus((string)$order->get_status(), (string)$receiptStatus);
                },
                'priority'      => 10,
                'accepted_args' => 6,
            ),
        ),
    ),
));
