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

namespace WcElectronInvoice\Admin\Settings;

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

use WcElectronInvoice\Plugin;
use WcElectronInvoice\Wizard;
use function WcElectronInvoice\Functions\checkOptions;
use function WcElectronInvoice\Functions\filterInput;
use function WcElectronInvoice\Functions\sanitize;

/**
 * Class OptionPage
 *
 * @since  1.0.0
 * @author alfiopiccione <alfio.piccione@gmail.com>
 */
final class OptionPage extends OptionFields
{
    /**
     * Instance
     *
     * @since 1.0.0
     *
     * @var object The instance of the class
     */
    private static $instance;

    /**
     * Holds the values to be used in the fields callbacks
     *
     * @since 1.0.0
     *
     * @var array
     */
    public $options;

    /**
     * Option Key
     *
     * @since 1.0.0
     *
     * @var string
     */
    public static string $optionKey = 'wc_el_inv-settings-';

    /**
     * The options group name
     *
     * @since 1.0.0
     *
     * @var string
     */
    public string $optionsName = 'wc_el_inv_options';

    /**
     * Sanitize Callback
     *
     * @since 1.0.0
     *
     * @var array
     */
    private $sanitize;

    /**
     * Menu Page Title
     *
     * @since 1.0.0
     *
     * @var string The text to be displayed in the title tags of the page when the menu is selected
     */
    private $menuPageTitle;

    /**
     * Menu Title
     *
     * @since 1.0.0
     *
     * @var string The text to be used for the menu
     */
    private $menuTitle;

    /**
     * Capability
     *
     * @since 1.0.0
     *
     * @var string The capability required for this menu to be displayed to the user.
     */
    private $capability;

    /**
     * Menu Slug
     *
     * @since 1.0.0
     *
     * @var string The slug name to refer to this menu by
     */
    private $menuSlug;

    /**
     * Callback Function
     *
     * @since 1.0.0
     *
     * @var string The function to be called to output the content for this page.
     */
    private $callback;

    /**
     * Menu icon
     *
     * @since 1.0.0
     *
     * @var string The icon for this page.
     */
    private $icon;

    /**
     * Contains arguments for sub menu page
     *
     * @since 1.0.0
     *
     * @var array
     */
    private $subPageArgs = array();

    /**
     * Contains arguments for tabs
     *
     * @since 1.0.0
     *
     * @var array
     */
    public $tabs = array();

    /**
     * No sent invoice count
     *
     * @var bool|mixed|void
     */
    public static $noSentCount = false;

    /**
     * Constructor
     *
     * @since 1.0.0
     */
    private function __construct()
    {
        // Load Localisation files.
        \WcElectronInvoice\Plugin::load_plugin_textdomain();

        // Setting data setup
        $this->setup();
        $this->options = $this->getOptions();
    }

    /**
     * Setting data setup
     *
     * @since 1.0.0
     */
    private function setup()
    {
        // Args for register settings
        $this->sanitize = array($this, 'sanitizeOptions');

        // Update message
        if (! empty($_REQUEST) && ! empty($_POST)) {
            if (isset($_REQUEST['action']) && 'update' === $_REQUEST['action'] && ! empty($_REQUEST[$this->optionsName])) {
                set_transient('wc_el_inv-options-saved-message',
                    esc_html__('Options saved successfully!', WC_EL_INV_TEXTDOMAIN), 10);
            }
        }

        // Args for menu page
        $this->menuPageTitle = esc_html__('Electronic Invoice - Settings', WC_EL_INV_TEXTDOMAIN);
        $this->menuTitle     = esc_html__('POP', WC_EL_INV_TEXTDOMAIN);
        // manage_options or min role shop_manager "manage_woocommerce"
        $this->capability = apply_filters('wc_el_inv-options-capability', Plugin::$capability);
        $this->menuSlug   = 'wc_el_inv-options-page';
        $this->callback   = array($this, 'createPage');
        $this->icon       = '';

        // Args for sub menu pages
        $this->subPageArgs['sub_menu_page'] = array(
            array(
                'parent_slug' => $this->menuSlug,
                'page_title'  => esc_html__('General', WC_EL_INV_TEXTDOMAIN),
                'menuTitle'   => esc_html__('General', WC_EL_INV_TEXTDOMAIN),
                'capability'  => $this->capability,
                'menuSlug'    => 'admin.php?page=' . $this->menuSlug . '&tab=general',
                'function'    => null,
            ),
            array(
                'parent_slug' => $this->menuSlug,
                'page_title'  => esc_html__('Checkout', WC_EL_INV_TEXTDOMAIN),
                'menuTitle'   => esc_html__('Checkout', WC_EL_INV_TEXTDOMAIN),
                'capability'  => $this->capability,
                'menuSlug'    => 'admin.php?page=' . $this->menuSlug . '&tab=provider-integration',
                'function'    => null,
            ),
            array(
                'parent_slug' => $this->menuSlug,
                'page_title'  => esc_html__('Numeration', WC_EL_INV_TEXTDOMAIN),
                'menuTitle'   => esc_html__('Numeration', WC_EL_INV_TEXTDOMAIN),
                'capability'  => $this->capability,
                'menuSlug'    => 'admin.php?page=' . $this->menuSlug . '&tab=numeration',
                'function'    => null,
            ),
            array(
                'parent_slug' => $this->menuSlug,
                'page_title'  => esc_html__('Documents', WC_EL_INV_TEXTDOMAIN),
                'menuTitle'   => esc_html__('Documents', WC_EL_INV_TEXTDOMAIN),
                'capability'  => $this->capability,
                'menuSlug'    => 'admin.php?page=' . $this->menuSlug . '&tab=invoice',
                'function'    => null,
            ),
            array(
                'parent_slug' => $this->menuSlug,
                'page_title'  => esc_html__('Advanced', WC_EL_INV_TEXTDOMAIN),
                'menuTitle'   => esc_html__('Advanced', WC_EL_INV_TEXTDOMAIN),
                'capability'  => $this->capability,
                'menuSlug'    => 'admin.php?page=' . $this->menuSlug . '&tab=advanced',
                'function'    => null,
            ),
            array(
                'parent_slug' => $this->menuSlug,
                'page_title'  => esc_html__('Invoices', WC_EL_INV_TEXTDOMAIN),
                'menuTitle'   => esc_html__('Invoices', WC_EL_INV_TEXTDOMAIN),
                'capability'  => $this->capability,
                'menuSlug'    => 'admin.php?page=' . $this->menuSlug . '&tab=xml',
                'function'    => null,
            ),
        );

        if ((class_exists('WooPoPToFattureInCloud\Plugin') ||
             class_exists('WooPoPToFattureAruba\Plugin') ||
             class_exists('WooPoPToSdIPec\Plugin')) &&
            current_user_can(apply_filters('wc_el_inv-options-capability', Plugin::$capability))
        ) {

            $addonTitle = null;
            if (class_exists('WooPoPToSdIPec\Plugin')) {
                $addonTitle = 'SdI PEC';
            } elseif (class_exists('WooPoPToFattureAruba\Plugin')) {
                $addonTitle = 'Fatture Aruba';
            } elseif (class_exists('WooPoPToFattureInCloud\Plugin')) {
                $addonTitle = 'Fatture in Cloud';
            }

            $this->subPageArgs['sub_menu_page'][] = array(
                'parent_slug' => $this->menuSlug,
                'page_title'  => esc_html__($addonTitle ?? 'Add-on', WC_EL_INV_TEXTDOMAIN),
                'menuTitle'   => esc_html__($addonTitle ?? 'Add-on', WC_EL_INV_TEXTDOMAIN),
                'capability'  => $this->capability,
                'menuSlug'    => 'admin.php?page=' . $this->menuSlug . '&tab=addon',
                'function'    => null,
            );
        }

        $this->subPageArgs['sub_menu_page'][] = array(
            'parent_slug' => $this->menuSlug,
            'page_title'  => esc_html__('Integrations', WC_EL_INV_TEXTDOMAIN),
            'menuTitle'   => esc_html__('Integrations', WC_EL_INV_TEXTDOMAIN),
            'capability'  => $this->capability,
            'menuSlug'    => 'admin.php?page=' . $this->menuSlug . '&tab=integration',
            'function'    => null,
        );

        $uidOption = (int)get_option('pop_account_user_id', false);
        if (! $uidOption) {
            $this->subPageArgs['sub_menu_page'][] = array(
                'parent_slug' => $this->menuSlug,
                'page_title'  => esc_html__('Wizard setup', WC_EL_INV_TEXTDOMAIN),
                'menuTitle'   => esc_html__('Wizard setup', WC_EL_INV_TEXTDOMAIN),
                'capability'  => $this->capability,
                'menuSlug'    => 'admin.php?page=' . $this->menuSlug . '&tab=wizard&wizard=init',
                'function'    => null,
            );
        }

        do_action('wc_el_inv-add_item_menu_main', $this);

        $this->tabs = include \WcElectronInvoice\Plugin::getPluginDirPath('/inc/settings/pageSettingsTabs.php');

        // parent setup
        parent::sectionFields();
    }

