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

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

$page       = \WcElectronInvoice\Admin\Settings\OptionPage::init();
$options    = $page->getOptions();
$countries  = new \WcElectronInvoice\Utils\Countries();
$wcFieldPos = $page->getOptions('billing_fields_position') ?: false;
$country    = is_user_logged_in() ?
    get_user_meta(get_current_user_id(), 'billing_country', true) :
    $countries->get_base_country();

$euVatCountry = $countries->get_european_union_countries();

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

$disablePecSdi = $page->getOptions('invoice_disable_pec_sdi');
$disableCf = $page->getOptions('invoice_disable_cf');
$activeJsCfCheck = $page->getOptions('invoice_active_js_cf_check');
if ($isPeppolContext) {
    $disablePecSdi = 'on';
    $disableCf = 'on';
    $activeJsCfCheck = 'off';
}

$currentAdminPage  = \WcElectronInvoice\Functions\filterInput($_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS);
$isPopPluginPage   = ($currentAdminPage === 'wc_el_inv-options-page');

$mode           = defined('WC_EL_INV_ENV') ? WC_EL_INV_ENV : null;
$forceJsDevMode = \WcElectronInvoice\Functions\filterInput($_GET, 'js_mode', FILTER_SANITIZE_SPECIAL_CHARS);
if (isset($forceJsDevMode) && $forceJsDevMode === 'dev') {
    $mode = 'dev';
}

