<?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 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\Plugin;
use WcElectronInvoice\Wizard;
use function WcElectronInvoice\Functions\popDeleteSavedFiles;

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

// include filtersAdmin.php for WooCommerce
include_once \WcElectronInvoice\Plugin::getPluginDirPath('/inc/wc/filtersAdmin.php');

//$endPointApi   = new \WcElectronInvoice\EndPoint\Endpoints();
$billingFields = include_once \WcElectronInvoice\Plugin::getPluginDirPath('/inc/wc/billingFields.php');
$resources     = new \WcElectronInvoice\Resources();
$optionPage    = \WcElectronInvoice\Admin\Settings\OptionPage::init();
$invoiceFields = new \WcElectronInvoice\WooCommerce\Fields\InvoiceFields((array)$billingFields, $optionPage);

//  array(
//      'filter'        => ''
//      'callback'      => ''
//      'priority'      => ''
//      'accepted_args' => ''
//  )
//
$filtersAdmin = array(
    'admin' => array(
        'action' => array(
            /**
             * Admin notice
             */
            array(
                'filter'   => 'wc_el_inv-plugin_header_notice',
                'callback' => function () {
                    if ($message = get_transient('wc_el_inv-options-saved-message')) {
                        \WcElectronInvoice\Functions\showAdminNotice($message, 'success', '', null);
                        delete_transient('wc_el_inv-options-saved-message');
                    }

                    if ($warnings = get_transient('wc_el_inv-number-next-override-warning')) {
                        $labels = [
                            'number_next_invoice' => esc_html__('Invoice', WC_EL_INV_TEXTDOMAIN),
                            'number_next_receipt' => esc_html__('Receipt', WC_EL_INV_TEXTDOMAIN),
                        ];
                        foreach ($warnings as $optionKey => $info) {
                            $label   = $labels[$optionKey] ?? $optionKey;
                            $message = sprintf(
                                /* translators: 1: document type, 2: value set by user, 3: last assigned number, 4: value that will actually be used */
                                esc_html__('%1$s - the number you entered (%2$d) is lower than or equal to the last number already issued in the current series (%3$d). To prevent duplicate document numbers the system will use %4$d as the next number. To reset numbering for a new year enable "Reset numeration on year change" in settings.',
                                    WC_EL_INV_TEXTDOMAIN),
                                '<b>' . $label . '</b>',
                                $info['set_value'],
                                $info['last_assigned'],
                                $info['will_use']
                            );
                            \WcElectronInvoice\Functions\showAdminNotice($message, 'warning', '', null, true);
                        }
                        delete_transient('wc_el_inv-number-next-override-warning');
                    }

                    \WcElectronInvoice\Functions\popNoticeIfNginx();
                },
                'priority' => 10,
            ),
            array(
                'filter'   => 'wc_el_inv-plugin_header_notice',
                'callback' => function () {
                    $page = \WcElectronInvoice\Functions\filterInput($_GET, 'page', FILTER_UNSAFE_RAW);
                    $tab  = \WcElectronInvoice\Functions\filterInput($_GET, 'tab', FILTER_UNSAFE_RAW);

                    if ('wc_el_inv-options-page' !== $page || 'xml' !== $tab) {
                        return;
                    }

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

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

            /**
             * PMPRo info notice
             */
//            array(
//                'filter'   => 'wc_el_inv-plugin_header_notice',
//                'callback' => function () {
//                    $page         = \WcElectronInvoice\Functions\filterInput($_GET, 'page', FILTER_UNSAFE_RAW);
//                    $tab          = \WcElectronInvoice\Functions\filterInput($_GET, 'tab', FILTER_UNSAFE_RAW);
//                    $allowedAddon = \WcElectronInvoice\Plugin::allowedAddon();
//                    $list         = \WcElectronInvoice\Functions\getListKeyValue($allowedAddon, 'item_code', 'status');
//                    $pmPro        = \WcElectronInvoice\Functions\getActiveAddon('WP-POP-PMPRO', $list);
//                    $statusPMPro  = \WcElectronInvoice\Functions\isPaidMembershipsProActive() && $pmPro;
//                    $pmProActive  = boolval(get_option('wc_el_inv-addon-pmpro'));
//
//                    if ($pmPro && $statusPMPro && $pmProActive && 'wc_el_inv-options-page' === $page && 'integration' === $tab) {
//                        $message = __('You have activated the <b>POP integration for Paid Memberships Pro</b>. Please note this is a <b>beta version</b>:<br><u>The 4% INPS surcharge and the €2 digital stamp (bollo) chargeable to the customer are not yet supported.</u>',
//                            WC_EL_INV_TEXTDOMAIN);
//                        \WcElectronInvoice\Functions\showAdminNotice($message, 'warning', '', null, true);
//                    }
//                },
//                'priority' => 10,
//            ),

            /**
             * Disable console log
             */
            array(
                'filter'        => 'in_plugin_update_message-woopop-electronic-invoice/index.php',
                'callback'      => function ($data, $response) {
                    echo "<script>console.log = function (){}; window.console.log = function (){}</script>";
                },
                'priority'      => 10,
                'accepted_args' => 2,
            ),

            /**
             * Set Fallback number is setOption not save
             */
            array(
                'filter'   => 'init',
                'callback' => 'WcElectronInvoice\\Functions\\setCreditNoteFallBackNumeration',
                'priority' => PHP_INT_MAX,
            ),

            /**
             * Options
             *
             * - addPluginPage   @since 1.0.0
             * - pageOptionsInit @since 1.0.0
             */
            array(
                'filter'   => 'admin_menu',
                'callback' => array($optionPage, 'addPluginPage'),
                'priority' => 10,
            ),
            array(
                'filter'   => 'admin_init',
                'callback' => array($optionPage, 'pageOptionsInit'),
                'priority' => 10,
            ),

            /**
             * Freshworks widget (admin settings page)
             *
             * Printed after the settings form via `do_action('wc_el_inv-after_settings_form');`.
             */
            array(
                'filter'   => 'wc_el_inv-after_settings_form',
                'callback' => function () {
                    $enabled = apply_filters('wc_el_inv-enable_freshworks_widget', true);
                    if (! $enabled) {
                        return;
                    }

                    if (function_exists('wp_doing_ajax') && wp_doing_ajax()) {
                        return;
                    }

                    if (! current_user_can(apply_filters('wc_el_inv-options-capability', Plugin::$capability))) {
                        return;
                    }

                    $widgetId = (int) apply_filters('wc_el_inv-freshworks_widget_id', 203000000092);
                    if ($widgetId <= 0) {
                        return;
                    }

                    $settings = wp_json_encode(array('widget_id' => $widgetId));
                    if (! $settings) {
                        return;
                    }

                    $inlineJs = 'window.fwSettings = ' . $settings . ';'
                        . '!function(){'
                        . 'if("function"!=typeof window.FreshworksWidget){'
                        . 'var n=function(){n.q.push(arguments)};'
                        . 'n.q=[],window.FreshworksWidget=n'
                        . '}'
                        . '}();';

                    $src = 'https://euc-widget.freshworks.com/widgets/' . rawurlencode((string) $widgetId) . '.js';

                    echo "\n<!-- FreshworksWidget -->\n";

                    if (function_exists('wp_print_inline_script_tag')) {
                        wp_print_inline_script_tag($inlineJs);
                    } else {
                        echo '<script>' . $inlineJs . '</script>' . "\n";
                    }

                    if (function_exists('wp_print_script_tag')) {
                        wp_print_script_tag(
                            array(
                                'type'  => 'text/javascript',
                                'src'   => esc_url($src),
                                'async' => true,
                                'defer' => true,
                            )
                        );
                    } else {
                        echo '<script type="text/javascript" src="' . esc_url($src) . '" async defer></script>' . "\n";
                    }
                },
                'priority' => 20,
            ),

            /**
             * Enqueue @since 1.0.0
             */
            array(
                'filter'   => 'admin_enqueue_scripts',
                'callback' => array($resources, 'register'),
                'priority' => 10,
            ),
            array(
                'filter'   => 'admin_enqueue_scripts',
                'callback' => array($resources, 'enqueue'),
                'priority' => 20,
            ),
            array(
                'filter'   => 'admin_enqueue_scripts',
                'callback' => array($resources, 'localizeScript'),
                'priority' => 30,
            ),

/**
             * Ajax mark "sent/no_sent" invoice
             */
            array(
                'filter'   => 'wp_ajax_markInvoice',
                'callback' => array($invoiceFields, 'markInvoice'),
                'priority' => 10,
            ),

            /**
             * Ajax processFileBatch for bulk download
             */
            array(
                'filter'   => 'wp_ajax_processFileBatch',
                'callback' => 'WcElectronInvoice\Functions\processFileBatch',
                'priority' => 10,
            ),

            /**
             * Ajax processFileBatch for bulk download
             */
            array(
                'filter'   => 'wp_ajax_processFileBatch',
                'callback' => 'WcElectronInvoice\\Functions\\processFileBatch',
                'priority' => 10,
            ),

            /**
             * Headers
             */
            array(
                'filter'   => 'wc_el_inv-add_json_header',
                'callback' => function () {
                    /**
                     * No cache
                     */
                    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
                    header('Cache-Control: post-check=0, pre-check=0', false);
                    header('Pragma: no-cache');

                    /**
                     * The origin parameter specifies a URI that may access the resource.
                     * The browser must enforce this. For requests
                     * without credentials, the server may specify "*" as a wildcard,
                     * thereby allowing any origin to access the resource.
                     */
                    header('Access-Control-Allow-Origin: *');

                    /**
                     * The Access-Control-Allow-Methods header specifies the method or methods allowed when accessing
                     * the resource. This is used in response to a preflight request. The conditions under
                     * which a request is preflighted are discussed above.
                     */
                    header('Access-Control-Allow-Methods: POST, GET');

                    /**
                     * The Access-Control-Allow-Credentials response header tells browsers whether to expose the
                     * response to frontend JavaScript code when the request's
                     * credentials mode (Request.credentials) is "include".
                     */
                    header('Access-Control-Allow-Credentials: true');
                },
                'priority' => 10,
            ),

            /**
             * Send xml @since 1.0.0
             */
            array(
                'filter'   => 'admin_init',
                'callback' => array(new \WcElectronInvoice\Xml\BuildXml(), 'send'),
                'priority' => 10,
            ),

            /**
             * Wizard Init
             */
            array(
                'filter'   => 'admin_init',
                'callback' => function () {
                    $wizard = new \WcElectronInvoice\Wizard();
                    $wizard->load();
                },
                'priority' => 10,
            ),

            /**
             * Disconnect Init
             */
            array(
                'filter'   => 'admin_init',
                'callback' => function () {
                    $page       = \WcElectronInvoice\Functions\filterInput($_GET, 'page');
                    $tab        = \WcElectronInvoice\Functions\filterInput($_GET, 'tab');
                    $disconnect = \WcElectronInvoice\Functions\filterInput($_GET, 'disconnect');
                    if ('true' === $disconnect && 'wc_el_inv-options-page' === $page && 'general' === $tab) {
                        // Save current pop user_id
                        update_option('pop_account_cached_user_id', get_option('pop_account_user_id'));
                        // Delete
                        delete_option('pop_account_user_id');
                        delete_option('pop_user_level');
                        delete_option('pop_user_level_expiration');
                        delete_option('pop_plugin_module_data');
                        delete_option('pop_plugin_last_check');
                        wp_redirect(admin_url('admin.php?page=wc_el_inv-options-page&tab=general'));
                        die();
                    }
                },
                'priority' => 10,
            ),

            /**
             * Update user license/level data
             */
            array(
                'filter'   => 'admin_init',
                'callback' => function () {
                    $forceUpdate     = \WcElectronInvoice\Functions\filterInput($_GET, 'forced_level_update',
                        FILTER_VALIDATE_INT);
                    $forceUpdateDone = \WcElectronInvoice\Functions\filterInput($_GET, 'forced_level_update_done',
                        FILTER_VALIDATE_INT);
                    if (1 === $forceUpdate) {
                        // Update user level and allowed addon data
                        $cachedLevel = get_option('pop_user_level');

                        $newLevel = \WcElectronInvoice\Wizard::popGetUserLevel(true);
                        if ($newLevel !== $cachedLevel) {
                            \WcElectronInvoice\Plugin::allowedAddon(true);
                        }

                        // Update the configuration to restore the data for SDI integration via POP that may have
                        // been deleted inside the plugin due to the switch to the Free tier
                        $licenseKey = \WcElectronInvoice\Admin\Settings\OptionPage::init()->getOptions('license_key') ?? null;
                        $wizard     = new Wizard();
                        $wizard->updateConfig($licenseKey);

                        wp_safe_redirect(add_query_arg(array(
                            'forced_level_update'      => null,
                            'forced_level_update_done' => 1,
                        )));
                        exit;
                    }

                    if (1 === $forceUpdateDone) {
                        add_action('wc_el_inv-plugin_header_notice', function () {
                            \WcElectronInvoice\Functions\showAdminNotice(
                                __('License info updated.', WC_EL_INV_TEXTDOMAIN),
                                'success',
                                '',
                                null
                            );
                        });
                    }
                },
                'priority' => 20,
            ),

            /**
             * Delete cached files
             */
            array(
                'filter'   => 'wc_el_inv-delete_cached_legal_file',
                'callback' => function () {
                    $cached_user_id = (int)get_option('pop_account_cached_user_id', false);
                    $user_id        = (int)get_option('pop_account_user_id', false);
                    if (
                        $user_id > 0 &&
                        $cached_user_id > 0 &&
                        $cached_user_id !== $user_id
                    ) {
                        popDeleteSavedFiles();
                        delete_option('pop_account_cached_user_id');
                    }
                },
                'priority' => 0,
            ),

            /**
             * Init Connection check @since 1.1.0
             */
            array(
                'filter'   => 'admin_init',
                'callback' => array(new \WcElectronInvoice\Connection(), 'check'),
                'priority' => 30,
            ),

            /**
             * PEPPOL POP createAndSendUblInvoice
             */
            array(
                'filter'   => 'wp_ajax_createAndSendUblInvoice',
                'callback' => 'WcElectronInvoice\\PeppolApi::createAndSendUblInvoice',
                'priority' => 10,
            ),

            /**
             * PEPPOL POP stateInvoice
             */
            array(
                'filter'   => 'wp_ajax_stateInvoice',
                'callback' => '\\WcElectronInvoice\\PeppolApi::stateInvoice',
                'priority' => 10,
            ),

            /**
             * KSeF POP createAndSendKsefInvoice
             */
            array(
                'filter'   => 'wp_ajax_createAndSendKsefInvoice',
                'callback' => 'WcElectronInvoice\\KsefApi::createAndSendKsefInvoice',
                'priority' => 10,
            ),

            /**
             * KSeF POP ksefStateInvoice
             */
            array(
                'filter'   => 'wp_ajax_ksefStateInvoice',
                'callback' => '\\WcElectronInvoice\\KsefApi::ksefStateInvoice',
                'priority' => 10,
            ),

            /**
             * Zoho POP createAndSendZohoInvoice
             */
            array(
                'filter'   => 'wp_ajax_createAndSendZohoInvoice',
                'callback' => 'WcElectronInvoice\\ZohoApi::createAndSendZohoInvoice',
                'priority' => 10,
            ),

            /**
             * SDI POP createAndSendInvoice
             */
            array(
                'filter'   => 'wp_ajax_createAndSendInvoice',
                'callback' => 'WcElectronInvoice\\InvoiceApi::createAndSendInvoice',
                'priority' => 10,
            ),

            /**
             * SDI POP notificationsInvoice
             */
            array(
                'filter'   => 'wp_ajax_notificationsInvoice',
                'callback' => '\\WcElectronInvoice\\InvoiceApi::notificationsInvoice',
                'priority' => 10,
            ),

            /**
             * SDI POP preserveInvoice
             */
            array(
                'filter'   => 'wp_ajax_preserveInvoice',
                'callback' => '\\WcElectronInvoice\\InvoiceApi::preserveInvoice',
                'priority' => 10,
            ),
            array(
                'filter'   => 'wp_ajax_confirmNativeSendWithUuid',
                'callback' => '\\WcElectronInvoice\\InvoiceApi::confirmNativeSendWithUuid',
                'priority' => 10,
            ),
            array(
                'filter'   => 'wp_ajax_cancelNativeTimeoutPending',
                'callback' => '\\WcElectronInvoice\\InvoiceApi::cancelNativeTimeoutPending',
                'priority' => 10,
            ),

            /**
             * POP sendWebhook
             */
            array(
                'filter'   => 'wp_ajax_sendWebhook',
                'callback' => 'WcElectronInvoice\\Functions\\sendWebhook',
                'priority' => 10,
            ),

            /**
             * POP deactivation lifecycle feedback
             */
            array(
                'filter'   => 'wp_ajax_pop_send_deactivation_feedback',
                'callback' => function () {
                    check_ajax_referer('pop_deactivation_nonce', 'nonce');

                    if (! current_user_can('activate_plugins')) {
                        wp_send_json_error(null, 403);
                        return;
                    }

                    $reason  = isset($_POST['reason']) ? sanitize_text_field(wp_unslash($_POST['reason'])) : '';
                    $message = isset($_POST['message']) ? sanitize_textarea_field(wp_unslash($_POST['message'])) : '';

                    $result = \WcElectronInvoice\Deactivate::sendLifecycleEvent($reason, $message);

                    wp_send_json($result ?? ['success' => false, 'code' => 0, 'body' => 'skipped']);
                },
                'priority' => 10,
            ),

            /**
             * POP notice reviews
             */
            array(
                'filter'   => 'admin_init',
                'callback' => 'WcElectronInvoice\\Functions\\popReviewNoticeInit',
                'priority' => 10,
            ),
            array(
                'filter'   => 'admin_notices',
                'callback' => 'WcElectronInvoice\\Functions\\popReviewNoticeDisplay',
                'priority' => 10,
            ),

            /**
             * POP invoice fields: centralized WordPress user profile section.
             * This is the only editable source in profile.php/user-edit.php to avoid
             * collisions with provider-specific duplicated fields.
             */
            array(
                'filter'        => [ 'show_user_profile', 'edit_user_profile' ],
                'callback'      => function ( $user ) {
                    if ( ! $user || ! isset( $user->ID ) ) {
                        return;
                    }

                    $isPeppolContext = \WcElectronInvoice\Integrations::isPeppolContext();

                    $fields = apply_filters( 'wc_el_inv-billing_fields', [] );
                    if ( ! is_array( $fields ) ) {
                        $fields = [];
                    }

                    $defaultFields = [
                        'billing_choice_type'  => [
                            'label'       => esc_html__( 'Choose the type of document', WC_EL_INV_TEXTDOMAIN ),
                            'type'        => 'select',
                            'description' => '',
                            'options'     => [
                                'receipt' => esc_html_x( 'Receipt', 'invoice_choice', WC_EL_INV_TEXTDOMAIN ),
                                'invoice' => esc_html_x( 'Invoice', 'invoice_choice', WC_EL_INV_TEXTDOMAIN ),
                            ],
                        ],
                        'billing_invoice_type' => [
                            'label'       => esc_html__( 'Customer type', WC_EL_INV_TEXTDOMAIN ),
                            'type'        => 'select',
                            'description' => '',
                            'options'     => [
                                'private'   => esc_html__( 'Private', WC_EL_INV_TEXTDOMAIN ),
                                'company'   => esc_html__( 'Company', WC_EL_INV_TEXTDOMAIN ),
                                'freelance' => esc_html__( 'Freelance', WC_EL_INV_TEXTDOMAIN ),
                            ],
                        ],
                        'billing_sdi_type'     => [
                            'label'       => esc_html__( 'E-mail (PEC) or the unique code', WC_EL_INV_TEXTDOMAIN ),
                            'type'        => 'text',
                            'description' => '',
                        ],
                        'billing_vat_number'   => [
                            'label'       => esc_html__( 'VAT number', WC_EL_INV_TEXTDOMAIN ),
                            'type'        => 'text',
                            'description' => '',
                        ],
                        'billing_company'      => [
                            'label'       => esc_html__( 'Name of the company', WC_EL_INV_TEXTDOMAIN ),
                            'type'        => 'text',
                            'description' => '',
                        ],
                        'billing_tax_code'     => [
                            'label'       => esc_html__( 'Tax Code', WC_EL_INV_TEXTDOMAIN ),
                            'type'        => 'text',
                            'description' => '',
                        ],
                    ];

                    $orderedKeys = [ 'billing_choice_type', 'billing_invoice_type', 'billing_sdi_type', 'billing_vat_number', 'billing_company', 'billing_tax_code' ];
                    ?>
                    <div id="pop-global-invoice-fields-wrap">
                    <h2 id="pop-global-invoice-fields"><?php esc_html_e( 'Invoice Fields', WC_EL_INV_TEXTDOMAIN ); ?></h2>
                    <p><?php esc_html_e( 'These fields are used by POP to collect billing information for user invoices.', WC_EL_INV_TEXTDOMAIN ); ?></p>
                    <table class="form-table" role="presentation">
                        <tbody>
                        <?php foreach ( $orderedKeys as $key ) :
                            if ( $isPeppolContext && in_array( $key, [ 'billing_sdi_type', 'billing_tax_code' ], true ) ) {
                                continue;
                            }
                            $field   = isset( $fields[ $key ] ) && is_array( $fields[ $key ] ) ? $fields[ $key ] : [];
                            $default = isset( $defaultFields[ $key ] ) ? $defaultFields[ $key ] : [];

                            $label       = isset( $field['label'] ) ? $field['label'] : ( $default['label'] ?? $key );
                            $type        = isset( $field['type'] ) ? $field['type'] : ( $default['type'] ?? 'text' );
                            $description = isset( $field['description'] ) ? $field['description'] : ( $default['description'] ?? '' );
                            $options     = isset( $field['options'] ) && is_array( $field['options'] ) ? $field['options'] : ( $default['options'] ?? [] );
                            $value       = get_user_meta( (int) $user->ID, $key, true );
                            ?>
                            <tr>
                                <th><label for="<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $label ); ?></label></th>
                                <td>
                                <?php if ( 'select' === $type ) : ?>
                                    <select name="<?php echo esc_attr( $key ); ?>" id="<?php echo esc_attr( $key ); ?>">
                                        <option value=""><?php esc_html_e( 'Select', WC_EL_INV_TEXTDOMAIN ); ?></option>
                                        <?php foreach ( $options as $optionValue => $optionLabel ) : ?>
                                            <option value="<?php echo esc_attr( $optionValue ); ?>" <?php selected( (string) $value, (string) $optionValue ); ?>>
                                                <?php echo esc_html( $optionLabel ); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                <?php else : ?>
                                    <input type="text"
                                           class="regular-text"
                                           name="<?php echo esc_attr( $key ); ?>"
                                           id="<?php echo esc_attr( $key ); ?>"
                                           value="<?php echo esc_attr( (string) $value ); ?>"/>
                                <?php endif; ?>
                                <?php if ( ! empty( $description ) ) : ?>
                                    <p class="description"><?php echo esc_html( $description ); ?></p>
                                <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                    </div>
                    <?php
                },
                'priority'      => 20,
                'accepted_args' => 1,
            ),
            array(
                'filter'        => [ 'personal_options_update', 'edit_user_profile_update' ],
                'callback'      => function ( $user_id ) {
                    if ( ! current_user_can( 'edit_user', $user_id ) ) {
                        return;
                    }

                    $meta_keys = [ 'billing_choice_type', 'billing_invoice_type', 'billing_sdi_type', 'billing_vat_number', 'billing_company', 'billing_tax_code' ];
                    foreach ( $meta_keys as $meta_key ) {
                        if ( ! array_key_exists( $meta_key, $_POST ) ) {
                            continue;
                        }

                        $raw_value = wp_unslash( $_POST[ $meta_key ] );
                        $value     = is_scalar( $raw_value ) ? sanitize_text_field( (string) $raw_value ) : '';
                        update_user_meta( $user_id, $meta_key, $value );
                    }
                },
                'priority'      => 20,
                'accepted_args' => 1,
            ),
            array(
                'filter'   => [ 'admin_footer-profile.php', 'admin_footer-user-edit.php' ],
                'callback' => function () {
                    ?>
                    <script>
                    (function () {
                        var fieldNames = [
                            'billing_choice_type',
                            'billing_invoice_type',
                            'billing_sdi_type',
                            'billing_vat_number',
                            'billing_company',
                            'billing_tax_code'
                        ];
                        var noticeHtml = '<span class="dashicons dashicons-info-outline" aria-hidden="true"></span> '
                            + '<?php echo esc_js( __( 'This provider section is read-only in this screen.', WC_EL_INV_TEXTDOMAIN ) ); ?> '
                            + '<a href="#pop-global-invoice-fields"><?php echo esc_js( __( 'Go to POP Invoice Fields section', WC_EL_INV_TEXTDOMAIN ) ); ?></a>';

                        var globalWrap = document.getElementById('pop-global-invoice-fields-wrap');

                        function insertNoticeForTable(table) {
                            if (!table || table.querySelector('.pop-readonly-fields-notice-row')) {
                                return;
                            }

                            var tbody = table.querySelector('tbody');
                            if (!tbody) {
                                return;
                            }

                            var tr = document.createElement('tr');
                            tr.className = 'pop-readonly-fields-notice-row';

                            var th = document.createElement('th');
                            var td = document.createElement('td');
                            var p = document.createElement('p');
                            p.className = 'description';
                            p.innerHTML = noticeHtml;

                            td.appendChild(p);
                            tr.appendChild(th);
                            tr.appendChild(td);
                            tbody.insertBefore(tr, tbody.firstChild);
                        }

                        function insertNoticeForPmpro(sectionInside) {
                            if (!sectionInside || sectionInside.querySelector('.pop-readonly-fields-notice')) {
                                return;
                            }

                            var p = document.createElement('p');
                            p.className = 'description pop-readonly-fields-notice';
                            p.innerHTML = noticeHtml;
                            sectionInside.insertBefore(p, sectionInside.firstChild);
                        }

                        fieldNames.forEach(function (name) {
                            var elements = document.querySelectorAll('[name="' + name + '"]');
                            elements.forEach(function (el) {
                                if (globalWrap && globalWrap.contains(el)) {
                                    return;
                                }
                                el.disabled = true;
                                if (window.jQuery && window.jQuery.fn && window.jQuery(el).data('select2')) {
                                    window.jQuery(el).trigger('change.select2');
                                }

                                var pmproInside = el.closest('.pmpro_section_inside');
                                if (pmproInside) {
                                    insertNoticeForPmpro(pmproInside);
                                    return;
                                }

                                var table = el.closest('table.form-table');
                                insertNoticeForTable(table);
                            });
                        });
                    })();
                    </script>
                    <?php
                },
                'priority' => 99,
            ),
        ),
        'filter' => array(
            array(
                'filter'   => 'wc_el_inv-xml_data_filter',
                'callback' => 'WcElectronInvoice\\Pdf\\CreatePdf::create',
                'priority' => 30,
            ),
        ),
    ),
);

return apply_filters('wc_el_inv-filters_admin', $filtersAdmin);