    /**
     * Get Plugin Capability
     *
     * @return string
     */
    public function getPluginCapability()
    {
        return $this->capability;
    }

    /**
     * Admin bar link
     *
     * @param \WP_Admin_Bar $adminBar
     *
     * @since 1.0.0
     *
     */
    public function adminToolbar(\WP_Admin_Bar $adminBar)
    {
        if (! is_user_logged_in() && ! current_user_can('administrator')) {
            return;
        }

        if (! $adminBar instanceof \WP_Admin_Bar) {
            return;
        }

        $uidOption  = (int)get_option('pop_account_user_id', false);
        $licenseKey = $this->getOptions('license_key') ?? null;
        $status     = ($licenseKey || $uidOption) ? 'active' : 'not-active' . ' ' . WC_EL_INV_ENV;

        $env = get_option('wc_el_inv_environment', 'live');

        if ('dev' === WC_EL_INV_ENV) {
            $this->menuTitle = $this->menuTitle . ' - ' . WC_EL_INV_ENV;
            $status          = "development" . ' environment-' . $env;

            if (in_array($env, ['live', 'sandbox'], true)) {
                $this->menuTitle = $this->menuTitle .": ". ucfirst($env);
            }
        } else {
            if (in_array($env, ['live', 'sandbox'], true)) {
                $this->menuTitle = $this->menuTitle . ': ' . ucfirst($env);
                $status          = $status . ' environment-' . $env;
            }
        }

        $adminBar->add_menu(array(
            'id'    => $this->optionsName,
            'title' => esc_html__($this->menuTitle, WC_EL_INV_TEXTDOMAIN),
            'href'  => esc_url(admin_url('admin.php?page=' . $this->menuSlug . '&tab=general')),
            'meta'  => array(
                'class' => $status,
            ),
        ));
        // Sum menu link
        $adminBar->add_menu(array(
            'parent' => $this->optionsName,
            'id'     => $this->optionsName . '-general',
            'title'  => esc_html__('General', WC_EL_INV_TEXTDOMAIN),
            'href'   => esc_url(admin_url('admin.php?page=' . $this->menuSlug . '&tab=general')),
        ));
        $adminBar->add_menu(array(
            'parent' => $this->optionsName,
            'id'     => $this->optionsName . '-provider-integration',
            'title'  => esc_html__('Checkout', WC_EL_INV_TEXTDOMAIN),
            'href'   => esc_url(admin_url('admin.php?page=' . $this->menuSlug . '&tab=provider-integration')),
        ));
        $adminBar->add_menu(array(
            'parent' => $this->optionsName,
            'id'     => $this->optionsName . '-numeration',
            'title'  => esc_html__('Numeration', WC_EL_INV_TEXTDOMAIN),
            'href'   => esc_url(admin_url('admin.php?page=' . $this->menuSlug . '&tab=numeration')),
        ));
        $adminBar->add_menu(array(
            'parent' => $this->optionsName,
            'id'     => $this->optionsName . '-invoice',
            'title'  => esc_html__('Documents', WC_EL_INV_TEXTDOMAIN),
            'href'   => esc_url(admin_url('admin.php?page=' . $this->menuSlug . '&tab=invoice')),
        ));
        $adminBar->add_menu(array(
            'parent' => $this->optionsName,
            'id'     => $this->optionsName . '-advanced',
            'title'  => esc_html__('Advanced', WC_EL_INV_TEXTDOMAIN),
            'href'   => esc_url(admin_url('admin.php?page=' . $this->menuSlug . '&tab=advanced')),
        ));
        $adminBar->add_menu(array(
            'parent' => $this->optionsName,
            'id'     => $this->optionsName . '-xml',
            'title'  => esc_html__('Invoices', WC_EL_INV_TEXTDOMAIN),
            'href'   => esc_url(admin_url('admin.php?page=' . $this->menuSlug . '&tab=xml')),
        ));
        if ((class_exists('WooPoPToFattureInCloud\Plugin') ||
             class_exists('WooPoPToFattureAruba\Plugin') ||
             class_exists('WooPoPToSdIPec\Plugin')) &&
            current_user_can(apply_filters('wc_el_inv-options-capability', Plugin::$capability))
        ) {

            $addonTitle = null;
            if (class_exists('WooPoPToSdIPec\Plugin')) {
                $addonTitle = 'SdI PEC';
            } elseif (class_exists('WooPoPToFattureAruba\Plugin')) {
                $addonTitle = 'Fatture Aruba';
            } elseif (class_exists('WooPoPToFattureInCloud\Plugin')) {
                $addonTitle = 'Fatture in Cloud';
            }

            $adminBar->add_menu(array(
                'parent' => $this->optionsName,
                'id'     => $this->optionsName . '-addon',
                'title'  => esc_html__($addonTitle ?? 'Add-on', WC_EL_INV_TEXTDOMAIN),
                'href'   => esc_url(admin_url('admin.php?page=' . $this->menuSlug . '&tab=addon')),
            ));
        }

        $adminBar->add_menu(array(
            'parent' => $this->optionsName,
            'id'     => $this->optionsName . '-integration',
            'title'  => esc_html__('Integrations', WC_EL_INV_TEXTDOMAIN),
            'href'   => esc_url(admin_url('admin.php?page=' . $this->menuSlug . '&tab=integration')),
        ));

        $uidOption = (int)get_option('pop_account_user_id', false);
        if (! $uidOption) {
            $adminBar->add_menu(array(
                'parent' => $this->optionsName,
                'id'     => $this->optionsName . '-wizard',
                'title'  => esc_html__('Wizard setup', WC_EL_INV_TEXTDOMAIN),
                'href'   => esc_url(admin_url('admin.php?page=' . $this->menuSlug . '&tab=wizard&wizard=init')),
            ));
        }

        do_action('wc_el_inv-add_item_menu_toolbar', $adminBar, $this);
    }