if (! is_admin()) {
    $scripts = array_merge($scripts, array(
        'wc_el_inv_invoice' => array(
            'mode'                 => $mode,
            'ajax_url'             => untrailingslashit(admin_url('admin-ajax.php')),
            'ajax_nonce'           => wp_create_nonce('wc_el_inv_ajax-ajax_nonce'),
            'rest_nonce'           => wp_create_nonce('wp_rest'),
            'store_api_nonce'      => wp_create_nonce('wc_store_api'),
            'invoice_required'     => 'required' === $page->getOptions('invoice_required') ? 1 : 0,
            'wc_fields_pos'        => $wcFieldPos,
            'user_level'           => \WcElectronInvoice\Wizard::popGetUserLevel(),
            'is_peppol_context'    => $isPeppolContext ? 1 : 0,
            'shop_country'         => \WcElectronInvoice\WooCommerce\Fields\GeneralFields::getGeneralInvoiceOptionCountryState(),
            'hide_outside_ue'      => $page->getOptions('hide_outside_ue'),
            'disable_pec_sdi'      => $disablePecSdi,
            'disable_cf'           => $disableCf,
            'active_js_cf_check'   => $activeJsCfCheck,
            'country'              => $country ?: '',
            'user_country'         => get_user_meta(get_current_user_id(), 'billing_country', true) ?: '',
            'eu_vat_country'       => $euVatCountry ?: '',
            'required_text'        => esc_html__('required', WC_EL_INV_TEXTDOMAIN),
            'not_required_text'    => esc_html__('not required', WC_EL_INV_TEXTDOMAIN),
            'vies_valid_label'     => esc_html__('VAT valid for VIES', WC_EL_INV_TEXTDOMAIN),
            'vies_not_valid_label' => esc_html__('The VAT number entered is not valid for VIES', WC_EL_INV_TEXTDOMAIN),
            'invalid_tax_code'     => esc_html__('Invalid Tax Code, check the name and surname entered.',
                WC_EL_INV_TEXTDOMAIN),
            'company_label'        => esc_html__('Company', WC_EL_INV_TEXTDOMAIN),
            'sdi_label'            => esc_html__('Certified e-mail (PEC) or the unique code', WC_EL_INV_TEXTDOMAIN),
            'sdi_placeholder'      => esc_html__('E-mail (PEC) or the unique code', WC_EL_INV_TEXTDOMAIN),
            'sdi_description'      => esc_html__('Please enter your certified e-mail (PEC) or the unique code',
                WC_EL_INV_TEXTDOMAIN),
            'pop_block_message' => [
                'required'        => __('The "%s" field is required.', WC_EL_INV_TEXTDOMAIN),
                'vat_tax__length' => __('The "%s" field must be at least 6 characters long.', WC_EL_INV_TEXTDOMAIN),
                'sdi_length'      => __('The "%s" field must be 7 characters long.', WC_EL_INV_TEXTDOMAIN),
                'min_length'      => __('The "%s" field must be at least 3 characters long.', WC_EL_INV_TEXTDOMAIN),
            ],
        ),
    ));
} else {
    $scripts = array_merge($scripts, array(
        'wc_el_inv_admin' => array(
            'mode'                              => defined('WC_EL_INV_ENV') ? WC_EL_INV_ENV : null,
            'ajax_url'                          => untrailingslashit(admin_url('admin-ajax.php')),
            'ajax_nonce'                        => wp_create_nonce('wc_el_inv_ajax-ajax_nonce'),
            'rest_nonce'                        => wp_create_nonce('wp_rest'),
            'store_api_nonce'                   => wp_create_nonce('wc_store_api'),
            'wc_fields_pos'                     => $wcFieldPos,
            'user_level'                        => \WcElectronInvoice\Wizard::popGetUserLevel(),
            'shop_country'                      => \WcElectronInvoice\WooCommerce\Fields\GeneralFields::getGeneralInvoiceOptionCountryState(),
            'count_filtered'                    => $isPopPluginPage ? count((array)get_option('temp_order_filtered', [])) : 0,
            'start_download'                    => __('download starting... 0%', WC_EL_INV_TEXTDOMAIN),
            'sdi_notice_details'                => __('Details', WC_EL_INV_TEXTDOMAIN),
            'sdi_notice_path'                   => __('Path', WC_EL_INV_TEXTDOMAIN),
            'sdi_notice_content'                => __('Content', WC_EL_INV_TEXTDOMAIN),
            'sdi_notice_message'                => __('Message', WC_EL_INV_TEXTDOMAIN),
            'overquota_title_default'           => __('POP API limit reached', WC_EL_INV_TEXTDOMAIN),
            'overquota_message_default'         => __('The action could not be completed because a POP API billing limit blocked the request. Check your account status on popapi.io to continue.',
                WC_EL_INV_TEXTDOMAIN),
            'overquota_title_disabled'          => __('Overquota disabled', WC_EL_INV_TEXTDOMAIN),
            'overquota_message_disabled'        => __('The action could not be completed because overquota is disabled for this account. Enable overquota on popapi.io to continue.', WC_EL_INV_TEXTDOMAIN),
            'overquota_title_settlement_required' => __('Pending billing settlement required', WC_EL_INV_TEXTDOMAIN),
            'overquota_message_settlement_required' => __('The action could not be completed because a billing settlement is required before overquota can be used again. Check your account on popapi.io and settle the pending amount to unblock the request.', WC_EL_INV_TEXTDOMAIN),
            'overquota_title_quota_limit'       => __('Plan limit reached', WC_EL_INV_TEXTDOMAIN),
            'overquota_message_quota_limit'     => __('The action could not be completed because the plan credit limit has been reached and overquota is not currently available. Check your account status on popapi.io to continue.', WC_EL_INV_TEXTDOMAIN),
            'overquota_title_cap_reached'       => __('Monthly overquota cap reached', WC_EL_INV_TEXTDOMAIN),
            'overquota_message_cap_reached'     => __('The action could not be completed because the overquota cap has been reached. Increase the cap on popapi.io to continue.', WC_EL_INV_TEXTDOMAIN),
            'overquota_title_payment_required'  => __('Payment method required', WC_EL_INV_TEXTDOMAIN),
            'overquota_message_payment_required'=> __('The action could not be completed because no valid payment method is available for overquota. Update the payment method on popapi.io to continue.',
                WC_EL_INV_TEXTDOMAIN),
            'overquota_title_unpaid'            => __('Unpaid overquota charges', WC_EL_INV_TEXTDOMAIN),
            'overquota_message_unpaid'          => __('The action could not be completed because there are overdue overquota charges older than 30 days. Settle the pending amount on popapi.io to continue.',
                WC_EL_INV_TEXTDOMAIN),
            'overquota_title_guardrail'         => __('Billing verification unavailable', WC_EL_INV_TEXTDOMAIN),
            'overquota_message_guardrail'       => __('The action could not be completed because billing verification is temporarily unavailable. Try again later or contact support if the problem persists.',
                WC_EL_INV_TEXTDOMAIN),
            'overquota_cta_open_pop'            => __('Open POP', WC_EL_INV_TEXTDOMAIN),
            'overquota_cta_contact_support'     => __('Contact support', WC_EL_INV_TEXTDOMAIN),
            'overquota_step_label'              => __('Next step', WC_EL_INV_TEXTDOMAIN),
            'required_text'                     => esc_html__('required', WC_EL_INV_TEXTDOMAIN),
            'not_required_text'                 => esc_html__('not required', WC_EL_INV_TEXTDOMAIN),
            'text_edit'                         => esc_html__('Edit', WC_EL_INV_TEXTDOMAIN),
            'text_save'                         => esc_html__('Save', WC_EL_INV_TEXTDOMAIN),
            'manual_reset_checkbox'             => esc_html__('Start a new numeration from this value', WC_EL_INV_TEXTDOMAIN),
            'manual_reset_help'                 => esc_html__('Use this only if previous numbers belong to tests or to a closed series. Existing documents will not be deleted.', WC_EL_INV_TEXTDOMAIN),
            'manual_reset_confirm'              => esc_html__('Confirm only if you want to start a new numeration segment from this value. Previous numbers in the same series will be ignored for next-number alignment.', WC_EL_INV_TEXTDOMAIN),
            'search_by_id'                      => esc_html__('Enter the order number to be searched',
                WC_EL_INV_TEXTDOMAIN),
            'select_date_filter'                => esc_html__('Select dates to filter', WC_EL_INV_TEXTDOMAIN),
            'renumber_not_data'                 => esc_html__('Set data for renumber', WC_EL_INV_TEXTDOMAIN),
            'invoice_sent_confirm'              => esc_html__(
                'WARNING: You are about to set the "SENT to invoice" status, do you want to confirm?',
                WC_EL_INV_TEXTDOMAIN
            ),
            'invoice_undo_confirm'              => esc_html__(
                'WARNING: You are about to set the "NOT SENT to invoice" status, do you want to confirm?',
                WC_EL_INV_TEXTDOMAIN
            ),
            'bulk_invoice_cb'                   => esc_html__(
                'First you must select one or more checkbox',
                WC_EL_INV_TEXTDOMAIN
            ),
            'refund_item_disabled_text'         => esc_html__(
                'Refund disabled: first you need to send the generated credit note',
                WC_EL_INV_TEXTDOMAIN
            ),
            'refund_amount_read_only_info_text' => esc_html__(
                'Before sending the invoice you cannot make a refund, on the total but only on the lines of the order',
                WC_EL_INV_TEXTDOMAIN
            ),
            'timeout_uuid_required'             => esc_html__(
                'UUID is required.',
                WC_EL_INV_TEXTDOMAIN
            ),
            'timeout_cancel_confirm'            => esc_html__(
                'Confirm only if POP support has explicitly verified that the document was NOT created/sent. This action re-enables send and may create duplicates if verification is incorrect.',
                WC_EL_INV_TEXTDOMAIN
            ),
        ),
        'wc_el_inv_deactivate' => array(
            'ajax_url'            => untrailingslashit(admin_url('admin-ajax.php')),
            'nonce'               => wp_create_nonce('pop_deactivation_nonce'),
            'logo_url'            => WC_EL_INV_URL . 'assets/images/pop.svg',
            'plugin_file'         => WC_EL_INV_PLUGIN_DIR . '/index.php',
            'title'               => esc_html__('Un feedback prima di andare?', WC_EL_INV_TEXTDOMAIN),
            'desc'                => esc_html__('Ci aiuteresti molto sapere il motivo, così possiamo migliorare.', WC_EL_INV_TEXTDOMAIN),
            'reason_label'        => esc_html__('Perché stai disattivando?', WC_EL_INV_TEXTDOMAIN),
            'message_label'       => esc_html__('Commenti aggiuntivi (opzionale)', WC_EL_INV_TEXTDOMAIN),
            'message_placeholder' => esc_html__('Raccontaci di più...', WC_EL_INV_TEXTDOMAIN),
            'deactivate'          => esc_html__('Disattiva', WC_EL_INV_TEXTDOMAIN),
            'reasons'             => array(
                'placeholder'      => esc_html__('— Seleziona un motivo —', WC_EL_INV_TEXTDOMAIN),
                'too_expensive'    => esc_html__('Il costo del piano è troppo alto', WC_EL_INV_TEXTDOMAIN),
                'setup_issue'      => esc_html__('Problemi durante la configurazione', WC_EL_INV_TEXTDOMAIN),
                'missing_feature'  => esc_html__('Manca una funzionalità necessaria', WC_EL_INV_TEXTDOMAIN),
                'not_working'      => esc_html__('Il plugin non funziona correttamente', WC_EL_INV_TEXTDOMAIN),
                'not_needed'       => esc_html__('Non ne ho più bisogno', WC_EL_INV_TEXTDOMAIN),
                'switched_plugin'  => esc_html__('Ho scelto un altro plugin/soluzione', WC_EL_INV_TEXTDOMAIN),
                'other'            => esc_html__('Altro', WC_EL_INV_TEXTDOMAIN),
            ),
        ),
        'wc_el_inv_integration' => array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('ajax_option_save_nonce'),
            'active'   => esc_html__('active', WC_EL_INV_TEXTDOMAIN),
            'mode'     => WC_EL_INV_ENV,
            'error'    => esc_html__("Error saving option.", WC_EL_INV_TEXTDOMAIN),
        ),
        'wc_el_inv_wizard'      => array(
            'ajax_url'             => admin_url('admin-ajax.php'),
            'pop_general_page'     => admin_url('/admin.php?page=wc_el_inv-options-page&tab=general'),
            'nonce'                => wp_create_nonce('ajax_wizard_nonce'),
            'mode'                 => WC_EL_INV_ENV,
            'default_error'        => esc_html__("Unknown Wizard Error", WC_EL_INV_TEXTDOMAIN),
            'loading_expired'      => esc_html__("Time is up. Try again...", WC_EL_INV_TEXTDOMAIN),
            'loading_setup'        => esc_html__("Setup configuration, please wait...", WC_EL_INV_TEXTDOMAIN),
            'completed'            => esc_html__("Process completed successfully!", WC_EL_INV_TEXTDOMAIN),
            'config_error'         => esc_html__("Error in the setup process, please try again...",
                WC_EL_INV_TEXTDOMAIN),
            'loading_popup'        => esc_html__("The window could not be opened. Please disable your pop-up blocker and try again.",
                WC_EL_INV_TEXTDOMAIN),
            'window_closed'        => esc_html__("The window was closed without completing the process.",
                WC_EL_INV_TEXTDOMAIN),
            'handle_window_closed' => esc_url_raw(admin_url('admin.php?page=wc_el_inv-options-page&tab=general')),
            '_locale'              => substr(get_locale(), 0, 2),
            '_site'                => esc_url_raw(site_url('/')),
            '_domain'              => esc_url_raw(WC_EL_INV_API_DOMAIN),
            '_pv'                  => esc_attr(WC_EL_INV_VERSION),
            '_code'                => esc_attr(\WcElectronInvoice\Wizard::randomCode()),
        ),
    ));
}

return apply_filters('wc_el_inv-scripts_localize_list', $scripts);
