<?php
/**
 * Oxygen MyData Class File
 *
 * @package Oxygen
 * @summary Class to add WooCommerce settings tab and fields, WooCommerce categories fields
 * @version 2.0.38
 * @since  1.0.0
 */

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

/**
 * Oxygen Woo Settings Class
 */
class OxygenWooSettings {

	/**
	 * Singleton Instance of Oxygen Woo Settings
	 *
	 * @var OxygenWooSettings
	 **/

	public string $id;
	public string $label;
	private static $instance = null;

	/**
	 * Singleton init Function
	 *
	 * @static
	 */
	public static function init() {
		if ( ! self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * OxygenWooSettings Constructor
	 */
	private function __construct() {

		$this->id    = 'oxygen_tab';
		$this->label = __( 'Oxygen', 'oxygen' );

		add_action( 'woocommerce_update_options_oxygen', __CLASS__ . '::update_settings', 1 );
		add_filter( 'woocommerce_settings_tabs_array', array( $this, 'add_settings_tab' ), 50 );
		add_action( "woocommerce_settings_{$this->id}", array( $this, 'output' ) );
		add_action( "woocommerce_settings_save_{$this->id}", array( $this, 'save' ) );
		add_action( 'woocommerce_admin_field_html', __CLASS__ . '::html_field', 10, 1 );
		add_action( 'woocommerce_admin_field_toggle', __CLASS__ . '::toggle_field', 10, 1 );
		add_action( 'woocommerce_update_option_toggle', array( $this, 'save_toggle_field' ), 10, 1 );

		/* Product categories - on prod. category creation or edit adds mydata_category / mydata_classification_type */
		add_action( 'product_cat_edit_form_fields', __CLASS__ . '::edit_term_fields', 10, 2 );

		/* Products - on product creation or edit adds mydata_category / mydata_classification_type */
		add_action( 'edited_product_cat', __CLASS__ . '::save_term_fields' );

		/* Products - add tabs/panels */
		add_action( 'woocommerce_product_data_tabs', array( __CLASS__, 'product_data_tabs' ) );
		add_action( 'woocommerce_product_data_panels', array( __CLASS__, 'product_data_panels' ) );

		/* On products creation or edit these triggers */
		add_action( 'woocommerce_update_product', array( __CLASS__, 'product_save' ), 10, 1 );

		/* Buttons settings and download log file */
		add_action( 'admin_init', array( $this, 'download_oxygen_settings' ), 10, 1 );
		add_action( 'wp_ajax_download_wc_log', array( $this, 'download_wc_log' ) );

		add_action( 'woocommerce_product_options_inventory_product_data', array( $this, 'add_measurement_unit_option' ) );
		add_action( 'woocommerce_process_product_meta', array( $this, 'add_measurement_unit_option' ) );

	}

	/**
	 * Adds the custom settings tab label to the WooCommerce settings tabs array.
	 *
	 * This method hooks into WooCommerce's settings system to register
	 * a new tab using the `$id` and `$label` defined in the class.
	 *
	 * @param array $settings_tabs Existing array of WooCommerce settings tabs.
	 * @return array Modified array with the custom settings tab included.
	 */
	public function add_settings_tab( $settings_tabs ) {
		$settings_tabs[ $this->id ] = $this->label;
		return $settings_tabs;
	}

	/**
	 * Outputs the settings page content for the custom WooCommerce settings tab.
	 *
	 * This method:
	 * - Sets the current section based on the query parameter.
	 * - Displays any API error messages stored in transients.
	 * - Displays section navigation links if multiple sections are defined.
	 * - Outputs the settings fields for the selected section.
	 *
	 * @global string $current_section The currently selected section.
	 *
	 * @return void
	 */
	public function output() {

		global $current_section;
		$current_section = isset( $_GET['section'] )
			? sanitize_text_field( wp_unslash( $_GET['section'] ) )
			: 'general';

		// Fetch and display transient errors.
		OxygenHelperFunctions::api_checks();

		$errors = get_transient( 'oxygen_api_errors' );
		if ( ! empty( $errors ) ) {
			foreach ( $errors as $error ) {
				echo '<div class="error"><p>' . esc_html( $error ) . '</p></div>';
			}
		}

		$sections = $this->get_sections();
		if ( ! empty( $sections ) ) {
			echo '<ul class="subsubsub" id="oxygen_tab">';
			foreach ( $sections as $section_id => $section_label ) {
				echo '<li><a href="?page=wc-settings&tab=' . esc_attr( $this->id ) . '&section=' . esc_attr( $section_id ) . '" class="' . ( $current_section === $section_id ? 'current' : '' ) . '">' . esc_html( $section_label ) . '</a> | </li>';
			}
			echo '</ul><br class="clear" />';

		}

		$settings = $this->get_settings( $current_section );
		WC_Admin_Settings::output_fields( $settings );
	}

	/**
	 * Saves the settings for the current section.
	 *
	 * Retrieves the settings fields for the current section under this tab
	 * and saves them using WooCommerce's built-in settings handler.
	 *
	 * @global string $current_section The currently active settings section.
	 *
	 * @return void
	 */
	public function save() {

		global $current_section;
		$settings = $this->get_settings( $current_section );
		WC_Admin_Settings::save_fields( $settings );
	}

	/**
	 * Retrieves the available sections for the custom settings tab.
	 *
	 * This method defines the default sections under the plugin's WooCommerce tab.
	 * Sections may be conditionally removed based on the plugin's settings,
	 * such as whether an API key is set or if the plugin is configured to use
	 * receipts only (and not invoices).
	 *
	 * Additionally, the returned sections can be filtered using the
	 * "woocommerce_get_sections_{$this->id}" filter.
	 *
	 * @return array Array of section slugs as keys and translated labels as values.
	 */
	public function get_sections() {

		// Define sections under the tab.
		$sections = array(
			'general'                     => __( 'General', 'oxygen' ),
			'receipts_settings'           => __( 'Receipts', 'oxygen' ),
			'invoices_settings'           => __( 'Invoices', 'oxygen' ),
			'intra_community_settings'    => __( 'Intra-Community', 'oxygen' ),
			'taxes_and_series_settings'   => __( 'Taxes & Series', 'oxygen' ),
			'general_documents_settings'  => __( 'Documents', 'oxygen' ),
			'shipping_data_settings'      => __( 'Shipping Data', 'oxygen' ),
			'order_and_products_settings' => __( 'Orders & Products', 'oxygen' ),
			'payments_settings'           => __( 'Payments', 'oxygen' ),

		);

		if ( empty( get_option( 'oxygen_api_key' ) ) ) {
			// Keep only the 'general' section and unset all others.
			$sections = array_intersect_key( $sections, array( 'general' => '' ) );
		}

		if ( 'yes' === get_option( 'oxygen_only_receipts' ) ) {
			unset( $sections['invoices_settings'] );
			unset( $sections['intra_community_settings'] );
		}

		if ( 'yes' !== get_option( 'oxygen_enable_intra_community_invoice' ) ) {
			unset( $sections['intra_community_settings'] );
		}

		if( 'yes' !== get_option( 'oxygen_enable_shipping_data' ) ) {
			unset( $sections['shipping_data_settings'] );
		}

		return apply_filters( "woocommerce_get_sections_{$this->id}", $sections );
	}



	/**
	 * Retrieves the settings fields for a given section.
	 *
	 * Returns the array of settings fields to be displayed and saved for
	 * the specified section under the plugin's WooCommerce settings tab.
	 * Each section can define its own group of configurable options.
	 *
	 * @param string $section Optional. Section ID. Default empty string for the general section.
	 * @return array Array of WooCommerce settings fields for the given section.
	 */
	public function get_settings( $section = '' ) {
		// Define settings fields based on the section.

		$oxygen_document_types      = OxygenHelperFunctions::document_types();
		$oxygen_document_type_names = OxygenHelperFunctions::document_type_names();
		$oxygen_taxes               = OxygenHelperFunctions::oxygen_tax_options();
		$default_logo_id            = OxygenHelperFunctions::get_default_logo_id();
		$available_payment_methods  = WC()->payment_gateways->payment_gateways();

		$oxygen_taxes_zero = array_filter(
			$oxygen_taxes,
			function ( $label ) {
				return preg_match( '/\s*-\s*0\.00(\s*-\s*Κατηγορία εξαίρεσης ΦΠΑ\s*\d+)?$/', trim( $label ) );
			}
		);

		switch ( $section ) {
			case 'receipts_settings':
				$settings = array(
					array(
						'title' => __( 'Receipts Settings', 'oxygen' ),
						'type'  => 'title',
						'desc'  => __( 'Default Settings for Receipts. Make sure to click Save after any changes.', 'oxygen' ),
						'id'    => 'oxygen_receipts_settings_header',
					),
					array(
						'type' => 'sectionend',
						'id'   => 'receipts_settings_end',
					),
					array(
						'type' => 'html',
						'html' => '<p style="margin-bottom: 60px;"></p>',
					),
					array(
						'name' => __( 'Receipt of Goods Settings:', 'oxygen' ),
						'id'   => 'oxygen_alp_settings_header',
						'type' => 'title',
					),
					array(
						'title'   => __( 'myDATA classification Category for Receipt of Goods:', 'oxygen' ),
						'id'      => 'oxygen_mydata_category_alp',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_categories(),
						'class'   => 'main mydata_category',
					),
					array(
						'title'   => __( 'myDATA classification Type for Receipt of Goods:', 'oxygen' ),
						'id'      => 'oxygen_mydata_classification_type_alp',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_types_receipts(),
						'class'   => 'mydata_classification_type',
					),
					array(
						'type' => 'sectionend',
						'id'   => 'receipts_settings_end',
					),
					array(
						'type' => 'html',
						'html' => '<p style="margin-bottom: 60px;"></p>',
					),
					array(
						'name' => __( 'Receipt of Service Settings:', 'oxygen' ),
						'id'   => 'oxygen_apy_settings_header',
						'type' => 'title',
					),
					array(
						'title'   => __( 'myDATA classification Category for Receipt of Service:', 'oxygen' ),
						'id'      => 'oxygen_mydata_category_apy',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_categories( 'category1_3' ),
						'class'   => 'main mydata_category',
					),
					array(
						'title'   => __( 'myDATA classification Type for Receipt of Service:', 'oxygen' ),
						'id'      => 'oxygen_mydata_classification_type_apy',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_types_receipts(),
						'class'   => 'mydata_classification_type',
					),
					array(
						'type' => 'sectionend',
						'id'   => 'receipts_settings_end',
					),
					array(
						'type' => 'html',
						'html' => '<p style="margin-bottom: 60px;"></p>',
					),
					array(
						'name' => __( 'Print Settings:', 'oxygen' ),
						'id'   => 'oxygen_print_settings_header',
						'type' => 'title',
						'desc' => __( 'Generic print settings for Receipts.', 'oxygen' ),
					),
					array(
						'name'    => __( 'Default Print Mode:', 'oxygen' ),
						'id'      => 'oxygen_receipt_print_type',
						'type'    => 'select',
						'options' => array(
							'0'    => __( 'Select mode', 'oxygen' ),
							'a4'   => 'A4',
							'80mm' => __( '80mm ( for thermal printer)', 'oxygen' ),
						),
					),
					array(
						'type' => 'sectionend',
						'id'   => 'receipts_settings_end',
					),
				);
				break;

			case 'invoices_settings':
				$user_meta_keys = OxygenHelperFunctions::get_user_meta_keys();

				$settings = array(
					array(
						'title' => __( 'Invoice Settings', 'oxygen' ),
						'type'  => 'title',
						'desc'  => __( 'Default Settings for Invoices. Make sure to click Save after any changes.', 'oxygen' ),
						'id'    => 'oxygen_invoices_settings_header',
					),
					array(
						'type' => 'sectionend',
						'id'   => 'receipts_settings_end',
					),
					array(
						'type' => 'html',
						'html' => '<p style="margin-bottom: 60px;"></p>',
					),
					array(
						'name' => __( 'Customer Facing Fields:', 'oxygen' ),
						'id'   => 'oxygen_customers_settings_header',
						'type' => 'title',
					),
					array(
						'name'     => __( 'Use Oxygen WooCommerce Plugin invoice fields:', 'oxygen' ),
						'desc_tip' => __(
							'Activating this option will use the plugin’s default invoicing fields, instead of any 3rd party plugin you may have installed.',
							'oxygen'
						),
						'id'       => 'oxygen_self_fields',
						'type'     => 'toggle',
						'toggle'   => '',
					),
					array(
						'name'    => __( 'Customer VAT/TIN number', 'oxygen' ),
						'id'      => 'oxygen_vat_metakey',
						'type'    => 'select',
						'options' => array( '0' => '' ) + $user_meta_keys,
					),
					array(
						'title'   => __( 'Customer Job Description', 'oxygen' ),
						'id'      => 'oxygen_working_field_metakey',
						'type'    => 'select',
						'options' => array( '0' => '' ) + $user_meta_keys,
					),
					array(
						'title'   => __( 'Customer Tax Office', 'oxygen' ),
						'id'      => 'oxygen_tax_office',
						'type'    => 'select',
						'options' => array( '0' => '' ) + $user_meta_keys,
					),
					array(
						'name'    => __( 'Auto-issue an invoice or notice when this field is checked', 'oxygen' ),
						'id'      => 'oxygen_issue_invoice_metakey',
						'type'    => 'select',
						'options' => array( '0' => '' ) + $user_meta_keys,
					),
					array(
						'name'     => __( 'Fetch invoicing details via Tax ID (VIES) during checkout:', 'oxygen' ),
						'desc_tip' => __( 'The plugin will search via Taxisnet or VIES, depending on the Tax ID’s origin country, and auto-complete all fields necessary for invoicing during checkout.', 'oxygen' ),
						'id'       => 'oxygen_fetch_vat_fields',
						'type'     => 'toggle',
						'toggle'   => '',
					),
					array(
						'type' => 'sectionend',
						'id'   => 'invoices_settings_end',
					),
					array(
						'name' => __( 'Invoice of Goods/Shipping Settings:', 'oxygen' ),
						'id'   => 'oxygen_tpda_settings_header',
						'type' => 'title',
					),
					array(
						'title'   => __( 'myDATA classification Category for Invoice of Goods:', 'oxygen' ),
						'id'      => 'oxygen_mydata_category_tpda',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_categories(),
						'class'   => 'main mydata_category',
					),
					array(
						'title'   => __( 'myDATA classification Type for Invoice of Goods:', 'oxygen' ),
						'id'      => 'oxygen_mydata_classification_type_tpda',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_types_invoices(),

						'class'   => 'mydata_classification_type',
					),
					array(
						'type' => 'sectionend',
						'id'   => 'receipts_settings_end',
					),
					array(
						'type' => 'html',
						'html' => '<p style="margin-bottom: 60px;"></p>',
					),
					array(
						'name' => __( 'Invoice of Service Settings:', 'oxygen' ),
						'id'   => 'oxygen_tpy_settings_header',
						'type' => 'title',
					),
					array(
						'title'   => __( 'myDATA classification Category for Invoice of Service:', 'oxygen' ),
						'id'      => 'oxygen_mydata_category_tpy',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_categories( 'category1_3' ),
						'class'   => 'main mydata_category',
					),
					array(
						'title'   => __( 'myDATA classification Type for Invoice of Service:', 'oxygen' ),
						'id'      => 'oxygen_mydata_classification_type_tpy',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_types_invoices(),
						'class'   => 'mydata_classification_type',
					),
					array(
						'type' => 'sectionend',
						'id'   => 'receipts_settings_end',
					),
				);

				break;

			case 'intra_community_settings':
				$settings = array(
					array(
						'name' => __( 'Intra-Community Settings', 'oxygen' ),
						'id'   => 'oxygen_intra_community_settings_header',
						'desc' => __( 'The following settings affect only Intra-Community Invoices.', 'oxygen' ),
						'type' => 'title',
					),
					array(
						'type' => 'sectionend',
						'id'   => 'receipts_settings_end',
					),
					array(
						'name' => __( 'myDATA Intra-Community Tax:', 'oxygen' ),
						'id'   => 'oxygen_intra_community_tax_header',
						'type' => 'title',
					),
					array(
						'title'   => __( 'Select Tax % for Intra-Community Invoices:', 'oxygen' ),
						'id'      => 'oxygen_intra_community_tax_invoices',
						'type'    => 'select',
						'options' => $oxygen_taxes_zero,
					),
					array(
						'type' => 'sectionend',
					),
					array(
						'type' => 'html',
						'html' => '<p style="margin-bottom: 60px;"></p>',
					),
					array(
						'name' => __( 'Invoice of Goods/Intra-Community Shipping Settings:', 'oxygen' ),
						'id'   => 'oxygen_intra_community_goods_header',
						'type' => 'title',
					),
					array(
						'title'   => __( 'myDATA classification Category for Intra-Community Invoice of Goods:', 'oxygen' ),
						'id'      => 'oxygen_mydata_category_tpda_intra',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_categories(),
						'class'   => 'main mydata_category',
					),
					array(
						'title'   => __( 'myDATA classification Type for Intra-Community Invoice of Goods:', 'oxygen' ),
						'id'      => 'oxygen_mydata_classification_type_tpda_intra',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_types_invoices(),
						'class'   => 'mydata_classification_type',
					),
					array(
						'type' => 'sectionend',
					),
					array(
						'type' => 'html',
						'html' => '<p style="margin-bottom: 60px;"></p>',
					),
					array(
						'name' => __(
							'Invoice of Service/Intra-Community Services Settings:',
							'oxygen'
						),
						'id'   => 'oxygen_tpendo_settings_header',
						'type' => 'title',
					),
					array(
						'title'   => __( 'myDATA classification Category for Intra-Community Invoice of Service:', 'oxygen' ),
						'id'      => 'oxygen_mydata_category_tpy_intra',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_categories( 'category1_3' ),
						'class'   => 'main mydata_category',

					),
					array(
						'title'   => __( 'myDATA classification Type for Intra-Community Invoice of Service:', 'oxygen' ),
						'id'      => 'oxygen_mydata_classification_type_tpy_intra',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::mydata_classification_types_invoices(),
						'class'   => 'mydata_classification_type',

					),
					array(
						'type' => 'sectionend',
					),
				);

				break;
			case 'taxes_and_series_settings':
				$settings = array(
					array(
						'title' => __( 'Taxes & Series Settings', 'oxygen' ),
						'type'  => 'title',
						'desc'  => __( 'The following settings are relevant to Taxes & Series of documents that are associated with Oxygen Pelatologio application.', 'oxygen' ),
						'id'    => 'oxygen_taxes_and_series_settings_header',
					),
					array(
						'type' => 'sectionend',
						'id'   => 'taxes_and_series_settings_end',
					),
					array(
						'type' => 'html',
						'html' => '<p style="margin-bottom: 60px;"></p>',
					),
					array(
						'name' => __( 'Document Series:', 'oxygen' ),
						'id'   => 'oxygen_num_sequences_header',
						'type' => 'title',
					),
				);

				$oxygen_sequences = OxygenHelperFunctions::oxygen_sequences_options();

				if ( ! empty( $oxygen_sequences ) ) {
					foreach ( $oxygen_document_types as $doc_key => $doc_type ) {
						$settings[] = array(
							'name'    => $oxygen_document_type_names[ $doc_key ],
							'id'      => 'oxygen_num_sequence_' . $doc_key,
							'type'    => 'select',
							'options' => ( isset( $oxygen_sequences[ $doc_type ] ) ? array( '0' => __( 'Select', 'oxygen' ) ) + $oxygen_sequences[ $doc_type ] : array() ),
						);
					}
				}

				$settings[] = array(
					'type' => 'sectionend',
					'id'   => 'taxes_and_series_settings_end',
				);

				$settings[] = array(
					'name' => __( 'Tax Settings:', 'oxygen' ),
					'id'   => 'oxygen_taxes_header',
					'type' => 'title',
				);

				$all_tax_rates              = OxygenHelperFunctions::woo_tax_rates();

				if ( ! empty( $all_tax_rates ) && count( $all_tax_rates ) > 0 ) {
					foreach ( $all_tax_rates as $tax_rate ) {
						$settings[] = array(
							'name'    => $tax_rate->tax_rate_name . ' ' . round( $tax_rate->tax_rate, 2 ),
							'id'      => 'oxygen_taxes[' . $tax_rate->tax_rate_id . ']',
							'type'    => 'select',
							'options' => $oxygen_taxes,
						);
					}
				} else {
					$settings[] = array(
						'name' => '',
						'id'   => 'oxygen_no_taxes_header',
						'type' => 'html',
						'html' => '<p>' . sprintf(
								esc_html(
									'Δεν έχει γίνει καμία ρύθμιση φόρων. <br>Πηγαίνετε εδώ <a target="_blank" href="%s">Woocommerce -> Tax</a> για να ρυθμίσετε τους φόρους του eshop σας.'
								),
								esc_url( admin_url( 'admin.php?page=wc-settings&tab=tax' ) )
							) . '</p>',
					);

					OxygenHelperFunctions::debug( array( 'Δεν έχει γίνει καμία ρύθμιση φόρων στο Woocommerce -> Tax.' ) );
				}

				$settings[] = array(
					'type' => 'sectionend',
					'id'   => 'taxes_and_series_settings_end',
				);

				break;

			case 'general_documents_settings':

				$get_logos                  = OxygenHelperFunctions::get_logos();

				$settings = array(
					array(
						'title' => __( 'Documents Settings', 'oxygen' ),
						'type'  => 'title',
						'id'    => 'oxygen_general_doc_settings_header',
					),
					array(
						'name'    => __( 'Default Document type:', 'oxygen' ),
						'id'      => 'oxygen_default_document_type',
						'type'    => 'select',
						'options' => array(
							'0'       => __( 'Select', 'oxygen' ),
							'invoice' => __( 'Invoice', 'oxygen' ) . '/' . __( 'Receipt', 'oxygen' ) . '/' . __( 'Intra-Community', 'oxygen' ),
							'notice'  => __( 'Notice', 'oxygen' ),
						),
					),
					array(
						'name'    => __( 'Default Invoice Type:', 'oxygen' ),
						'id'      => 'oxygen_default_invoice_type',
						'type'    => 'select',
						'options' => array(
							'0'    => __( 'Select', 'oxygen' ),
							'tpy'  => __( 'Invoice of Service', 'oxygen' ),
							'tpda' => __( 'Invoice of Goods/Shipping', 'oxygen' ),
						),
					),
					array(
						'name'    => __( 'Default Receipt Type:', 'oxygen' ),
						'id'      => 'oxygen_default_receipt_type',
						'type'    => 'select',
						'options' => array(
							'0'   => __( 'Select', 'oxygen' ),
							'apy' => __( 'Receipt of Service', 'oxygen' ),
							'alp' => __( 'Receipt of Goods', 'oxygen' ),
						),
					),
					array(
						'name'    => __( 'Default Intra-Community Invoice Type:', 'oxygen' ),
						'id'      => 'oxygen_default_intra_type',
						'type'    => 'select',
						'options' => array(
							'0'          => __( 'Select', 'oxygen' ),
							'tpda_intra' => __( 'Invoice of Goods/Intra-Community Shipping', 'oxygen' ),
							'tpy_intra'  => __( 'Invoice of Service/Intra-Community Service', 'oxygen' ),
						),
					),
					array(
						'name'    => __( 'Document Logo:', 'oxygen' ),
						'id'      => 'oxygen_logo',
						'type'    => 'select',
						'options' => array_merge(
							array( 0 => __( 'Select', 'oxygen' ) ),
							is_array( $get_logos ) ? $get_logos : array()
						),
						'default' => $default_logo_id,
					),
					array(
						'name'    => __( 'Document Language:', 'oxygen' ),
						'id'      => 'oxygen_language',
						'type'    => 'select',
						'options' => array(
							'EL'         => __( 'Greek', 'oxygen' ),
							'EN'         => __( 'English', 'oxygen' ),
							'order_lang' => __( 'Same as order language', 'oxygen' ),
						),
					),
					array(
						'name' => __( 'Shipping Code:', 'oxygen' ),
						'id'   => 'oxygen_shipping_code',
						'type' => 'text',
						'desc' => __( 'Only latin characters and numbers allowed. Do not use spaces and/or special characters.', 'oxygen' ),
					),
                    array(
                            'name'    => __( 'myDATA classification Type for Shipping:', 'oxygen' ),
                            'id'      => 'oxygen_mydata_classification_type_shipping',
                            'type'    => 'select',
                            'options' => array(
                                    'E3_562' => 'E3_562',
                                    'E3_561_007' => 'E3_561_007',
                                    'E3_563' => 'E3_563',
                                    'E3_570' => 'E3_570'
                            ),
                            'desc' => sprintf(
                                    __( 'Check the accepted transport designations, listed in the file of Combinations of designations (xls), on the official website of %s.', 'oxygen' ),
                                    '<a href="https://aade.gr/mydata/tehnikes-prodiagrafes-ekdoseis-mydata/" target="_blank" title="ΑΑΔΕ">ΑΑΔΕ</a>'
                            ),
                    ),
					array(
						'name'   => __( 'Email document to customer', 'oxygen' ),
						'id'     => 'oxygen_order_attachment',
						'type'   => 'toggle',
						'toggle' => '',
						'desc'   => __( 'Send the document to your customer via email once it’s created.', 'oxygen' ),
					),
					array(
						'type' => 'sectionend',
						'id'   => 'general_documents_settings_end',
					),
					array(
						'title' => __( 'User Settings:', 'oxygen' ),
						'type'  => 'title',
						'id'    => 'oxygen_users_header',
					),
					array(
						'name'     => __( 'Show documents in User Account:', 'oxygen' ),
						'desc_tip' => __( 'Check this box if you want the documents to be visible in your customers’ User Accounts.', 'oxygen' ),
						'id'       => 'oxygen_users_view_settings',
						'type'     => 'toggle',
						'toggle'   => '',
					),
				);

				$settings[] = array(
					'type' => 'sectionend',
				);

				break;

			case 'shipping_data_settings' :

				$settings = array(
					array(
						'title' => __( 'Settings Shipping Data', 'oxygen' ),
						'id'    => 'oxygen_shipping_settings_header',
						'type'  => 'title',
					),
					array(
						'type' => 'sectionend',
					),
					array(
						'title' => __( 'Transfer Data', 'oxygen' ),
						'id'    => 'oxygen_tranfer_header',
						'type'  => 'title',
					),
					array(
						'name'     => __( 'Move purpose', 'oxygen' ),
						'id'       => 'oxygen_move_purpose',
						'type'    => 'select',
						'options' => OxygenHelperFunctions::move_purposes(),
					),
					array(
						'name' => __( 'Other move purpose title', 'oxygen' ),
						'id'   => 'oxygen_other_move_purpose_title',
						'type' => 'text',
					),
					array(
						'name' => __( 'Vehicle number', 'oxygen' ),
						'id'   => 'oxygen_vehicle_number',
						'type' => 'text',
					),
					array(
						'name' => __( 'Comments', 'oxygen' ),
						'id'   => 'oxygen_shipping_comments',
						'type' => 'textarea',
					),
					array(
						'type' => 'sectionend',
					),
					array(
						'title' => __( 'Pick up details', 'oxygen' ),
						'id'    => 'oxygen_pickup_header',
						'type'  => 'title',
					),
					array(
						'name' => __('Pick up branch code', 'oxygen'),
						'id'    => 'oxygen_pickup_branch_code',
						'type' => 'number',
					),
					array(
						'name' => __('Pick up street', 'oxygen'),
						'id'    => 'oxygen_pickup_street',
						'type' => 'text',
					),
					array(
						'name' => __('Pick up address number', 'oxygen'),
						'id'    => 'oxygen_pickup_address_number',
						'type' => 'text',
					),
					array(
						'name' => __('Pick up postal_code', 'oxygen'),
						'id'    => 'oxygen_pickup_postal_code',
						'type' => 'text',
					),
					array(
						'name' => __('Pick up city', 'oxygen'),
						'id'    => 'oxygen_pickup_city',
						'type' => 'text',
					),
					array(
						'name' => __('Pick up country', 'oxygen'),
						'id'    => 'oxygen_pickup_country',
						'type' => 'select',
						'options' => OxygenHelperFunctions::countries(),
					),
					array(
						'name' => __('Transmit the above shipping data during automatic creation of document', 'oxygen'),
						'id'    => 'oxygen_autocreate_default_shipping_data',
						'desc' => __( 'By choosing to transmit the above information, documents will be automatically issued with the specified shipping details.', 'oxygen' ),
						'type'     => 'toggle',
						'toggle'   => '',
					),
				);
				$settings[] = array(
					'type' => 'sectionend',
				);
				break;

			case 'order_and_products_settings':

				$measurements_oxygen = OxygenHelperFunctions::oxygen_measurement_units();

				$settings = array(
					array(
						'title' => __( 'Orders & Products Settings', 'oxygen' ),
						'id'    => 'oxygen_orders_and_products_settings_header',
						'type'  => 'title',
					),
					array(
						'name'    => __( 'Default Order Status:', 'oxygen' ),
						'id'      => 'oxygen_order_status',
						'type'    => 'select',
						'options' => array( '0' => __( 'Do not create automatically', 'oxygen' ) ) + wc_get_order_statuses(),
						'desc'    => __( 'The status in which we should create the Invoice/Receipt.', 'oxygen' ),
					),
					array(
						'name'   => __( 'Use Parent’s SKU for product variations:', 'oxygen' ),
						'desc'   => __( 'Enabling this option will allow variant products to use their parent’s SKU to create receipts/invoices in Oxygen Pelatologio app.', 'oxygen' ),
						'id'     => 'oxygen_products_variations',
						'type'   => 'toggle',
						'toggle' => '',
					),
					array(
						'id'          => 'oxygen_measurement_unit_default',
						'name'       => __( 'Measurement Unit', 'oxygen' ),
						'desc' => __( 'Select default measurement unit to applied for products with empty measurement unit.', 'oxygen' ),
						'type'    => 'select',
						'options'     => $measurements_oxygen ,
					),
					array(
						'type' => 'sectionend',
						'id'   => 'order_and_products_settings_end',
					),

				);


				/* an ta oxygen payments einai enabled tote emfanise ta parakatw settings */
				if ( ! empty( $available_payment_methods ) && ! empty( $available_payment_methods['oxygen_payment'] ) && 'yes' === $available_payment_methods['oxygen_payment']->enabled ) {

					$settings[] = array(
						'title' => __( 'Oxygen Payments - Order Status:', 'oxygen' ),
						'id'    => 'oxygen_payment_order_status_header',
						'type'  => 'title',
					);

					/* Κατάσταση παραγγελίας μετά την επιτυχημένη πληρωμή μέσω Oxygen Payments --- default -> σε επεξεργασία */

					$settings[] = array(
						'name'    => __( 'Order Status after Oxygen Payment:', 'oxygen' ),
						'id'      => 'oxygen_payment_order_status',
						'type'    => 'select',
						'options' => wc_get_order_statuses(),
						'default' => 'wc-processing',
						'desc'    => __( 'The default status of an order after it has been successfully paid via Oxygen Payments.', 'oxygen' ),
					);
				}

				$settings[] = array(
					'type' => 'sectionend',
					'id'   => 'order_and_products_settings_end',
				);

				break;

			case 'payments_settings':
				$settings = array(
					array(
						'title' => __( 'Payments Settings', 'oxygen' ),
						'id'    => 'oxygen_payments_settings_header',
						'type'  => 'title',
						'desc'  => __( 'Settings for the available payment methods between the Oxygen Pelatologio application and WooCommerce.', 'oxygen' ),
					),
					array(
						'type' => 'sectionend',
						'id'   => 'payments_settings_end',
					),
					array(
						'type' => 'html',
						'html' => '<p style="margin-bottom: 60px;"></p>',
					),
					array(
						'title' => __( 'Payment Methods:', 'oxygen' ),
						'id'    => 'oxygen_payment_methods_header',
						'type'  => 'title',
						'desc'  => __( 'Select the default Payment Method that will appear on Documents for each Payment Method on WooCommerce.', 'oxygen' ),
					),
				);

				$oxygen_payments = OxygenHelperFunctions::oxygen_payment_methods();

				if ( ! empty( $available_payment_methods ) ) {

					foreach ( $available_payment_methods as $key => $payment_method ) {

						if ( 'yes' === $payment_method->enabled ) {

							$settings[] = array(
								'name'    => $payment_method->get_title(),
								'id'      => 'oxygen_payment_methods[' . $key . ']',
								'type'    => 'select',
								'options' => $oxygen_payments,
								'class'   => 'ox_payments_method',
							);

						}
					}
					$settings[] = array(
						'name'    => __( 'Default Payment Method:', 'oxygen' ),
						'id'      => 'oxygen_payment_default',
						'type'    => 'select',
						'options' => $oxygen_payments,
					);

					$settings[] = array(
						'type' => 'sectionend',
						'id'   => 'payments_settings_end',
					);

					$settings[] = array(
						'title' => __( 'Document Payment Status:', 'oxygen' ),
						'type'  => 'title',
						'desc'  => __( 'Select the default Payment Status (paid/not paid) for Documents for each Payment Method.', 'oxygen' ),
						'id'    => 'oxygen_payment_doc_status_header',
					);


					foreach ( $available_payment_methods as $key => $payment_method ) {

						if ( 'yes' === $payment_method->enabled ) {

							$settings[] = array(
								'name'    => $payment_method->get_title(),
								'id'      => 'oxygen_is_paid[' . $key . ']',
								'type'    => 'select',
								'options' => array(
									'yes' => __( 'Paid', 'oxygen' ),
									'no'  => __( 'Unpaid', 'oxygen' ),
								),
								'class'   => 'ox_document_payment_status',
							);

						}
					}
				}

				$settings[] = array(
					'type' => 'sectionend',
					'id'   => 'payments_settings_end',
				);

				break;

			default:
				/* download manual */
				$lang_pdf_manual = 'WooCommerce_plugin_v2.pdf';

				/* button for export plugins settings in json */
				$download_url = add_query_arg( 'download_oxygen_settings', 'true', admin_url( 'admin.php?page=wc-settings&tab=oxygen_tab' ) );
				/* button to download oxygen latest log file from wc-logs */
				$most_recent_file = OxygenHelperFunctions::find_most_recent_oxygen_log();

				$settings = array(
					array(
						'title' => __( 'General Settings', 'oxygen' ),
						'type'  => 'title',
						'desc'  => __( 'General settings for Oxygen MyData Plugin.', 'oxygen' ) . '(Oxygen myDATA)',
						'id'    => 'oxygen_general_settings',
					),
					array(
						'title' => __( 'Οδηγίες χρήσης:', 'oxygen' ),
						'type'  => 'title',
						'desc'  => '<span style="font-size: 12px;">' .
						           '<a href="' . esc_url( plugin_dir_url( __FILE__ ) . '../assets/' . $lang_pdf_manual ) .
						           '" target="_blank" download>' .
						           esc_html__( 'Oxygen MyData Plugin Manual', 'oxygen' ) .
						           '</a></span>',
						'id'    => 'download_pdf' . get_user_locale(),
					),
					array(
						'title'   => esc_html__( 'Oxygen API Key:', 'oxygen' ),
						'desc'    => __( 'API key provided by <a href="https://www.pelatologio.gr/" target="_blank" title="Oxygen Pelatologio">Oxygen Pelatologio</a>', 'oxygen' ),
						'id'      => 'oxygen_api_key',
						'type'    => 'text',
						'default' => '',
					),
					array(
						'title'   => __( 'Environment:', 'oxygen' ),
						'id'      => 'oxygen_status',
						'type'    => 'select',
						'options' => array(
							'live' => __( 'Live', 'oxygen' ),
							'test' => __( 'Sandbox', 'oxygen' ),
						),
						'desc'    => ( 'test' === get_option( 'oxygen_status' ) )
							? __( '<span class="alert info">You are in Sandbox Mode.</span>', 'oxygen' )
							: ( 'live' === get_option( 'oxygen_status' )
								? __( '<span class="alert success">You are in Live mode.</span>', 'oxygen' )
								: ''
							),
					),

					/*
					Document type i
					document type i ( xwris stoixeia diakinisis ) - v2+
						array(
							'id'       => 'oxygen_enable_simple_invoice',
							'name'    => __( 'I want simple invoice without traffic data', 'oxygen' ),
							'type'     => 'toggle',
							'title'    => __( 'I want simple invoice without traffic data', 'oxygen' ),
							'toggle'  => '',
							'desc_tip' => __( 'By enabling this option , you will be able to create an invoice without traffic data.', 'oxygen' ),
							'desc'    => ( 'yes' === get_option( 'oxygen_enable_simple_invoice' ) )
										? __('<span class="alert info">Προσοχή! Τα τιμολόγια σας θα εκδίδονται χωρίς στοιχεία διακίνησης.</span>', 'oxygen')
										: '',
						),
					*/
					array(
						'id'     => 'oxygen_only_receipts',
						'name'   => __( 'Receipts Only:', 'oxygen' ),
						'type'   => 'toggle',
						'title'  => __( 'Receipts Only:', 'oxygen' ),
						'toggle' => '',
						'desc'   => __( 'Enabling this option allows you to automatically create only Receipts from WooCommerce.', 'oxygen' ),
					),
					array(
						'id'     => 'oxygen_enable_shipping_data',
						'name'   => __( 'Use Shipping Data:', 'oxygen' ),
						'type'   => 'toggle',
						'title'  => __( 'Use Shipping Data:', 'oxygen' ),
						'toggle' => '',
						'desc'   => __( 'Enabling this option allows you to add shipping details on documents like Invoice of Goods/Receipts of Goods.', 'oxygen' ),
						'link' => '<span style="font-size: 12px;"><a href="https://www.pelatologio.gr/blog/read.php?id=43&lang=1" target="_blank">' .
						          esc_html__( 'Δείτε εδώ για την υποχρεωτικότητα των στοιχείων διακίνησης', 'oxygen' ) .'</a></span>',
					),
					array(
						'id'     => 'oxygen_enable_intra_community_invoice',
						'name'   => __( 'Intra-Community Invoicing:', 'oxygen' ),
						'type'   => 'toggle',
						'title'  => __( 'Intra-Community Invoicing:', 'oxygen' ),
						'toggle' => '',
						'desc'   => __( 'Enabling this option allows you to create Intra-Community Invoices.', 'oxygen' ),
					),
					array(
						'id'     => 'oxygen_debug',
						'name'   => __( 'Debug Mode', 'oxygen' ),
						'type'   => 'toggle',
						'title'  => __( 'Error Logs for Oxygen WooCommerce Plugin:', 'oxygen' ),
						'toggle' => '',
						'desc'   => __( 'Enabling this option activates the creation of Error Logging for this plugin, helping us understand and fix any issues that may occur.', 'oxygen' ),
					),
					array(
						'type' => 'sectionend',
						'id'   => 'payments_settings_end',
					),
				);

				$settings[] = array(
					'name' => __( 'Download Oxygen Settings', 'oxygen' ),
					'type' => 'title',
					'desc' => '<a href="' . esc_url( $download_url ) . '" class="button button-primary">' . __( 'Download Oxygen Settings', 'oxygen' ) . '</a>',
					'id'   => 'oxygen_settings_export',
				);

				// Check if a file was found.
				if ( $most_recent_file ) {
					// Create the download URL.
					$download_url = add_query_arg( 'file', basename( $most_recent_file ), admin_url( 'admin-ajax.php?action=download_wc_log' ) );

					$settings[] = array(
						'name' => __( 'Download Oxygen Log File', 'oxygen' ),
						'type' => 'title', // Use title to add custom HTML.
						'desc' => '<a href="' . esc_url( $download_url ) . '" class="button button-primary">' . __( 'Download most recent Oxygen Log', 'oxygen' ) . '</a>',
						'id'   => 'oxygen_log_download_button',
					);
				} else {
					$settings[] = array(
						'name' => __( 'Download Oxygen Log File', 'oxygen' ),
						'type' => 'title',
						'desc' => '<p>' . __( 'No Oxygen log file found for today.', 'oxygen' ) . '</p>',
						'id'   => 'oxygen_log_download_button',
					);
				}
				/* button to download oxygen latest log file from wc-logs */
				$settings[] = array(
					'type' => 'sectionend',
					'id'   => 'oxygen_general_settings',
				);
				break;
		}

		if ( empty( get_option( 'oxygen_api_key' ) ) ) {
			/*
				Document type i
				document type i ( xwris stoixeia diakinisis ) - v2+  add key to exclude oxygen_enable_simple_invoice
				$ids_to_remove = array('oxygen_enable_simple_invoice','oxygen_only_receipts','oxygen_enable_intra_community_invoice','oxygen_debug','oxygen_settings_export','oxygen_log_download_button');
			*/
			$ids_to_remove = array( 'oxygen_only_receipts', 'oxygen_enable_intra_community_invoice', 'oxygen_debug', 'oxygen_settings_export', 'oxygen_log_download_button' );
			$settings      = OxygenHelperFunctions::remove_settings_by_ids( $settings, $ids_to_remove );
		}

		/* Only if receipts is checked remove series for invoices type tpy and tpda */
		if ( 'yes' === get_option( 'oxygen_only_receipts' ) ) {
			/*
				Document type i
				document type i ( xwris stoixeia diakinisis ) - v2+  add key to exclude oxygen_enable_simple_invoice
				$ids_to_remove = array('oxygen_num_sequencetpy','oxygen_num_sequencetpda','oxygen_enable_simple_invoice','oxygen_enable_intra_community_invoice');
			*/
			$ids_to_remove = array( 'oxygen_num_sequencetpy', 'oxygen_num_sequencetpda', 'oxygen_enable_intra_community_invoice' );

			$settings = OxygenHelperFunctions::remove_settings_by_ids( $settings, $ids_to_remove );
		}

		return apply_filters( "woocommerce_get_settings_{$this->id}_{$section}", $settings );
	}



	/**
	 * Uses the WooCommerce options API to save settings via the @see woocommerce_update_options() function.
	 *
	 * @uses woocommerce_update_options()
	 * @uses self::get_settings()
	 */
	public static function update_settings() {

		woocommerce_update_options( ( new OxygenWooSettings() )->get_settings() );
	}

	/**
	 *  Output HTML on WooCommerce settings
	 *
	 *  @param array $value WooCommerce settings fields array.
	 *  @return void
	 */
	public static function html_field( $value ) {

		?>
        <tr valign="top">
            <th class="forminp forminp-html" id="<?php echo esc_attr( $value['id'] ); ?>">
                <label><?php echo esc_attr( $value['title'] ); ?>
					<?php echo wp_kses_post( isset( $value['desc_tip'] ) && ! empty( $value['desc_tip'] ) ? wc_help_tip( sanitize_text_field( $value['desc_tip'] ) ) : '' ); ?>
                </label>
            </th>
            <td class="forminp"><?php echo wp_kses_post( $value['html'] ); ?></td>
        </tr>
		<?php
	}

	/**
	 *  Output HTML on WooCommerce settings
	 *
	 *  @param array $value WooCommerce settings fields array.
	 *  @return void
	 */
	public static function toggle_field( $value ) {

		$is_checked = get_option( $value['id'] );

		?>
        <tr valign="top">
            <th><?php echo esc_attr( $value['title'] ); ?></th>
            <td class="forminp forminp-toggle">
                <label class="oxygen toggle <?php echo 'yes' === $is_checked ? 'checked_toggle' : ''; ?>" for="<?php echo esc_attr( $value['id'] ); ?>">
                    <input name="<?php echo esc_attr( $value['id'] ); ?>" id="<?php echo esc_attr( $value['id'] ); ?>" type="checkbox" class="toggle-switch oxygen-toggle" value="<?php echo 'yes' === $is_checked ? 'yes' : 'no'; ?>">
                </label>
                <p class="description_tip "><?php echo esc_html( $value['desc_tip'] ); ?></p>
                <p class="description "><?php echo esc_html( $value['desc'] ); ?></p>
                <p class="link "><?php echo !empty($value['link']) ? $value['link'] : '' ; ?></p>
            </td>
        </tr>
		<?php
	}

	/**
	 * Saves the value of a toggle (checkbox) field to the database.
	 *
	 * Checks if the given option ID is present in the POST data and saves
	 * the value as 'yes' or 'no' accordingly. If the field is not submitted,
	 * it is assumed to be unchecked and saved as 'no'.
	 *
	 * This is typically used for boolean-style WooCommerce admin settings.
	 *
	 * @param array $option {
	 *     The option field definition.
	 *
	 *     @type string $id The unique option key to update.
	 * }
	 *
	 * @return void
	 */
	public static function save_toggle_field( $option ) {

		// Check if the option ID is set.
		if ( isset( $option['id'] ) ) {
			$field_id = $option['id'];
			// If the field is set in $_POST, set it to 'yes'. Otherwise, set it to 'no'.
			$value = get_option( $option['id'] );
			if ( isset( $_POST[ $field_id ] ) ) {
				$value = 'yes' === $_POST[ $field_id ] ? 'yes' : 'no';
			}
			// Update the option with the field value.
			update_option( $field_id, $value );
		}
	}

	/**
	 * Downloads a WooCommerce log file from the logs directory.
	 *
	 * Validates the `file` parameter from the query string, sanitizes the
	 * filename, and serves it as a downloadable file. If the file does not
	 * exist, a WordPress error message is displayed.
	 *
	 * @return void
	 */
	public function download_wc_log() {
		// Check if the file parameter exists.
		if ( isset( $_GET['file'] ) ) {
			$file_name = sanitize_file_name( wp_unslash( $_GET['file'] ) );
			$file_path = WC_LOG_DIR . $file_name;

			// Verify the file exists.
			if ( file_exists( $file_path ) ) {
				header( 'Content-Description: File Transfer' );
				header( 'Content-Type: application/octet-stream' );
				header( 'Content-Disposition: attachment; filename="' . basename( $file_path ) . '"' );
				header( 'Content-Length: ' . filesize( $file_path ) );
				flush(); // Flush system output buffer.
				readfile( $file_path ); // Read the file and output its contents.
				exit;
			} else {
				wp_die( esc_html__( 'Oxygen log file not found.', 'oxygen' ) );
			}
		} else {
			wp_die( esc_html__( 'No oxygen log file specified.', 'oxygen' ) );
		}
	}

	/**
	 * Downloads the current Oxygen plugin settings as a JSON file.
	 *
	 * This function is triggered via the `download_oxygen_settings=true`
	 * query parameter. It checks for sufficient user permissions, retrieves
	 * the plugin settings, and forces the download of a JSON file.
	 *
	 * @return void
	 */
	public static function download_oxygen_settings(): void {

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( isset( $_GET['download_oxygen_settings'] ) && 'true' === $_GET['download_oxygen_settings'] ) {

			$settings = OxygenHelperFunctions::retrieve_oxygen_settings();
			// Set headers to force download.
			header( 'Content-Type: application/json' );
			header( 'Content-Disposition: attachment; filename="oxygen-settings.json"' );
			header( 'Content-Length: ' . strlen( $settings ) );

			// Output the settings and exit.
			echo esc_html( $settings );
			exit;
		}
	}

	/**
	 *  Add new WooCommerce product tab
	 *
	 *  @param array $tabs of WooCommerce tabs.
	 *
	 *  @return array of WooCommerce tabs
	 */
	public static function product_data_tabs( $tabs ) {

		$tabs['oxygen'] = array(
			'label'    => _x( 'Oxygen options', 'Oxygen product settings', 'woocommerce' ),
			'target'   => 'oxygen_settings',
			'class'    => array(),
			'priority' => 990,
		);

		return $tabs;
	}


	/**
	 *  Edit WooCommerce product categories fields
	 *
	 *  @param object $term the term object.
	 *  @param object $taxonomy the taxonomy object.
	 *  @return void
	 */
	public static function edit_term_fields( $term, $taxonomy ) {
		// Dynamically build the fields array.
		$fields = array(
			'oxygen_mydata_cat_tpda_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Category for Invoice of Goods/Shipping', 'oxygen' ),
				'description' => __( 'This will override the classification Category value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_categories(),
				'class'       => 'mydata_category cat_taxonomy',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_cat_tpda_product_panel_cat_taxonomy', true ),
			),
			'oxygen_mydata_clas_type_tpda_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Type for Invoice of Goods/Shipping', 'oxygen' ),
				'description' => __( 'This will override the classification Type value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_types_invoices(),
				'class'       => 'mydata_type',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_clas_type_tpda_product_panel_cat_taxonomy', true ),
			),
			'oxygen_mydata_cat_tpy_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Category for Invoice of Service', 'oxygen' ),
				'description' => __( 'This will override the classification Category value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_categories( 'category1_3' ),
				'class'       => 'mydata_category cat_taxonomy',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_cat_tpy_product_panel_cat_taxonomy', true ),
			),
			'oxygen_mydata_clas_type_tpy_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Type for Invoice of Service', 'oxygen' ),
				'description' => __( 'This will override the classification Type value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_types_invoices(),
				'class'       => 'mydata_type',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_clas_type_tpy_product_panel_cat_taxonomy', true ),
			),
			'oxygen_mydata_cat_alp_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Category for Receipt of Goods', 'oxygen' ),
				'description' => __( 'This will override the classification Category value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_categories(),
				'class'       => 'mydata_category cat_taxonomy',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_cat_alp_product_panel_cat_taxonomy', true ),
			),
			'oxygen_mydata_clas_type_alp_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Type for Receipt of Goods', 'oxygen' ),
				'description' => __( 'This will override the classification Type value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_types_receipts(),
				'class'       => 'mydata_type',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_clas_type_alp_product_panel_cat_taxonomy', true ),
			),
			'oxygen_mydata_cat_apy_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Category for Receipt of Service', 'oxygen' ),
				'description' => __( 'This will override the classification Category value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_categories( 'category1_3' ),
				'class'       => 'mydata_category cat_taxonomy',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_cat_apy_product_panel_cat_taxonomy', true ),
			),
			'oxygen_mydata_clas_type_apy_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Type for Receipt of Service', 'oxygen' ),
				'description' => __( 'This will override the classification Type value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_types_receipts(),
				'class'       => 'mydata_type',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_clas_type_apy_product_panel_cat_taxonomy', true ),
			),
			'oxygen_mydata_cat_tpda_intra_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Category for Invoice of Goods/Intra-Community Shipping', 'oxygen' ),
				'description' => __( 'This will override the classification Category value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_categories(),
				'class'       => 'mydata_category cat_taxonomy',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_cat_tpda_intra_product_panel_cat_taxonomy', true ),
			),
			'oxygen_mydata_clas_type_tpda_intra_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Type for Invoice of Goods/Intra-Community Shipping', 'oxygen' ),
				'description' => __( 'This will override the classification Type value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_types_invoices(),
				'class'       => 'mydata_type',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_clas_type_tpda_intra_product_panel_cat_taxonomy', true ),
			),
			'oxygen_mydata_cat_tpy_intra_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Category for Invoice of Service/Intra-Community Services', 'oxygen' ),
				'description' => __( 'This will override the classification Category value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_categories( 'category1_3' ),
				'class'       => 'mydata_category cat_taxonomy',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_cat_tpy_intra_product_panel_cat_taxonomy', true ),
			),
			'oxygen_mydata_clas_type_tpy_intra_product_panel_cat_taxonomy' => array(
				'label'       => __( 'Product classification Type for Invoice of Service/Intra-Community Services', 'oxygen' ),
				'description' => __( 'This will override the classification Type value', 'oxygen' ),
				'options'     => OxygenHelperFunctions::mydata_classification_types_invoices(),
				'class'       => 'mydata_type',
				'value'       => get_term_meta( $term->term_id, 'oxygen_mydata_clas_type_tpy_intra_product_panel_cat_taxonomy', true ),
			),
		);

		if ( 'no' === get_option( 'oxygen_enable_intra_community_invoice' ) ) {
			$ids_to_remove = array(
				'oxygen_mydata_cat_tpda_intra_product_panel_cat_taxonomy',
				'oxygen_mydata_clas_type_tpda_intra_product_panel_cat_taxonomy',
				'oxygen_mydata_clas_type_tpy_intra_product_panel_cat_taxonomy',
				'oxygen_mydata_cat_tpy_intra_product_panel_cat_taxonomy',
			);
			foreach ( $ids_to_remove as $id ) {
				if ( isset( $fields[ $id ] ) ) {
					unset( $fields[ $id ] );
				}
			}
		}

		if ( 'yes' === get_option( 'oxygen_only_receipts' ) ) {
			$ids_to_remove = array(
				'oxygen_mydata_cat_tpda_intra_product_panel_cat_taxonomy',
				'oxygen_mydata_clas_type_tpda_intra_product_panel_cat_taxonomy',
				'oxygen_mydata_clas_type_tpy_intra_product_panel_cat_taxonomy',
				'oxygen_mydata_cat_tpy_intra_product_panel_cat_taxonomy',
				'oxygen_mydata_cat_tpda_product_panel_cat_taxonomy',
				'oxygen_mydata_clas_type_tpda_product_panel_cat_taxonomy',
				'oxygen_mydata_cat_tpy_product_panel_cat_taxonomy',
				'oxygen_mydata_clas_type_tpy_product_panel_cat_taxonomy',
			);
			foreach ( $ids_to_remove as $id ) {
				if ( isset( $fields[ $id ] ) ) {
					unset( $fields[ $id ] );
				}
			}
		}

		// Render fields dynamically.
		foreach ( $fields as $field_id => $field ) {
			if ( ! empty( $field_id ) && isset( $_POST[ $field_id ] ) ) {
				update_term_meta(
					$term->term_id,
					$field_id,
					sanitize_text_field( wp_unslash( $_POST[ $field_id ] ) )
				);
			}
			?>
            <tr class="form-field">
                <th>
                    <label for="<?php echo esc_attr( $field_id ); ?>">
						<?php echo esc_html( $field['label'] ); ?>
                    </label>
                </th>
                <td>
                    <select name="<?php echo esc_attr( $field_id ); ?>" id="<?php echo esc_attr( $field_id ); ?>" class="<?php echo esc_attr( $field['class'] ); ?>">
						<?php foreach ( $field['options'] as $key => $label ) { ?>
                            <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $field['value'], $key ); ?>>
								<?php echo esc_html( $label ); ?>
                            </option>
						<?php } ?>
                    </select>
					<?php if ( ! empty( $field['description'] ) ) { ?>
                        <p class="description"><?php echo esc_html( $field['description'] ); ?></p>
					<?php } ?>
                </td>
            </tr>
			<?php
		}

		// Add nonce for security.
		wp_nonce_field( 'oxygen_term_nonce', 'oxygen_nonce' );
	}


	/**
	 *  Save new WooCommerce product categories fields
	 *
	 *  @param int $term_id the term id of the fields that is being saved.
	 *
	 *  @return void|int
	 */
	public static function save_term_fields( $term_id ) {

		if ( ! current_user_can( 'edit_term', $term_id ) ) {
			return $term_id;
		}

		if ( ! isset( $_POST['oxygen_nonce'] ) ) {
			return $term_id;
		}

		// Security nonce check.
		$nonce = sanitize_key( wp_unslash( $_POST['oxygen_nonce'] ) );
		if ( empty( sanitize_key( $nonce ) ) || ! wp_verify_nonce( $nonce, 'oxygen_term_nonce' ) ) {
			return $term_id;
		}

		$ids = array(
			'oxygen_mydata_cat_tpda_product_panel_cat_taxonomy',
			'oxygen_mydata_clas_type_tpda_product_panel_cat_taxonomy',
			'oxygen_mydata_cat_tpy_product_panel_cat_taxonomy',
			'oxygen_mydata_clas_type_tpy_product_panel_cat_taxonomy',
			'oxygen_mydata_cat_alp_product_panel_cat_taxonomy',
			'oxygen_mydata_clas_type_alp_product_panel_cat_taxonomy',
			'oxygen_mydata_cat_apy_product_panel_cat_taxonomy',
			'oxygen_mydata_clas_type_apy_product_panel_cat_taxonomy',
			'oxygen_mydata_cat_tpda_intra_product_panel_cat_taxonomy',
			'oxygen_mydata_clas_type_tpda_intra_product_panel_cat_taxonomy',
			'oxygen_mydata_cat_tpy_intra_product_panel_cat_taxonomy',
			'oxygen_mydata_clas_type_tpy_intra_product_panel_cat_taxonomy',
		);

		foreach ( $ids as $id ) {
			if ( isset( $_POST[ $id ] ) ) {
				if ( '0' === $_POST[ $id ] ) {
					delete_term_meta( $term_id, $id );
				} else {
					update_term_meta( $term_id, $id, sanitize_text_field( wp_unslash( $_POST[ $id ] ) ) );
				}
			}
		}
	}



	/**
	 *  Add new WooCommerce product tab content
	 *
	 *  @return void
	 */
	public static function product_data_panels() {

		global $post;

		// Ensure $post is available.
		if ( ! isset( $post ) || ! is_a( $post, 'WP_Post' ) ) {
			return;
		}

		?>
        <div id="oxygen_settings" class="panel woocommerce_options_panel hidden">
            <div class="options_group">
				<?php
				// Define fields in an array for reusability and cleaner code.
				$fields = array(
					'oxygen_mydata_cat_tpda_product_panel' => array(
						'label'       => __( 'Product classification Category for Invoice of Goods/Shipping', 'oxygen' ),
						'description' => __( 'This will override the classification Category value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_categories(),
						'class'       => 'mydata_category',
						'default'     => '0',
					),
					'oxygen_mydata_clas_type_tpda_product_panel' => array(
						'label'       => __( 'Product classification Type for Invoice of Goods/Shipping', 'oxygen' ),
						'description' => __( 'This will override the classification Type value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_types_invoices(),
						'class'       => 'mydata_classification_type',
					),
					'oxygen_mydata_cat_tpy_product_panel'  => array(
						'label'       => __( 'Product classification Category for Invoice of Service', 'oxygen' ),
						'description' => __( 'This will override the classification Category value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_categories( 'category1_3' ),
						'class'       => 'mydata_category',
					),
					'oxygen_mydata_clas_type_tpy_product_panel' => array(
						'label'       => __( 'Product classification Type for Invoice of Service', 'oxygen' ),
						'description' => __( 'This will override the classification Type value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_types_invoices(),
						'class'       => 'mydata_classification_type',
					),
					'oxygen_mydata_cat_alp_product_panel'  => array(
						'label'       => __( 'Product classification Category for Receipt of Goods', 'oxygen' ),
						'description' => __( 'This will override the classification Category value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_categories(),
						'class'       => 'mydata_category',
					),
					'oxygen_mydata_clas_type_alp_product_panel' => array(
						'label'       => __( 'Product classification Type for Receipt of Goods', 'oxygen' ),
						'description' => __( 'This will override the classification Type value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_types_receipts(),
						'class'       => 'mydata_classification_type',
					),
					'oxygen_mydata_cat_apy_product_panel'  => array(
						'label'       => __( 'Product classification Category for Receipt of Service', 'oxygen' ),
						'description' => __( 'This will override the classification Category value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_categories( 'category1_3' ),
						'class'       => 'mydata_category',
					),
					'oxygen_mydata_clas_type_apy_product_panel' => array(
						'label'       => __( 'Product classification Type for Receipt of Service', 'oxygen' ),
						'description' => __( 'This will override the classification Type value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_types_receipts(),
						'class'       => 'mydata_classification_type',
					),
					'oxygen_mydata_cat_tpda_intra_product_panel' => array(
						'label'       => __( 'Product classification Category for Invoice of Goods/Intra-Community Shipping', 'oxygen' ),
						'description' => __( 'This will override the classification Category value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_categories(),
						'class'       => 'mydata_category',
					),
					'oxygen_mydata_clas_type_tpda_intra_product_panel' => array(
						'label'       => __( 'Product classification Type for Invoice of Goods/Intra-Community Shipping', 'oxygen' ),
						'description' => __( 'This will override the classification Type value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_types_invoices(),
						'class'       => 'mydata_classification_type',
					),
					'oxygen_mydata_cat_tpy_intra_product_panel' => array(
						'label'       => __( 'Product classification Category for Invoice of Service/Intra-Community Services', 'oxygen' ),
						'description' => __( 'This will override the classification Category value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_categories( 'category1_3' ),
						'class'       => 'mydata_category',
					),
					'oxygen_mydata_clas_type_tpy_intra_product_panel' => array(
						'label'       => __( 'Product classification Type for Invoice of Service/Intra-Community Services', 'oxygen' ),
						'description' => __( 'This will override the classification Type value', 'oxygen' ),
						'options'     => OxygenHelperFunctions::mydata_classification_types_invoices(),
						'class'       => 'mydata_classification_type',
					),
				);

				if ( 'no' === get_option( 'oxygen_enable_intra_community_invoice' ) ) {
					$ids_to_remove = array(
						'oxygen_mydata_cat_tpda_intra_product_panel',
						'oxygen_mydata_clas_type_tpda_intra_product_panel',
						'oxygen_mydata_cat_tpy_intra_product_panel',
						'oxygen_mydata_clas_type_tpy_intra_product_panel',
					);
					foreach ( $ids_to_remove as $id ) {
						if ( isset( $fields[ $id ] ) ) {
							unset( $fields[ $id ] );
						}
					}
				}

				if ( 'yes' === get_option( 'oxygen_only_receipts' ) ) {
					$ids_to_remove = array(
						'oxygen_mydata_cat_tpda_intra_product_panel',
						'oxygen_mydata_clas_type_tpda_intra_product_panel',
						'oxygen_mydata_cat_tpy_intra_product_panel',
						'oxygen_mydata_clas_type_tpy_intra_product_panel',
						'oxygen_mydata_cat_tpda_product_panel',
						'oxygen_mydata_clas_type_tpda_product_panel',
						'oxygen_mydata_cat_tpy_product_panel',
						'oxygen_mydata_clas_type_tpy_product_panel',
					);
					foreach ( $ids_to_remove as $id ) {
						if ( isset( $fields[ $id ] ) ) {
							unset( $fields[ $id ] );
						}
					}
				}

				// Loop through fields and render them.
				foreach ( $fields as $field_id => $field_data ) {
					woocommerce_wp_select(
						array(
							'id'          => $field_id,
							'value'       => get_post_meta( $post->ID, $field_id, true ),
							'label'       => $field_data['label'],
							'desc_tip'    => true,
							'description' => $field_data['description'],
							'options'     => $field_data['options'],
							'class'       => $field_data['class'],
						)
					);
				}
				?>
            </div>
        </div>
		<?php
	}

	/**
	 *  Save WooCommerce product custom fields
	 *
	 *  @param int $product_id the ID of the product.
	 *  @return void
	 */
	public static function product_save( $product_id ) {

		if ( ! is_admin() ) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! isset( $_POST['_wpnonce'] ) ) {
			return;
		}

		// Security nonce check.
		$nonce = sanitize_key( wp_unslash( $_POST['_wpnonce'] ) );
		if ( empty( sanitize_key( $nonce ) ) || ! wp_verify_nonce( $nonce, "update-post_$product_id" ) ) {
			return;
		}

		$ids = array(
			'oxygen_mydata_cat_tpda_product_panel',
			'oxygen_mydata_clas_type_tpda_product_panel',
			'oxygen_mydata_cat_tpy_product_panel',
			'oxygen_mydata_clas_type_tpy_product_panel',
			'oxygen_mydata_cat_alp_product_panel',
			'oxygen_mydata_clas_type_alp_product_panel',
			'oxygen_mydata_cat_apy_product_panel',
			'oxygen_mydata_clas_type_apy_product_panel',
			'oxygen_mydata_cat_tpda_intra_product_panel',
			'oxygen_mydata_clas_type_tpda_intra_product_panel',
			'oxygen_mydata_cat_tpy_intra_product_panel',
			'oxygen_mydata_clas_type_tpy_intra_product_panel',
			'oxygen_wc_measurement_unit'
		);

		foreach ( $ids as $id ) {
			if ( isset( $_POST[ $id ] ) ) {
				if ( '0' === $_POST[ $id ] ) {
					delete_post_meta( $product_id, $id );
				} else {
					update_post_meta( $product_id, $id, sanitize_text_field( wp_unslash( $_POST[ $id ] ) ) );
				}
			}
		}
	}

	public static function add_measurement_unit_option() {

		$measurements_oxygen = OxygenHelperFunctions::oxygen_measurement_units();

		echo '<div class="wc_measurement_unit">';

		woocommerce_wp_select(
			array(
				'id'          => 'oxygen_wc_measurement_unit',
				'label'       => __( 'Measurement Unit', 'oxygen' ),
				'placeholder' => '',
				'desc_tip'    => 'true',
				'description' => __( 'Select your measurement unit for this product', 'oxygen' ),
				'options'     => $measurements_oxygen ,
			)
		);
		echo '</div>';
	}

}