    /**
     * Get key
     *
     * @return false|mixed|void
     */
    public static function getK()
    {
        return get_option('wc_el_inv-secret-api-key');
    }

    /**
     * Return Options
     *
     * @param string $singleKey
     * @param bool   $allowedHtml
     *
     * @return array|bool|mixed|string $option The value of the option retrieved from the options array / single key
     *                                 value or false
     * @since 1.0.0
     *
     */
    public function getOptions($singleKey = '', $allowedHtml = false)
    {
        $options = get_option($this->optionsName);

        if (! empty($options) && is_array($options)) {
            if ('' === $singleKey) {
                return (array)$options;
            } else {
                if (isset($options[self::$optionKey . $singleKey])) {
                    if (! $allowedHtml) {
                        return \WcElectronInvoice\Functions\sanitize($options[self::$optionKey . $singleKey]);
                    } else {
                        return $options[self::$optionKey . $singleKey];
                    }
                }
            }
        }

        return false;
    }

    /**
     * Set Option
     *
     * @param $key
     * @param $value
     *
     * @return bool
     * @since 1.0.0
     */
    public function setOption($key, $value)
    {
        $options = get_option($this->optionsName);
        $update  = false;

        if (! empty($options) && is_array($options)) {
            if ('' !== $key && array_key_exists(self::$optionKey . $key, $options)) {
                // Old value
                $oldValue = $this->getOptions($key);

                // Standardize the values for the control.
                if (is_int($value)) {
                    $oldValue = (int)$oldValue;
                } elseif (is_string($value)) {
                    $oldValue = (string)$oldValue;
                }

                if ($value !== $oldValue) {
                    $currentValue                     = \WcElectronInvoice\Functions\sanitize($value);
                    $options[self::$optionKey . $key] = $currentValue;
                    $update                           = update_option($this->optionsName, $options);
                }
            }
        }

        return $update;
    }

    /**
     * getOptionJsonCollections
     *
     * @return mixed
     */
    public function getOptionJsonCollections()
    {
        $options = get_option($this->optionsName) ?? array();
        if (! empty($options)) {
            // Unset import field
            unset($options['wc_el_inv-settings-import_collections']);
            unset($options['wc_el_inv-settings-invoice_vies_check']);
        }

        // WC integration default options key
        $optionsKeyDefault = array(
            // General store
            'wc_el_inv-general_store_country',
            'wc_el_inv-general_store_sm_country',
            'wc_el_inv-general_store_your_name',
            'wc_el_inv-general_store_your_surname',
            'wc_el_inv-general_store_company_name',
            'wc_el_inv-general_store_vat_number',
            'wc_el_inv-general_store_tax_regime',
            'wc_el_inv-province_business_register_office',
            'wc_el_inv-rea_registration_number',
            'wc_el_inv-liquidation_status',
            'wc_el_inv-general_store_phone',
            'wc_el_inv-general_store_email',
            'wc_el_inv-general_store_vat_number_transmitter',
            'wc_el_inv-general_store_phone_transmitter',
            'wc_el_inv-general_store_email_transmitter',
            // Reverse charge
            'wc_el_inv-invoice_vies_check',
            'wc_el_inv-global_active_reverse_charge',
            'wc_el_inv-reverse_charge_tax_class',
            'wc_el_inv-ue_private_nature_code',
            'wc_el_inv-ue_private_normative_reference',
            'wc_el_inv-ue_company_nature_code',
            'wc_el_inv-ue_company_normative_reference',
            'wc_el_inv-ue_company_no_vies_nature_code',
            'wc_el_inv-ue_company_no_vies_normative_reference',
            'wc_el_inv-extra_ue_private_nature_code',
            'wc_el_inv-extra_ue_private_normative_reference',
            'wc_el_inv-extra_ue_company_nature_code',
            'wc_el_inv-extra_ue_company_normative_reference',
            // Automatic sending
            'wc_el_inv-automatic_sending_status',
            'wc_el_inv-enable_automatic_sending',
            'wc_el_inv-automatic_sending_time',
            // Webhook
            'wc_el_inv-enable_pop_webhook',
            'wc_el_inv-pop_webhook_id',
            'wc_el_inv-automatic_sending_webhook_status',
            'wc_el_inv-enable_automatic_sending_webhook',
            'wc_el_inv-automatic_sending_webhook_time',
        );
        $wcOptions         = array();
        foreach ($optionsKeyDefault as $key) {
            $wcOptions[$key] = get_option($key) ?? '';
        }

        $options = array_merge((array)$options, $wcOptions);

        return json_encode((array)$options);
    }

    /**
     * Register and add settings
     *
     * @since 1.0.0
     */
    public function pageOptionsInit()
    {
        register_setting(
        // A settings group name. Should correspond to a whitelisted option key name.
            $this->optionsName . '_group',
            // The name of an option to sanitize and save.
            $this->optionsName,
            // A callback function that sanitizes the option's value.
            $this->sanitize
        );

        /**
         * Add option and fields
         *
         * @since 1.0.0
         */
        $this->setAllSectionAndFields();
    }

    /**
     * Add options page
     *
     * @see   https://codex.wordpress.org/Function_Reference/add_menu_page
     *
     * @since 1.0.0
     */
    public function addPluginPage()
    {
        // This is the page "Settings".
        add_menu_page(
        // The text to be displayed in the title tags of the page when the menu is selected.
            esc_html__($this->menuPageTitle, WC_EL_INV_TEXTDOMAIN),
            // The text to be used for the menu.
            esc_html__($this->menuTitle, WC_EL_INV_TEXTDOMAIN),
            // The capability required for this menu to be displayed to the user.
            $this->capability,
            // The slug name to refer to this menu by (should be unique for this menu).
            $this->menuSlug,
            // The function to be called to output the content for this page.
            $this->callback,
            // The url to the icon to be used for this menu.
            $this->icon
        );

        /**
         * Add sub menu pages
         *
         * @since 1.0.0
         */
        $this->submenuPage();
    }

    /**
     * Add sub menu pages
     *
     * @param $subPageArgs
     *
     * @since 1.0.0
     *
     */
    private function addPluginSubmenuPage($subPageArgs)
    {
        if (empty($subPageArgs) || sizeof($subPageArgs) == 0) {
            return;
        }

        // This is the Sub page "Settings"
        foreach ($subPageArgs as $args) {
            add_submenu_page(
            // The slug name for the parent menu (or the file name of a standard WordPress admin page).
                $args['parent_slug'],
                // The text to be displayed in the title tags of the page when the menu is selected.
                esc_html__($args['page_title'], WC_EL_INV_TEXTDOMAIN),
                // The text to be used for the menu.
                esc_html__($args['menuTitle'], WC_EL_INV_TEXTDOMAIN),
                // The capability required for this menu to be displayed to the user.
                $args['capability'],
                // The slug name to refer to this menu by (should be unique for this menu).
                $args['menuSlug'],
                // The function that displays the page content for the menu page.
                $args['function'] ? array($this, $args['function']) : null
            );
        }
    }

    /**
     * Add sub menu page
     *
     * @return bool
     * @since 1.0.0
     *
     */
    public function submenuPage()
    {
        if (empty($this->subPageArgs) || sizeof($this->subPageArgs) == 0) {
            return false;
        }

        // Add sub menu pages
        $this->addPluginSubmenuPage($this->subPageArgs['sub_menu_page']);
    }

    /**
     * Setting all section and fields
     *
     * @since 1.0.0
     */
    public function setAllSectionAndFields()
    {
        // Add section and fields
        $this->addSectionAndFields(
            $this->sectionAndFieldsOptions()
        );
    }

    /**
     * Add sections and fields in the settings
     *
     * @param array $sectionFields
     *
     * @return bool
     * @since 1.0.0
     *
     */
    private function addSectionAndFields(array $sectionFields)
    {
        if (empty($sectionFields) || count($sectionFields) === 0) {
            return false;
        }

        // Add the section settings.
        if (! empty($sectionFields['section'])) {
            $sectionsArgs = array_filter($sectionFields['section']);
            if (! empty($sectionsArgs)) {
                foreach ($sectionsArgs as $key => $section) {
                    // Check section title structure.
                    if (is_array($sectionFields['section'][$key]['section_title'])) {
                        $titleString  = $sectionFields['section'][$key]['section_title'][1] ?? '';
                        $sectionTitle = sprintf(
                            $sectionFields['section'][$key]['section_title'][0] ?? '',
                            __($titleString, WC_EL_INV_TEXTDOMAIN)
                        );
                    } else {
                        $sectionTitle = __($sectionFields['section'][$key]['section_title'], WC_EL_INV_TEXTDOMAIN);
                    }

                    add_settings_section(
                    // Slug-name to identify the section. Used in the 'id' attribute of tags.
                        $sectionFields['section'][$key]['section_id'],
                        // Formatted title of the section. Shown as the heading for the section.
                        $sectionTitle,
                        // Function that echos out any content at the top of the section (between heading and fields).
                        $sectionFields['section'][$key]['section_callback'],
                        // The slug-name of the settings page on which to show the section.
                        $sectionFields['section'][$key]['section_page']
                    );
                }
            }
        }

        // Add the fields
        if (! empty($sectionFields['fields'])) {
            $fieldsArgs = array_filter($sectionFields['fields']);
            if (! empty($fieldsArgs)) {
                foreach ($fieldsArgs as $field) {
                    // Check empty field
                    if (empty($field)) {
                        continue;
                    }

                    add_settings_field(
                    // Slug-name to identify the field. Used in the 'id' attribute of tags.
                        $field['field_id'],
                        // Formatted title of the field. Shown as the label for the field during output.
                        wp_kses($field['field_title'], array(
                            'h4'    => array(),
                            'br'    => true,
                            'small' => true,
                            'span'  => array(
                                'class' => true,
                            ),
                        )),
                        // Function that fills the field with the desired form inputs. The function should echo its output.
                        $field['field_callback'],
                        // The slug-name of the settings page on which to show the section.
                        $field['field_page'],
                        // The slug-name of the section of the settings page.
                        $field['field_section'],
                        ! empty($field['field_args']) ? $field['field_args'] : array()
                    );
                }
            }
        }
    }

    /**
     * Check Actiore tab.
     *
     * @param $tabs
     *
     * @return string The active tab
     * @since 1.0.0
     *
     */
    public function checkPageTab($tabs)
    {
        $tab    = \WcElectronInvoice\Functions\filterInput($_GET, 'tab', FILTER_UNSAFE_RAW);
        $wizard = \WcElectronInvoice\Functions\filterInput($_GET, 'wizard', FILTER_UNSAFE_RAW);

        // Default active tab
        $activeTab = 'general';
        if ($tab && is_array($tabs)) {
            if (array_key_exists($tab, $tabs)) {
                $activeTab = $tab;
            }
        }

        if ('init' === $wizard) {
            // Show wizard template
            $activeTab = 'wizard';
        }

        return $activeTab;
    }

    /**
     * Page tabs
     *
     * @since 1.0.0
     */
    public function pageTab()
    {
        $tab    = \WcElectronInvoice\Functions\filterInput($_GET, 'tab', FILTER_UNSAFE_RAW);
        $wizard = \WcElectronInvoice\Functions\filterInput($_GET, 'wizard', FILTER_UNSAFE_RAW);
        if ('init' === $wizard || 'wizard' === $tab) {
            return;
        }

        $active = $this->checkPageTab($this->tabs);
        $output = '';

        if (! empty($this->tabs)) {
            $output = '<ul class="wc_el_inv__tabs active_' . $active . '">';
            $icon   = null;
            foreach ($this->tabs as $key => $tab) {
                $keyArgs = $key;
                if ('wizard' === $key) {
                    $keyArgs = "wizard&wizard=init";
                }

                if (is_array($tab['header']) && ! empty($tab['header'])) {
                    if ('provider-integration' === $key) {
                        $icon = ! checkOptions('checkout') ? '<span title="' . esc_html__('Complete the fields in the "Checkout" tab',
                                WC_EL_INV_TEXTDOMAIN) . '" class="field-verification dashicons dashicons-dismiss"></span>' : '';
                    } elseif ('numeration' === $key) {
                        $icon = ! checkOptions('numeration') ? '<span title="' . esc_html__('Complete the fields in "Numeration"',
                                WC_EL_INV_TEXTDOMAIN) . '" class="field-verification dashicons dashicons-dismiss"></span>' : '';
                    } else {
                        $icon = null;
                    }

                    $output .= sprintf('<li class="wc_el_inv__tabs--item %s">%s<a class="%s" href="%s">%s%s</a></li>',
                        "tab-{$key}",
                        $icon,
                        $key === $active ? 'active' : '',
                        admin_url("admin.php?page={$this->menuSlug}&tab={$keyArgs}"),
                        isset($tab['header'][0]) ? $tab['header'][0] : '', // icon
                        esc_html__($tab['header'][1], WC_EL_INV_TEXTDOMAIN) // label
                    );
                } else {
                    if (isset($tab['header'])) {
                        $output .= sprintf('<li class="wc_el_inv__tabs--item"><a class="%s" href="%s">%s</a></li>',
                            $key === $active ? 'active' : '',
                            admin_url("admin.php?page={$this->menuSlug}&tab={$key}"),
                            esc_html__($tab['header'], WC_EL_INV_TEXTDOMAIN)
                        );
                    }
                }
            }
            $output .= '</ul>';

            // Warning info
            ob_start();
            if (class_exists('WooPoPToFattureInCloud\Plugin') && 'numeration' === $active) : ?>
                <div class="pop-notice notice-info">
                    <p><span class="dashicons dashicons-info"></span>
                        <?php esc_html_e(
                            'Some fields on this page have been disabled because you can now manage them from your account on Fatture in Cloud.',
                            WC_EL_INV_TEXTDOMAIN
                        ); ?>
                    </p>
                </div>
            <?php endif;
            $output .= ob_get_clean();
        }

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $output;
    }

    /**
     * Options page callback
     *
     * @since 1.0.0
     */
    public function createPage()
    {
        $active          = $this->checkPageTab($this->tabs);
        $submit          = isset($this->tabs[$active]['submit']) ? $this->tabs[$active]['submit'] : true;
        $ficAddonClass   = class_exists('WooPoPToFattureInCloud\Plugin') ? 'wc_el_inv-fic-addon' : '';
        $arubaAddonClass = class_exists('WooPoPToFattureAruba\Plugin') ? 'wc_el_inv-aruba-addon' : '';
        $uidOption       = (int)get_option('pop_account_user_id', false);
        $noConnect       = ! $uidOption ? 'pop_not_connected' : 'pop_connected';

        // POP Notifications
        $notifications      = \WcElectronInvoice\Functions\notifications();
        $notificationsClass = $notifications ? 'have_notifications' : '';
        add_action('wc_el_inv-plugin_header_notice', function () use ($notifications) {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo $notifications;
        });
        ?>

        <div class="wc_el_inv-wrapper no-js <?php echo esc_attr("{$notificationsClass} {$ficAddonClass} {$arubaAddonClass} current-{$this->tabs[$active]['section_id']}"); ?>">
            <form class="wc_el_inv-form <?php echo esc_attr($noConnect); ?>" id="options_form" name="options_form"
                  method="post" action="options.php">
                <input name="tab" type="hidden" value="<?php echo esc_attr($active); ?>">
                <header class="wc_el_inv__header">
                    <div id="icon-themes" class="icon32"></div>
                    <h2>
                        <img class="pop-logo" title="<?php echo esc_html__('POP', WC_EL_INV_TEXTDOMAIN); ?>"
                             src="<?php echo esc_url(WC_EL_INV_URL . 'assets/images/pop.svg'); ?>">
                        <small class="version">v<?php echo esc_attr(WC_EL_INV_VERSION); ?></small>
                        <?php do_action('wc_el_inv-plugin_header_license_info'); ?>
                    </h2>
                    <?php if (phpversion() < 7.4) : ?>
                        <p class="php_version">
                            <?php esc_html_e('POP 4.0.0 made some changes that require PHP 7.4. it is recommended to update the PHP version.',
                                WC_EL_INV_TEXTDOMAIN) ?>
                        </p>
                    <?php endif; ?>
                </header>

                <div class="wrap">
                    <?php do_action('wc_el_inv-plugin_header_notice'); ?>
                </div>

                <?php $this->pageTab(); ?>
                <?php
                // This hidden setting fields.
                settings_fields(
                // A settings group name. This should match the group name used in register_setting().
                    $this->optionsName . '_group'
                );
                // Prints out all settings sections added to a particular settings page.
                do_settings_sections(
                // The slug name of the page whos settings sections you want to output.
                    $this->menuSlug
                );

                /**
                 * Before closing Settings Form
                 *
                 * @since 3.2.4
                 */
                do_action('wc_el_inv-before_closing_settings_form');

                if ($submit) {
                    // A submit button.
                    submit_button(
                    // The text of the button (defaults to 'Save Changes').
                        esc_html__('Save data', WC_EL_INV_TEXTDOMAIN)
                    );
                }
                ?>
            </form>

            <?php
            /**
             * After Settings Form
             *
             * @since 1.0.0
             */
            do_action('wc_el_inv-after_settings_form');
            ?>
        </div>

        <?php
    }

    /**
     * Sub menu page
     *
     * @since 1.0.0
     */
    function subMenuPageCreate()
    {
    }

    /**
     * Premium settings are editable only on paid plans.
     *
     * @return bool
     */
    private function isPremiumSettingsLocked()
    {
        $level = \WcElectronInvoice\Wizard::popGetUserLevel();

        return ! \WcElectronInvoice\Wizard::isUserLevelGte($level, 'basic');
    }

    /**
     * Premium option keys grouped by settings tab.
     *
     * @param string $tab
     *
     * @return array
     */
    private function getPremiumSettingsKeysByTab($tab)
    {
        $premiumKeys = array(
            'numeration' => array(
                'wc_el_inv-settings-prefix_credit_note_number',
                'wc_el_inv-settings-numeration_credit_note_active',
                'wc_el_inv-settings-number_next_credit_note',
                'wc_el_inv-settings-prefix_credit_note_receipt_number',
                'wc_el_inv-settings-numeration_credit_note_receipt_active',
                'wc_el_inv-settings-number_next_credit_note_receipt',
            ),
            'invoice'    => array(
                'wc_el_inv-settings-invoice_saving_directory_xml_enable',
                'wc_el_inv-settings-invoice_saving_directory_xml',
            ),
            'advanced'   => array(
                'wc_el_inv-invoice_vies_check',
                'wc_el_inv-global_active_reverse_charge',
                'wc_el_inv-reverse_charge_tax_class',
                'wc_el_inv-ue_private_nature_code',
                'wc_el_inv-ue_private_normative_reference',
                'wc_el_inv-ue_company_nature_code',
                'wc_el_inv-ue_company_normative_reference',
                'wc_el_inv-ue_company_no_vies_nature_code',
                'wc_el_inv-ue_company_no_vies_normative_reference',
                'wc_el_inv-extra_ue_private_nature_code',
                'wc_el_inv-extra_ue_private_normative_reference',
                'wc_el_inv-extra_ue_company_nature_code',
                'wc_el_inv-extra_ue_company_normative_reference',
                'wc_el_inv-automatic_sending_status',
                'wc_el_inv-enable_automatic_sending',
                'wc_el_inv-automatic_sending_time',
                'wc_el_inv-enable_pop_webhook',
                'wc_el_inv-pop_webhook_id',
                'wc_el_inv-automatic_sending_webhook_status',
                'wc_el_inv-enable_automatic_sending_webhook',
                'wc_el_inv-automatic_sending_webhook_time',
            ),
        );

        return $premiumKeys[$tab] ?? array();
    }

    /**
     * Prevent premium keys from being modified on free plans.
     *
     * @param array  $options
     * @param string $tab
     *
     * @return array
     */
    private function filterLockedPremiumSettings(array $options, $tab)
    {
        if (! $this->isPremiumSettingsLocked()) {
            return $options;
        }

        foreach ($this->getPremiumSettingsKeysByTab($tab) as $key) {
            unset($options[$key]);
        }

        return $options;
    }

    /**
     * Sanitize and Store each setting field as needed
     *
     * @param $input
     *
     * @return array|bool|string
     * @since 1.0.0
     *
     */
    public function sanitizeOptions($input)
    {
        $this->sanitizeWCIntegrationOptions($_POST);

        // Save environment setting
        $env = \WcElectronInvoice\Functions\filterInput($_POST, 'wc_el_inv_environment', FILTER_UNSAFE_RAW);
        if ($env && in_array($env, ['live', 'sandbox'], true)) {
            update_option('wc_el_inv_environment', $env);
        }

        $tab   = \WcElectronInvoice\Functions\filterInput($_POST, 'tab', FILTER_UNSAFE_RAW);
        $input = $this->filterLockedPremiumSettings((array)$input, $tab);

        // Unset export field
        unset($input['wc_el_inv-settings-export_collections']);
        // Get import data
        $importData = $input['wc_el_inv-settings-import_collections'] ?? null;

        // Sanitize input
        $sanitizedValue = \WcElectronInvoice\Functions\sanitize($input);

        // If is not options
        if (! $this->options) {
            $this->options = $input;
        } else {
            $currentOptions = $sanitizedValue;
        }

        // Set import data as current options
        if ($importData) {
            $currentOptions = json_decode($importData, true) ?? array();
            $currentOptions = $this->filterLockedPremiumSettings((array)$currentOptions, $tab);
            // Unset import field
            unset($input['wc_el_inv-settings-import_collections']);
        }

        if (! empty($currentOptions) && is_array($currentOptions)) {
            // Update old value
            foreach ($currentOptions as $key => $option) {
                // Current $_POST data
                if (isset($currentOptions[$key]) && $currentOptions[$key] !== $this->options[$key]) {
                    $this->options[$key] = $currentOptions[$key];
                }

                // Set Fallback number is setOption not save
                if ($key === 'wc_el_inv-settings-number_next_credit_note') {
                    update_option("number_next_credit_note", $option);
                }
                if ($key === 'wc_el_inv-settings-number_next_credit_note_receipt') {
                    update_option("number_next_credit_note_receipt", $option);
                }

                $checkBoxesNumeration  = array(
                    'wc_el_inv-settings-reset_numerations_year_change',
                    'wc_el_inv-settings-suffix_year_invoice_number',
                    'wc_el_inv-settings-numeration_credit_note_active',
                    'wc_el_inv-settings-numeration_credit_note_receipt_active',
                );
                $checkBoxesInvoice     = array(
                    'wc_el_inv-settings-disable_invoice_number_order_zero',
                    'wc_el_inv-settings-remove_product_from_invoice_is_total_zero',
                    'wc_el_inv-settings-invoice_description_type',
                    'wc_el_inv-settings-invoice_product_meta',
                    'wc_el_inv-settings-add_stamp_duty',
                    'wc_el_inv-settings-stamp_duty_paid_customer',
                    'wc_el_inv-settings-add_rivalsa_inps',
                    'wc_el_inv-settings-add_rivalsa_inps_paid_customer',
                    'wc_el_inv-settings-invoice_in_my_orders',
                    'wc_el_inv-settings-invoice_via_email',
                    'wc_el_inv-settings-invoice_html',
                );
                $checkBoxesIntegration = array(
                    'wc_el_inv-settings-invoice_choice_type',
                    'wc_el_inv-settings-invoice_disable_pec_sdi',
                    'wc_el_inv-settings-invoice_disable_cf',
                    'wc_el_inv-settings-invoice_active_js_cf_check',
                );

                // When input is checkbox if not isset value is null
                // Forced off value
                // !! invoice tab and numeration have checkbox !!
                if ('invoice' === $tab || 'numeration' === $tab) {
                    if (! array_key_exists($key, $currentOptions) &&
                        ! isset($currentOptions[$key]) &&
                        null === $currentOptions[$key] &&
                        'on' === $currentOptions[$key]
                    ) {
                        // check ??
                        $this->options[$key] = 'off';
                    } else {
                        foreach ($this->options as $optionKey => $value) {
                            if ('numeration' === $tab) {
                                foreach ($checkBoxesNumeration as $name) {
                                    if (isset($this->options[$name]) && 'on' === $this->options[$name] && ! isset($currentOptions[$name])) {
                                        $this->options[$name] = 'off';
                                    }
                                }
                            } elseif ('invoice' === $tab) {
                                foreach ($checkBoxesInvoice as $name) {
                                    if (isset($this->options[$name]) && 'on' === $this->options[$name] && ! isset($currentOptions[$name])) {
                                        $this->options[$name] = 'off';
                                    }
                                }
                                $selectKey = 'wc_el_inv-settings-invoice_ref_normative_N4_nature';
                                if (isset($this->options[$selectKey]) && $currentOptions[$selectKey] !== $this->options[$selectKey]) {
                                    $this->options[$selectKey] = $currentOptions[$selectKey];
                                }
                            }

                            if (isset($this->options[$optionKey]) && ! isset($currentOptions[$optionKey]) && 'off' === $this->options[$optionKey]) {
                                $this->options[$key] = $currentOptions[$key];
                            }
                        }
                    }
                } elseif ('provider-integration' === $tab) {
                    // When input is checkbox if not isset value is null
                    // Forced off value
                    // !! provider-integration have checkbox !!
                    if (! array_key_exists($key, $currentOptions) &&
                        ! isset($currentOptions[$key]) &&
                        null === $currentOptions[$key] &&
                        'on' === $currentOptions[$key]
                    ) {
                        // check ??
                        $this->options[$key] = 'off';
                    } else {
                        foreach ($this->options as $optionKey => $value) {
                            foreach ($checkBoxesIntegration as $name) {
                                if (isset($this->options[$name]) && 'on' === $this->options[$name] && ! isset($currentOptions[$name])) {
                                    $this->options[$name] = 'off';
                                }
                            }
                        }
                    }
                    foreach ($currentOptions as $optionKey => $value) {
                        if (isset($this->options[$optionKey]) && $this->options[$optionKey] !== $value) {
                            $this->options[$optionKey] = $value;
                        }
                    }
                } elseif ('general' === $tab) {
                    foreach ($currentOptions as $optionKey => $value) {
                        if (isset($this->options[$optionKey]) && $this->options[$optionKey] !== $value) {
                            $this->options[$optionKey] = $value;
                        }

                        // Wc integration options
                        if (false === strpos($optionKey, '-settings-')) {
                            update_option($optionKey, $value);
                        }
                    }
                }
            }

            // Merge options
            if ($currentOptions) {
                $this->options = array_merge($this->options, $currentOptions);
            }
        }

        // Update configurations
        $config = $this->updatePopConfigurations($this->options);
        if ($config && $config->options) {
            $this->options = $config->options;
        }

        // Update license API key
        if ($this->options['wc_el_inv-settings-license_key'] !== $this->options['wc_el_inv-settings-key']) {
            $wizard = new Wizard();
            $wizard->setLicense($this->options['wc_el_inv-settings-license_key']);
            // update level
            \WcElectronInvoice\Wizard::popGetUserLevel(true);
        }

        // Warn when a manually set next-number is lower than the last assigned in the current series.
        $numberSeriesFields = [
            'wc_el_inv-settings-number_next_invoice' => 'number_next_invoice',
            'wc_el_inv-settings-number_next_receipt' => 'number_next_receipt',
        ];
        $postedOptions = isset($_POST[$this->optionsName]) && is_array($_POST[$this->optionsName]) ? (array)$_POST[$this->optionsName] : [];
        $manualResetFields = [
            'wc_el_inv_manual_reset_number_next_invoice' => [
                'legacy_option_key' => 'wc_el_inv-settings-manual_reset_number_next_invoice',
                'number_field_key'  => 'wc_el_inv-settings-number_next_invoice',
                'option_key'        => 'number_next_invoice',
            ],
            'wc_el_inv_manual_reset_number_next_receipt' => [
                'legacy_option_key' => 'wc_el_inv-settings-manual_reset_number_next_receipt',
                'number_field_key'  => 'wc_el_inv-settings-number_next_receipt',
                'option_key'        => 'number_next_receipt',
            ],
        ];

        // Receipts always use their own separate numbering sequence; enforce minimum 1.
        $receiptKey = 'wc_el_inv-settings-number_next_receipt';
        if (isset($this->options[$receiptKey]) && (int)$this->options[$receiptKey] < 1) {
            $this->options[$receiptKey] = 1;
        }

        $manualResetApplied = [];
        foreach ($manualResetFields as $fieldKey => $config) {
            $optionKey      = $config['option_key'];
            $legacyOptionKey = $config['legacy_option_key'];
            $numberFieldKey = $config['number_field_key'];
            $resetRequested = (
                (! empty($_POST[$fieldKey]) && 'on' === (string)$_POST[$fieldKey])
                ||
                (! empty($postedOptions[$legacyOptionKey]) && 'on' === (string)$postedOptions[$legacyOptionKey])
                ||
                (! empty($this->options[$legacyOptionKey]) && 'on' === (string)$this->options[$legacyOptionKey])
            );
            $setValue       = isset($postedOptions[$numberFieldKey]) ? (int)$postedOptions[$numberFieldKey] : 0;
            if ($setValue < 1 && isset($this->options[OptionPage::$optionKey . $optionKey])) {
                $setValue = (int)$this->options[OptionPage::$optionKey . $optionKey];
            }

            if ($resetRequested && $setValue >= 1 && function_exists('\WcElectronInvoice\Functions\registerManualNumerationResetForSeries')) {
                $this->options = \WcElectronInvoice\Functions\registerManualNumerationResetForSeries($optionKey, $setValue, $this->options);
                $manualResetApplied[$optionKey] = true;
            }

            unset($this->options[$fieldKey], $this->options[$legacyOptionKey]);
        }

        $numberOverrideWarnings = [];
        foreach ($numberSeriesFields as $fieldKey => $optionKey) {
            $setValue = isset($this->options[$fieldKey]) ? (int)$this->options[$fieldKey] : 0;
            if (! empty($manualResetApplied[$optionKey])) {
                continue;
            }

            if ($setValue >= 1 && function_exists('\WcElectronInvoice\Functions\getLastAssignedInvoiceCandidateForSeries')) {
                $candidate    = \WcElectronInvoice\Functions\getLastAssignedInvoiceCandidateForSeries($optionKey);
                $lastAssigned = (int)$candidate['number'];
                if ($lastAssigned > 0 && $setValue <= $lastAssigned) {
                    $numberOverrideWarnings[$optionKey] = [
                        'set_value'    => $setValue,
                        'last_assigned' => $lastAssigned,
                        'will_use'     => $lastAssigned + 1,
                    ];
                }
            }
        }
        if (! empty($numberOverrideWarnings)) {
            set_transient('wc_el_inv-number-next-override-warning', $numberOverrideWarnings, 60);
        }

        // Save extra data.
        $this->saveExtraData();

        return $this->options;
    }

    /**
     * sanitizeWCIntegrationOptions
     *
     * @param $postData
     *
     * @return void
     */
    public function sanitizeWCIntegrationOptions($postData)
    {
        $sanitizedValue = sanitize($postData);
        $tab            = filterInput($_POST, 'tab', FILTER_UNSAFE_RAW);
        if ('advanced' === $tab) {
            // advanced default options key
            $optionsKeyDefault = array(
                // Reverse charge
                'wc_el_inv-invoice_vies_check',
                'wc_el_inv-global_active_reverse_charge',
                'wc_el_inv-reverse_charge_tax_class',
                'wc_el_inv-ue_private_nature_code',
                'wc_el_inv-ue_private_normative_reference',
                'wc_el_inv-ue_company_nature_code',
                'wc_el_inv-ue_company_normative_reference',
                'wc_el_inv-ue_company_no_vies_nature_code',
                'wc_el_inv-ue_company_no_vies_normative_reference',
                'wc_el_inv-extra_ue_private_nature_code',
                'wc_el_inv-extra_ue_private_normative_reference',
                'wc_el_inv-extra_ue_company_nature_code',
                'wc_el_inv-extra_ue_company_normative_reference',
                // Automatic sending
                'wc_el_inv-automatic_sending_status',
                'wc_el_inv-enable_automatic_sending',
                'wc_el_inv-automatic_sending_time',
                // Webhook
                'wc_el_inv-enable_pop_webhook',
                'wc_el_inv-pop_webhook_id',
                'wc_el_inv-automatic_sending_webhook_status',
                'wc_el_inv-enable_automatic_sending_webhook',
                'wc_el_inv-automatic_sending_webhook_time',
            );

            /**
             * Filter default options key
             */
            $optionsKey = apply_filters('wc_el_inv-provider-integration-fields-key', $optionsKeyDefault);
            if (empty($optionsKey)) {
                $optionsKey = $optionsKeyDefault;
            }

            if (! empty($optionsKey)) {
                if ($this->isPremiumSettingsLocked()) {
                    return;
                }

                foreach ($optionsKey as $key) {
                    $value = filterInput($sanitizedValue, $key, FILTER_UNSAFE_RAW);
                    if ('wc_el_inv-global_active_reverse_charge' === $key && 1 === (int)$value ||
                        'wc_el_inv-invoice_vies_check' === $key && 1 === (int)$value ||
                        'wc_el_inv-enable_automatic_sending' === $key && 1 === (int)$value ||
                        'wc_el_inv-enable_pop_webhook' === $key && 1 === (int)$value ||
                        'wc_el_inv-enable_automatic_sending_webhook' === $key && 1 === (int)$value
                    ) {
                        update_option($key, 'yes');
                    } else {
                        update_option($key, $value);
                    }
                }
            }
        }
    }

    /**
     * updatePopConfigurations
     *
     * @return false|object
     */
    public function updatePopConfigurations($options)
    {
        $tab = filterInput($_POST, 'tab', FILTER_UNSAFE_RAW);
        if ('provider-integration' === $tab) {
            $uidOption = (int)get_option('pop_account_user_id', false);
            if ($uidOption) {
                $wizard = new Wizard();
                $config = $wizard->updateConfig($options['wc_el_inv-settings-license_key']);

                // Set license_key from API
                if (property_exists($config, 'license_key') && isset($config->license_key)) {
                    $options['wc_el_inv-settings-license_key'] = $config->license_key;
                    $options['wc_el_inv-settings-key']         = $config->license_key;
                }

                return (object)array(
                    'config'  => $config,
                    'options' => $options,
                );
            }
        }

        return false;
    }

    /**
     * Save Extra Data.
     *
     * @since 1.0.0
     */
    public function saveExtraData()
    {
        $active    = $this->checkPageTab($this->tabs);
        $uidOption = (int)get_option('pop_account_user_id', false);

        $args[$this->optionsName] = array(
            'filter' => array(FILTER_UNSAFE_RAW),
            'flags'  => FILTER_FORCE_ARRAY,
        );

        // Key data saved
        $data = filter_var_array($_POST, $args);
        $Lkey = isset($data[$this->optionsName]['wc_el_inv-settings-license_key']) ?
            $data[$this->optionsName]['wc_el_inv-settings-license_key'] : null;

        $secretApiKey = null;
        if (isset($Lkey) && '' !== $Lkey) {
            // reset allowedAddon and repeat the check
            \WcElectronInvoice\Plugin::allowedAddon(true);
            $currentLicense = get_option('wc_el_inv-license_check');
            if (! $currentLicense) {
                // Old data
                $currentLicense = get_transient('wc_el_inv-license_check');
                update_option('wc_el_inv-license_check', $currentLicense);
                delete_transient('wc_el_inv-license_check');
            }

            $licenseKey = OptionPage::init()->getOptions('license_key');
            $getK       = self::getK() ?: false;

            if (! $currentLicense || ($licenseKey !== $Lkey) || ! $getK) {
                if ($licenseKey !== $Lkey) {
                    update_option('wc_el_inv-license_check', null);
                }
            }

            if ('general' === $active &&
                $data &&
                is_array($data[$this->optionsName]) &&
                array_key_exists('wc_el_inv-settings-key', $data[$this->optionsName])
            ) {
                if (! $currentLicense && ! $secretApiKey) {
                    // Delete license transient.
                    delete_option('wc_el_inv-license_check');
                    if (! $uidOption) {
                        update_option('wc_el_inv-secret-api-key', '');
                    }
                }
            }
        } else {
            delete_option('wc_el_inv-license_check');
            if (! $uidOption) {
                update_option('wc_el_inv-secret-api-key', '');
            }
        }
    }

    /**
     * Instance
     *
     * @param null
     *
     * @return OptionPage|object The Class Instance
     * @since 1.0.0
     *
     */
    public static function init()
    {
        if (null === self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;
    }
}
