<?php // phpcs:ignore WordPress.Files.FileName

if ( ! defined( 'YITH_COG_PATH' ) ) {
	exit( 'Direct access forbidden.' );
}

/**
 * Class YITH_COG_Admin
 *
 * @class      YITH_COG_Admin
 * @package    YITH
 * @since      Version 1.0.0
 * @author     Francisco Mendoza
 */

if ( ! class_exists( 'YITH_COG_Admin' ) ) {

	/**
	 * Class YITH_COG_Admin
	 *
	 * @author
	 */
	class YITH_COG_Admin {

		/**
		 * Main Instance
		 *
		 * @var YITH_COG_Admin
		 * @since 1.0
		 */
		protected static $instance = null;

		/**
		 * Options.
		 *
		 * @var string
		 */
		public $options = null;

		/**
		 * Panel
		 *
		 * @var string
		 */
		protected $panel = null;

		/**
		 * Panel page.
		 *
		 * @var string
		 */
		protected $panel_page = 'yith_cog_setting';

		/**
		 * Main panel option.
		 *
		 * @var string
		 */
		protected $main_panel_option;

		/**
		 * Main panel screen options.
		 *
		 * @var array
		 */
		protected $screen_options = array();

		/**
		 * Main panel screen columns.
		 *
		 * @var array
		 */
		protected $screen_columns = array();

		/**
		 * Construct
		 *
		 * @author
		 * @since 1.0
		 */
		public function __construct() {

			/* === Show Plugin Information === */
			add_filter( 'plugin_action_links_' . plugin_basename( YITH_COG_PATH . '/' . basename( YITH_COG_FILE ) ), array( $this, 'action_links' ) );
			add_filter( 'yith_show_plugin_row_meta', array( $this, 'plugin_row_meta' ), 10, 5 );

			/* ====== ENQUEUE STYLES AND JS ====== */
			add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
			/* === Register Panel Settings === */
			add_action( 'admin_menu', array( $this, 'add_users_settings_page' ), 5 );

			/* Register plugin to licence/update system */
			add_action( 'wp_loaded', array( $this, 'register_plugin_for_activation' ), 99 );
			add_action( 'wp_loaded', array( $this, 'register_plugin_for_updates' ), 99 );

			// Integration with YITH Name your Price.
			if ( function_exists( 'yith_name_your_price_premium_init' ) ) {
				add_action( 'ywcnp_after_admin_tab_single_product_metabox', array( $this, 'add_cost_field_to_simple_product_name_your_price' ) );
			} else {
				// General Product Field
				// add cost field to simple products under the 'General' tab.
				add_action( 'woocommerce_product_options_pricing', array( $this, 'add_cost_field_to_simple_product' ) );

				// add cost field to YITH Bundle products under the 'Bundle options' tab
				if ( function_exists( 'yith_wcpb_pr_init' ) ) {
					add_action( 'yith_wcpb_after_product_bundle_options_tab', array( $this, 'add_cost_field_to_bundle_products' ) );
				}
				// add cost field to variable products under the 'General' tab.
				add_action( 'woocommerce_product_options_sku', array( $this, 'add_cost_field_to_variable_product' ) );
			}

			// save the cost field for simple products.
			add_action( 'woocommerce_process_product_meta', array( $this, 'save_simple_product_cost' ), 10, 2 );
			// add cost field to variable products under the 'Variations' tab after the shipping class select.
			add_action( 'woocommerce_product_after_variable_attributes', array( $this, 'add_cost_field_to_product_variation' ), 15, 3 );
			// save the cost field for variable products.
			add_action( 'woocommerce_save_product_variation', array( $this, 'save_variation_product_cost' ) );
			// save the default cost, cost/min/max costs for variable products.
			add_action( 'woocommerce_process_product_meta_variable', array( $this, 'save_variable_product_cost' ), 15 );
			add_action( 'woocommerce_ajax_save_product_variations', array( $this, 'save_variable_product_cost' ), 15 );

			// Bulk Actions
			// adds the product variation 'Cost' bulk edit action.
			add_action( 'woocommerce_variable_product_bulk_edit_actions', array( $this, 'add_variable_product_bulk_edit_cost_action' ) );
			// save variation cost for bulk edit action.
			add_action( 'woocommerce_bulk_edit_variations_default', array( $this, 'variation_bulk_action_variable_cost' ), 10, 4 );
			// Edit products Cost in the Product List Table with the Bulk Action.
			add_filter( 'bulk_actions-edit-product', array( $this, 'bulk_actions_edit_product' ) );
			add_filter( 'handle_bulk_actions-edit-product', array( $this, 'handle_bulk_actions_edit_product' ), 10, 3 );

			// Product List Table
			// Adds a "Cost" column header.
			add_filter( 'manage_edit-product_columns', array( $this, 'product_list_table_cost_column_header' ), 11 );
			// Renders the product cost in the product list table.
			add_action( 'manage_product_posts_custom_column', array( $this, 'product_list_table_cost_column' ), 11 );
			// Make the "Cost" column display as sortable.
			add_filter( 'manage_edit-product_sortable_columns', array( $this, 'product_list_table_cost_column_sortable' ), 11 );
			// Make the "Cost" column sortable.
			add_filter( 'request', array( $this, 'product_list_table_cost_column_orderby' ), 11 );

			// Quick edit.
			add_action( 'woocommerce_product_quick_edit_end', array( $this, 'render_quick_edit_cost_field' ) );
			add_action( 'manage_product_posts_custom_column', array( $this, 'add_quick_edit_inline_values' ) );
			add_action( 'woocommerce_product_quick_edit_save', array( $this, 'save_quick_edit_cost_field' ) );

			// Reports tab contents.
			add_action( 'yith_cog_stock_reports_options', array( $this, 'stock_report_tab_content' ) );
			add_action( 'yith_cog_reports_options', array( $this, 'report_tab_content' ) );

			// Render the Apply Cost buttons in the settings tab.
			add_action( 'woocommerce_admin_field_yith_cog_apply_cost_html', array( $this, 'yith_apply_cost_buttons' ) );
			// Render the import Cost buttons in the settings tab.
			add_action( 'woocommerce_admin_field_yith_cog_import_cost_html', array( $this, 'yith_import_cost_buttons' ) );

			// Hidde the item meta in the order.
			add_filter( 'woocommerce_hidden_order_itemmeta', array( $this, 'yith_cog_hidden_order_item_meta' ), 10, 1 );

			add_filter( 'yith_cog_settings_options', array( $this, 'add_integration_options_in_settings' ), 10, 1 );

			// screen options.
			add_filter( 'screen_options_show_submit', array( $this, 'custom_screen_options' ), 10, 2 );
			add_action( 'current_screen', array( $this, 'add_screen_option' ) );
			add_filter( 'set-screen-option', array( $this, 'set_screen_option' ), 10, 3 );
			add_filter( 'manage_yith-plugins_page_yith_cog_setting_columns', array( $this, 'add_screen_columns' ) );

			add_action( 'admin_action_export_sales_report', array( $this, 'export_sales_report' ) );
			add_action( 'admin_action_export_stock_report', array( $this, 'export_stock_report' ) );

		}

		/**
		 * Returns single instance of the class
		 *
		 * @since 1.0.0
		 */
		public static function get_instance() {
			if ( is_null( self::$instance ) ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		/**
		 * Add custom Screen option
		 *
		 * @param string $show_button  Default screen html.
		 * @param mixed  $screen_class Default screen class value.
		 *
		 * @return $show_button
		 * @since 1.0.0
		 */
		public function custom_screen_options( $show_button, $screen_class ) {

			if ( isset( $_GET['tab'] ) && 'settings' == $_GET['tab'] ) { //phpcs:ignore
				return;
			}

			if ( isset( $_GET['page'] ) && 'yith_cog_setting' === $_GET['page'] ) { //phpcs:ignore

				$currency_option = array(
					'label' => esc_html_x( 'Currency', 'input title', 'yith-cost-of-goods-for-woocommerce' ),
					'desc'  => esc_html_x( 'Show currency symbol', 'input description', 'yith-cost-of-goods-for-woocommerce' ),
					'type'  => 'onoff',
					'id'    => 'yith_cog_currency_report',
					'name'  => 'yith_cog_currency_report',
					'value' => get_option( 'yith_cog_currency_report', false ),
				);

				?>
				<fieldset class="yith-cog-currency-symbol-option">
					<legend class="field-label"><?php echo esc_html( $currency_option['label'] ); ?></legend>
					<label for="yith_cog_show_currency"><?php echo esc_html( $currency_option['desc'] ); ?></label>
					<?php yith_plugin_fw_get_field( $currency_option, true ); ?>
				</fieldset>

				<?php

			}

			return $show_button;

		}


		/**
		 * Add Screen option
		 *
		 * @return void
		 * @since 1.0.0
		 */
		public function add_screen_option() {

			if ( isset( $_GET['tab'] ) && 'settings' == $_GET['tab'] ) { //phpcs:ignore
				return;
			}

			if ( isset( $_GET['page'] ) && 'yith_cog_setting' === $_GET['page'] ) { //phpcs:ignore

				$this->screen_options = array(
					'per_page' => array(
						'label'    => _x( 'Products per page', '[ADMIN] Rates pagination label', 'yith-cost-of-goods-for-woocommerce' ),
						'default'  => 20,
						'option'   => 'yith_cog_products_per_page',
						'sanitize' => 'intval',
					),
				);
			}

			if ( empty( $this->screen_options ) ) {
				return;
			}

			foreach ( $this->screen_options as $slug => $options ) {
				add_screen_option( $slug, $options );
			}
		}

		/**
		 * Save custom screen options
		 *
		 * @param bool   $set    Value to filter (default to false).
		 * @param string $option Custom screen option key.
		 * @param mixed  $value  Custom screen option value.
		 *
		 * @return mixed Value to be saved as user meta; false if no value should be saved
		 */
		public function set_screen_option( $set, $option, $value ) {

			if ( ! isset( $_GET['page'] ) && 'yith_cog_setting' !== $_GET['page'] ) { //phpcs:ignore
				return false;
			}

			if ( 'yith_cog_products_per_page' !== $option ) {
				return false;
			}

			if ( ! $value ) {
				return false;
			}

			update_option( $option, $value );

			return $value;
		}

		/**
		 * Add Screen columns for current screen
		 *
		 * @param array $columns Array of defined columns.
		 *
		 * @return array Filtered array of columns
		 */
		public function add_screen_columns( $columns ) {

			if ( isset( $_GET['page'] ) && 'yith_cog_setting' === $_GET['page'] && ! isset( $_GET['tab'] ) || isset( $_GET['tab'] ) && 'report' === $_GET['tab'] && isset( $_GET['sub_tab'] ) && 'report-sales' === $_GET['sub_tab'] ) { //phpcs:ignore

				$this->screen_columns = array(
					'product'            => _x( 'Product', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'quantity'           => _x( 'Quantity', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'avg_product_price'  => _x( 'AVG Product Price', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'revenue'            => _x( 'Revenue', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'avg_product_cost'   => _x( 'AVG Product Cost', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'cost'               => _x( 'Cost', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'avg_product_margin' => _x( 'AVG Gross Profit', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'margin'             => _x( 'Gross Profit', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'margin_percentage'  => _x( 'Margin %', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
				);

			} else if ( isset( $_GET['page'] ) && 'yith_cog_setting' === $_GET['page'] && isset( $_GET['tab'] ) && 'report' === $_GET['tab'] && isset( $_GET['sub_tab'] ) && 'report-stock' === $_GET['sub_tab'] ) { //phpcs:ignore

				$this->screen_columns = array(
					'product'          => _x( 'Product', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'quantity'         => _x( 'Stock Quantity', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'product_price'    => _x( 'Price', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'total_price'      => _x( 'Total Price', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'product_cost'     => _x( 'Cost', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'cost'             => _x( 'Total Cost', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
					'potential_profit' => _x( 'Potential Profit', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' ),
				);
			}

			if ( ! empty( $this->screen_columns ) ) {
				$custom_columns_options = get_option( 'yith_cog_columns_custom_fields_toggle', array() );

				if ( ! empty( $custom_columns_options ) ) {
					foreach ( $custom_columns_options as $column ) {
						$columns[ $column['cog_custom_column_meta'] ] = $column['cog_custom_column_name'];
					}
				}

				$columns = array_merge( $this->screen_columns, $columns );
			}

			return $columns;
		}

		/**
		 * Action Links.
		 *
		 * @param array $links Plugin links.
		 *
		 * @return array
		 */
		public function action_links( $links ) {
			$links = yith_add_action_links( $links, $this->panel_page, false, YITH_COG_SLUG );
			return $links;
		}

		/**
		 * Adds action links to plugin admin page
		 *
		 * @param array    $new_row_meta_args Row meta args.
		 * @param string[] $plugin_meta   An array of the plugin's metadata, including the version, author, author URI, and plugin URI.
		 * @param string   $plugin_file   Path to the plugin file relative to the plugins directory.
		 * @param array    $plugin_data   Plugin data.
		 * @param string   $status        Status.
		 * @param string   $init_file     Init file.
		 *
		 * @return array
		 */
		public function plugin_row_meta( $new_row_meta_args, $plugin_meta, $plugin_file, $plugin_data, $status, $init_file = 'YITH_COG_INIT' ) {
			if ( defined( $init_file ) && constant( $init_file ) === $plugin_file ) {
				$new_row_meta_args['slug'] = YITH_COG_SLUG;
			}

			return $new_row_meta_args;
		}


		/**
		 * Register plugins for activation tab
		 *
		 * @return void
		 * @since    1.0.0
		 * @author   Andrea Grillo <andrea.grillo@yithemes.com>
		 */
		public function register_plugin_for_activation() {
			if ( ! class_exists( 'YIT_Plugin_Licence' ) ) {
				require_once YITH_COG_PATH . '/plugin-fw/licence/lib/yit-licence.php';
				require_once YITH_COG_PATH . '/plugin-fw/licence/lib/yit-plugin-licence.php';
			}
			YIT_Plugin_Licence()->register( YITH_COG_INIT, YITH_COG_SECRETKEY, YITH_COG_SLUG );
		}

		/**
		 * Register plugins for update tab
		 *
		 * @return void
		 * @since    1.0.0
		 * @author   Andrea Grillo <andrea.grillo@yithemes.com>
		 */
		public function register_plugin_for_updates() {
			if ( ! class_exists( 'YIT_Upgrade' ) ) {
				require_once YITH_COG_PATH . '/plugin-fw/lib/yit-upgrade.php';
			}
			YIT_Upgrade()->register( YITH_COG_SLUG, YITH_COG_INIT );
		}

		/**
		 * Retrieve the admin panel tabs.
		 *
		 * @return array
		 */
		protected function get_admin_panel_tabs(): array {
			return apply_filters(
				'yith_cog_admin_panel_tabs',
				array(
					'report'   => array(
						'title' => _x( 'Reports', 'Settings tab name', 'yith-cost-of-goods-for-woocommerce' ),
						'icon'  => '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
						<path stroke-linecap="round" stroke-linejoin="round" d="M3.75 3v11.25A2.25 2.25 0 006 16.5h2.25M3.75 3h-1.5m1.5 0h16.5m0 0h1.5m-1.5 0v11.25A2.25 2.25 0 0118 16.5h-2.25m-7.5 0h7.5m-7.5 0l-1 3m8.5-3l1 3m0 0l.5 1.5m-.5-1.5h-9.5m0 0l-.5 1.5m.75-9l3-3 2.148 2.148A12.061 12.061 0 0116.5 7.605" />
					  </svg>
					  ',
					),
					'settings' => array(
						'title' => _x( 'Settings', 'Settings tab name', 'yith-cost-of-goods-for-woocommerce' ),
						'icon'  => 'settings',
					),
				)
			);
		}



		/**
		 * Add Report settings page
		 */
		public function add_users_settings_page() {
			if ( ! empty( $this->panel ) ) {
				return;
			}
			$admin_tabs = $this->get_admin_panel_tabs();

			/**
			 * APPLY_FILTERS: yith_wcog_settings_page_capability
			 *
			 * Filter the Cost of Goods settings panel capabilities.
			 *
			 * @param string the capabilities
			 *
			 * @return string
			 */
			/**
			 * APPLY_FILTERS: yith_cog_setting_tabs
			 *
			 * Filter the plugin settings tabs.
			 *
			 * @param array the tabs
			 *
			 * @return array
			 */
			$args = array(
				'ui_version'       => 2,
				'create_menu_page' => true,
				'parent_slug'      => '',
				'page_title'       => 'YITH Cost of Goods for WooCommerce',
				'menu_title'       => 'Cost of Goods',
				'capability'       => apply_filters( 'yith_wcog_settings_page_capability', 'manage_options' ),
				'parent'           => '',
				'class'            => yith_set_wrapper_class(),
				'parent_page'      => 'yit_plugin_panel',
				'page'             => $this->panel_page,
				'admin-tabs'       => apply_filters( 'yith_cog_setting_tabs', $admin_tabs ),
				'options-path'     => YITH_COG_PATH . 'plugin-options',
				'plugin-url'       => YITH_COG_URL,
				'plugin_slug'      => YITH_COG_SLUG,
				'is_premium'       => defined( 'YITH_COG_PREMIUM' ),
				'help_tab'         => array(
					'hc_url'     => 'https://support.yithemes.com/hc/en-us',
					'doc_url'    => 'https://docs.yithemes.com/yith-cost-of-goods-for-woocommerce/',
				),
				'your_store_tools' => array(
					'items' => array(
						'wishlist'               => array(
							'name'           => 'Wishlist',
							'icon_url'       => YITH_COG_ASSETS_URL . '/images/plugins/wishlist.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-wishlist/',
							'description'    => _x(
								'Allow your customers to create lists of products they want and share them with family and friends.',
								'[YOUR STORE TOOLS TAB] Description for plugin YITH WooCommerce Wishlist',
								'yith-woocommerce-gift-cards'
							),
							'is_active'      => defined( 'YITH_WCWL_PREMIUM' ),
							'is_recommended' => true,
						),
						'ajax-product-filter'    => array(
							'name'           => 'Ajax Product Filter',
							'icon_url'       => YITH_COG_ASSETS_URL . '/images/plugins/ajax-product-filter.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-ajax-product-filter/',
							'description'    => _x(
								'Help your customers to easily find the products they are looking for and improve the user experience of your shop.',
								'[YOUR STORE TOOLS TAB] Description for plugin YITH WooCommerce Ajax Product Filter',
								'yith-woocommerce-gift-cards'
							),
							'is_active'      => defined( 'YITH_WCAN_PREMIUM' ),
							'is_recommended' => true,
						),
						'booking'                => array(
							'name'           => 'Booking and Appointment',
							'icon_url'       => YITH_COG_ASSETS_URL . '/images/plugins/booking.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-booking/',
							'description'    => _x(
								'Enable a booking/appointment system to manage renting or booking of services, rooms, houses, cars, accommodation facilities and so on.',
								'[YOUR STORE TOOLS TAB] Description for plugin YITH Bookings',
								'yith-woocommerce-gift-cards'
							),
							'is_active'      => defined( 'YITH_WCBK_PREMIUM' ),
							'is_recommended' => false,

						),
						'request-a-quote'        => array(
							'name'           => 'Request a Quote',
							'icon_url'       => YITH_COG_ASSETS_URL . '/images/plugins/request-a-quote.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-request-a-quote/',
							'description'    => _x(
								'Hide prices and/or the "Add to cart" button and let your customers request a custom quote for every product.',
								'[YOUR STORE TOOLS TAB] Description for plugin YITH WooCommerce Request a Quote',
								'yith-woocommerce-gift-cards'
							),
							'is_active'      => defined( 'YITH_YWRAQ_PREMIUM' ),
							'is_recommended' => false,
						),
						'product-addons'         => array(
							'name'           => 'Product Add-Ons & Extra Options',
							'icon_url'       => YITH_COG_ASSETS_URL . '/images/plugins/product-add-ons.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-product-add-ons/',
							'description'    => _x(
								'Add paid or free advanced options to your product pages using fields like radio buttons, checkboxes, drop-downs, custom text inputs, and more.',
								'[YOUR STORE TOOLS TAB] Description for plugin YITH WooCommerce Product Add-Ons',
								'yith-woocommerce-gift-cards'
							),
							'is_active'      => defined( 'YITH_WAPO_PREMIUM' ),
							'is_recommended' => false,
						),
						'dynamic-pricing'        => array(
							'name'           => 'Dynamic Pricing and Discounts',
							'icon_url'       => YITH_COG_ASSETS_URL . '/images/plugins/dynamic-pricing-and-discounts.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-dynamic-pricing-and-discounts/',
							'description'    => _x(
								'Increase conversions through dynamic discounts and price rules, and build powerful and targeted offers.',
								'[YOUR STORE TOOLS TAB] Description for plugin YITH WooCommerce Dynamic Pricing and Discounts',
								'yith-woocommerce-gift-cards'
							),
							'is_active'      => defined( 'YITH_YWDPD_PREMIUM' ),
							'is_recommended' => false,
						),
						'customize-my-account'   => array(
							'name'           => 'Customize My Account Page',
							'icon_url'       => YITH_COG_ASSETS_URL . '/images/plugins/customize-myaccount-page.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-customize-my-account-page/',
							'description'    => _x( 'Customize the My Account page of your customers by creating custom sections with promotions and ad-hoc content based on your needs.', '[YOUR STORE TOOLS TAB] Description for plugin YITH WooCommerce Customize My Account', 'yith-woocommerce-gift-cards' ),
							'is_active'      => defined( 'YITH_WCMAP_PREMIUM' ),
							'is_recommended' => false,
						),
						'recover-abandoned-cart' => array(
							'name'           => 'Recover Abandoned Cart',
							'icon_url'       => YITH_COG_ASSETS_URL . '/images/plugins/recover-abandoned-cart.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-recover-abandoned-cart/',
							'description'    => _x(
								'Contact users who have added products to the cart without completing the order and try to recover lost sales.',
								'[YOUR STORE TOOLS TAB] Description for plugin Recover Abandoned Cart',
								'yith-woocommerce-gift-cards'
							),
							'is_active'      => defined( 'YITH_YWRAC_PREMIUM' ),
							'is_recommended' => false,
						),
					),
				),
			);

			/* === Fixed: not updated theme  === */
			if ( ! class_exists( 'YIT_Plugin_Panel_WooCommerce' ) ) {
				require_once '../plugin-fw/lib/yit-plugin-panel-wc.php';
			}

			$this->panel             = new YIT_Plugin_Panel_WooCommerce( $args );
			$this->main_panel_option = "yit_{$args['parent']}_options";

		}

		/** Render the Cost for the Products & other methods ***************************************/

		/**
		 * Add cost field to simple products
		 */
		public function add_cost_field_to_simple_product() {

			/**
			 * APPLY_FILTERS: yith_cog_add_cost_field_label
			 *
			 * Filter the Cost of Goods field label in the products edit page.
			 *
			 * @param string the label
			 *
			 * @return string
			 */
			woocommerce_wp_text_input(
				array(
					'id'        => 'yith_cog_cost',
					'class'     => 'wc_input_price short',
					'label'     => apply_filters( 'yith_cog_add_cost_field_label', esc_html__( 'YITH Cost of Good', 'yith-cost-of-goods-for-woocommerce' ) ) . ' (' . get_woocommerce_currency_symbol() . ')',
					'data_type' => 'price',
				)
			);
		}

		/**
		 * Add cost field to variable products
		 */
		public function add_cost_field_to_variable_product() {

			woocommerce_wp_text_input(
				array(
					'id'            => 'yith_cog_cost_variable',
					'class'         => 'wc_input_price short',
					'wrapper_class' => 'show_if_variable',
					'label'         => apply_filters( 'yith_cog_add_cost_field_label', esc_html__( 'YITH Cost of Good', 'yith-cost-of-goods-for-woocommerce' ) ) . ' (' . get_woocommerce_currency_symbol() . ')',
					'data_type'     => 'price',
				)
			);
		}

		/**
		 * Add cost field to YITH Bundle products
		 */
		public function add_cost_field_to_bundle_products() {
			global $product_object;

			if ( ! $product_object->is_type( 'yith_bundle' ) ) {
				return;
			}

			?>

			<div class="yith-wcpb-form-field">
				<label class="yith-wcpb-form-field__label"><?php echo esc_html( apply_filters( 'yith_cog_add_cost_field_label', __( 'YITH Cost of Good', 'yith-cost-of-goods-for-woocommerce' ) ) . ' (' . get_woocommerce_currency_symbol() . ')' ); ?></label>
				<div class="yith-wcpb-form-field__content">
					<?php
					yith_plugin_fw_get_field(
						array(
							'type'  => 'text',
							'id'    => 'yith_cog_cost',
							'name'  => 'yith_cog_cost',
							'value' => $product_object->get_meta( 'yith_cog_cost' ),
						),
						true
					);
					?>
				</div>
			</div>

			<?php

			/* woocommerce_wp_text_input(
				array(
					'id'            => 'yith_cog_cost',
					'class'         => 'wc_input_price short',
					'label'         => apply_filters( 'yith_cog_add_cost_field_label', esc_html__( 'YITH Cost of Good', 'yith-cost-of-goods-for-woocommerce' ) ) . ' (' . get_woocommerce_currency_symbol() . ')',
					'data_type'     => 'price',
					'wrapper_class' => 'show_if_yith_bundle',
				)
			); */
		}

		/**
		 * Save cost field for simple product
		 *
		 * @param int $post_id Post ID.
		 */
		public function save_simple_product_cost( $post_id ) {

			$product_type = empty( $_POST['product-type'] ) ? 'simple' : sanitize_title( stripslashes( $_POST['product-type'] ) ); // phpcs:ignore

			if ( 'variable' !== $product_type ) {

				$cost = $_POST['yith_cog_cost']; // phpcs:ignore

				update_post_meta( $post_id, 'yith_cog_cost', wc_format_decimal( $cost ) );
			}
		}

		/**
		 * Add cost field to variable products under the Variations tab after the shipping class dropdown
		 *
		 * @param int     $loop           Position in the loop.
		 * @param array   $variation_data Variation data.
		 * @param WP_Post $variation      Post data.
		 */
		public function add_cost_field_to_product_variation( $loop, $variation_data, $variation ) {

			$default_cost = get_post_meta( $variation->post_parent, 'yith_cog_cost_variable', true );
			$cost         = get_post_meta( $variation->ID, 'yith_cog_cost', true );

			// if the variation cost is actually the default variable product cost.
			if ( 'yes' === get_post_meta( $variation->ID, 'yith_cog_default_cost', true ) ) {
				$cost = '';
			}
			?>
			<div>
				<p class="form-row form-row-first">
					<label>
						<?php
						/**
						 * APPLY_FILTERS: yith_cog_add_cost_field_label_variations
						 *
						 * Filter the Cost of Goods field label in the product variations edit page.
						 *
						 * @param string the label
						 *
						 * @return string
						 */
						/* translators: Placeholder: %s - currency symbol */
						apply_filters( 'yith_cog_add_cost_field_label_variations', printf( esc_html__( 'YITH Cost of Good: (%s)', 'yith-cost-of-goods-for-woocommerce' ), esc_html( get_woocommerce_currency_symbol() ) ) );
						?>
					</label>
					<input type="text" size="6" name="variable_cost_of_good[<?php echo esc_attr( $loop ); ?>]" value="<?php echo esc_attr( $cost ); ?>" class="wc_input_price" placeholder="<?php echo esc_attr( $default_cost ); ?>" />
				</p>
			</div>
			<?php
		}

		/**
		 * Update cost meta for a variation
		 *
		 * @param int $variation_id Variation ID.
		 * @param int $cost Cost.
		 */
		public function update_variation_product_cost( $variation_id, $cost ) {

			if ( '' !== $cost ) {
				update_post_meta( $variation_id, 'yith_cog_cost', wc_format_decimal( $cost ) );
				update_post_meta( $variation_id, 'yith_cog_default_cost', 'no' );
			} else {
				update_post_meta( $variation_id, 'yith_cog_cost', '' );
				update_post_meta( $variation_id, 'yith_cog_default_cost', 'no' );
			}
		}


		/**
		 * Save cost field for the variation product
		 *
		 * @param  int $variation_id Variation ID.
		 */
		public function save_variation_product_cost( $variation_id ) {
			$i = array_search( $variation_id, $_POST['variable_post_id'] ); // phpcs:ignore

			if ( false !== $i ) {
				$cost = $_POST['variable_cost_of_good'][ $i ]; // phpcs:ignore
				$this->update_variation_product_cost( $variation_id, $cost );
			}
		}

		/**
		 * Save the overall cost/min/max costs for variable products
		 *
		 * @param int $post_id Post ID.
		 */
		public function save_variable_product_cost( $post_id ) {

			if ( isset( $_POST['yith_cog_cost_variable'] ) ) { // phpcs:ignore
				$cost = $_POST['yith_cog_cost_variable']; // phpcs:ignore
			} else {
				$cost = get_post_meta( $post_id, 'yith_cog_cost_variable', true );
			}

			$this->update_variable_product_cost( $post_id, $cost );

			// update each variation with the parent cog.
			if ( '' !== $cost ) {
				$product = wc_get_product( $post_id );
				foreach ( $product->get_children() as $child_id ) {

					$variation_cost = get_post_meta( $child_id, 'yith_cog_cost', true );

					if ( empty( $variation_cost ) ) {
						$this->update_variation_product_cost( $child_id, $cost );
					}
				}
			}

		}

		/**
		 * Update the cost meta for a variable product and set variations costs if needed.
		 *
		 * @param object $product Product.
		 * @param int    $cost Cost.
		 */
		protected function update_variable_product_cost( $product, $cost ) {

			$product    = wc_get_product( $product );
			$product_id = $product->get_id();

			if ( ! $product ) {
				return;
			}

			update_post_meta( $product_id, 'yith_cog_cost_variable', wc_format_decimal( $cost ) );

			foreach ( $product->get_children() as $child_id ) {
				$child_product = wc_get_product( $child_id );

				if ( $child_product ) {
					$child_cost = get_post_meta( $child_id, 'yith_cog_cost', true );
					$is_default = 'yes' === get_post_meta( $child_id, 'yith_cog_default_cost', true );

					if ( '' === $child_cost || $is_default ) {
						update_post_meta( $child_id, 'yith_cog_cost', wc_format_decimal( $cost ) );
						update_post_meta( $child_id, 'yith_cog_default_cost', '' !== $cost ? 'yes' : 'no' );
					}
				}
			}

			list( $min_variation_cost, $max_variation_cost ) = get_variable_product_min_max_costs( $product_id );

			update_post_meta( $product_id, 'yith_cog_cost', wc_format_decimal( $min_variation_cost ) );
			update_post_meta( $product_id, 'yith_cog_min_variation_cost', wc_format_decimal( $min_variation_cost ) );
			update_post_meta( $product_id, 'yith_cog_max_variation_cost', wc_format_decimal( $max_variation_cost ) );
		}

		/** Bulk Actions methods ***************************************/

		/**
		 * Cost bulk edit action on the products admin table
		 *
		 * @param array $bulk_actions Bulk actions.
		 *
		 * @return array
		 */
		public function bulk_actions_edit_product( $bulk_actions ) {
			$bulk_actions['set_cost_of_goods'] = esc_html__( 'Set Cost of Goods', 'yith-cost-of-goods-for-woocommerce' );
			return $bulk_actions;
		}

		/**
		 * Handle the Cost bulk edit action on the products admin table
		 *
		 * @param string $redirect_to URL to redirect to.
		 * @param string $action      Action name.
		 * @param array  $post_ids         List of ids.
		 *
		 * @return string
		 */
		public function handle_bulk_actions_edit_product( $redirect_to, $action, $post_ids ) {
			if ( 'set_cost_of_goods' !== $action ) {
				return $redirect_to;
			} elseif ( ! isset( $_REQUEST['yith_cog_cost'] ) || empty( $_REQUEST['yith_cog_cost'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				return $redirect_to;
			}

			$updated_post_ids = array();
			$new_cog          = (float) $_REQUEST['yith_cog_cost']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

			foreach ( $post_ids as $post_id ) {
				$product = wc_get_product( $post_id );

				if ( 'simple' === $product->get_type() ) {
					if ( ! update_post_meta( $post_id, 'yith_cog_cost', $new_cog ) ) {
						wp_die( esc_html__( 'Error while updating the product cost.', 'yith-cost-of-goods-for-woocommerce' ) );
					}
					$updated_post_ids[] = $post_id;
				}
				if ( 'variable' === $product->get_type() ) {
					if ( ! update_post_meta( $post_id, 'yith_cog_cost_variable', $new_cog ) ) {
						wp_die( esc_html__( 'Error while updating the product cost.', 'yith-cost-of-goods-for-woocommerce' ) );
					}
					$updated_post_ids[] = $post_id;
				}
			}

			$redirect_to = add_query_arg( 'bulk_product_cog_update_results', count( $updated_post_ids ), $redirect_to );

			return $redirect_to;
		}


		/**
		 * Cost bulk edit action on the product admin Variations tab
		 */
		public function add_variable_product_bulk_edit_cost_action() {
			?>
			<optgroup label="Cost of Goods">
				<option value="variable_cost_of_goods"><?php esc_html_e( 'Set cost', 'yith-cost-of-goods-for-woocommerce' ); ?></option>
			</optgroup>
			<?php
		}

		/**
		 * Set variation cost for variations via bulk edit
		 *
		 * @param string $bulk_action Bulk action.
		 * @param array  $data Data.
		 * @param int    $product_id Product ID.
		 * @param array  $variations Variations.
		 */
		public function variation_bulk_action_variable_cost( $bulk_action, $data, $product_id, $variations ) {

			if ( empty( $data['value'] ) ) {
				return;
			}
			if ( 'variable_cost_of_goods' !== $bulk_action ) {
				return;
			}
			foreach ( $variations as $variation_id ) {
				$this->update_variation_product_cost( $variation_id, $data['value'] );
			}
		}


		/** Product List table methods ********************************************/

		/**
		 * Add a "Cost" column header on the Product list table
		 *
		 * @param array $existing_columns Columns.
		 *
		 * @return array
		 */
		public function product_list_table_cost_column_header( $existing_columns ) {

			$columns = array();
			foreach ( $existing_columns as $key => $value ) {
				$columns[ $key ] = $value;

				if ( 'price' === $key ) {
					$columns['cost'] = esc_html__( 'Cost', 'yith-cost-of-goods-for-woocommerce' );
				}
			}
			return $columns;
		}

		/**
		 * Product cost value in the products list table
		 *
		 * @param string $column Table column.
		 */
		public function product_list_table_cost_column( $column ) {
			global $the_product;

			if ( 'cost' === $column ) {

				if ( get_cost_html( $the_product ) ) {
					echo wp_kses_post( get_cost_html( $the_product ) );
				} else {
					echo '<span class="na">&ndash;</span>';
				}
			}
			/**
			 * APPLY_FILTERS: yith_cog_product_list_table_column_value
			 *
			 * Filter the Cost of Goods column value in the products table.
			 *
			 * @param string $column the value in HTML
			 *
			 * @return string
			 */
			apply_filters( 'yith_cog_product_list_table_column_value', $column );
		}

		/**
		 * Add the Cost column to the list of sortable columns
		 *
		 * @param array $columns Sortable columns.
		 *
		 * @return array
		 */
		public function product_list_table_cost_column_sortable( $columns ) {
			$columns['cost'] = 'cost';
			return $columns;
		}

		/**
		 * Add the Cost column to the orderby clause if sorting by cost
		 *
		 * @param array $vars Query vars.
		 *
		 * @return array
		 */
		public function product_list_table_cost_column_orderby( $vars ) {

			if ( isset( $vars['orderby'] ) && 'cost' === $vars['orderby'] ) {

				$vars = array_merge(
					$vars,
					array(
						'meta_key' => 'yith_cog_cost', // phpcs:ignore slow query ok.
						'orderby'  => 'meta_value_num',
					)
				);
			}
			return $vars;
		}


		/** Quick Edit ****************************************************/

		/**
		 * Quick edit cost field.
		 */
		public function render_quick_edit_cost_field() {
			?>
			<br class="clear" />
			<label class="alignleft">
				<span class="title"><?php esc_html_e( 'Cost of Goods' ); ?></span>
				<span class="input-text-wrap">
					<input type="text" name="yith_cog_cost" class="text yith-cog-cost" value="">
				</span>
			</label>
			<?php
		}

		/**
		 * Add markup for the custom product meta values so Quick Edit can fill the inputs.
		 *
		 * @param string $column Column name.
		 */
		public function add_quick_edit_inline_values( $column ) {
			global $the_product;

			if ( 'name' === $column && is_object( $the_product ) ) {

				$meta_key   = $the_product->is_type( 'variable' ) ? 'yith_cog_cost_variable' : 'yith_cog_cost';
				$meta_value = get_post_meta( $the_product->get_id(), $meta_key, true );

				echo '<div id="yith_cog_inline_' . esc_attr( $the_product->get_id() ) . '" class="hidden">';
				echo '<div class="yith_cog_cost">' . esc_html( $meta_value ) . '</div>';
				echo '</div>';
			}
		}


		/**
		 * Save the quick edit cost field
		 *
		 * @param object $product Product.
		 */
		public function save_quick_edit_cost_field( $product ) {

			$cost = isset( $_REQUEST['yith_cog_cost'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['yith_cog_cost'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

			if ( $product->is_type( 'variable' ) ) {
				$this->update_variable_product_cost( $product, $cost );
			} else {
				update_post_meta( $product->get_id(), 'yith_cog_cost', wc_format_decimal( $cost ) );
			}
		}

		/** Apply Cost buttons. ****************************************************/

		/**
		 * Render the apply cost buttons.
		 */
		public function yith_apply_cost_buttons() {

			yith_cog_get_view( 'apply-cost-settings.php' );
		}


		/** Import Cost buttons. ****************************************************/

		/**
		 * Render the import cost buttons.
		 */
		public function yith_import_cost_buttons() {

			yith_cog_get_view( 'import-cost-settings.php' );
		}


		/**
		 * Hide item meta from the orders.
		 *
		 * @param array $meta_array Array with metas that will be hidden.
		 *
		 * @return array
		 */
		public function yith_cog_hidden_order_item_meta( $meta_array ) {

			$meta_array[] = '_yith_cog_item_cost';
			$meta_array[] = '_yith_cog_item_total_cost';
			$meta_array[] = '_yith_cog_item_price';
			$meta_array[] = '_yith_cog_item_tax';
			$meta_array[] = '_yith_cog_item_name_sortable';
			$meta_array[] = '_yith_cog_item_product_type';

			/**
			 * APPLY_FILTERS: yith_cog_order_item_meta
			 *
			 * Filter the hidden order item meta from the cost of goods.
			 *
			 * @param array $meta_array the array with the hidden meta data
			 *
			 * @return array
			 */
			return apply_filters( 'yith_cog_order_item_meta', $meta_array );
		}


		/**
		 * Add cost field to Name your price products
		 */
		public function add_cost_field_to_simple_product_name_your_price() {

			woocommerce_wp_text_input(
				array(
					'id'        => 'yith_cog_cost',
					'class'     => 'wc_input_price short',
					'label'     => apply_filters( 'yith_cog_add_cost_field_label', esc_html__( 'YITH Cost of Good', 'yith-cost-of-goods-for-woocommerce' ) ) . ' (' . get_woocommerce_currency_symbol() . ')',
					'data_type' => 'price',
				)
			);
		}

		/**
		 * Add cost field to variable products with Name Your Price
		 *
		 * @param array $settings Default setting options array.
		 *
		 * @return array
		 */
		public function add_integration_options_in_settings( $settings ) {

			if ( apply_filters( 'yith_cog_shop_wc_cost_of_goods_integration_option', false ) ) {
				$option = array(
					'import_cost_tab_start'  => array(
						'type' => 'sectionstart',
						'id'   => 'yith_previous_orders_settings_tab_start',
					),
					'import_cost_tab_title'  => array(
						'title' => esc_html__( 'Import Cost of Goods from WooCommerce', 'yith-cost-of-goods-for-woocommerce' ),
						'type'  => 'title',
						'desc'  => '',
						'id'    => 'yith_cog_import_cost_tab',
					),
					'import_cost_tab_button' => array(
						'title' => '',
						'desc'  => '',
						'id'    => '',
						'type'  => 'yith_cog_import_cost_html',
						'html'  => '',
					),
					'import_cost_tab_end'    => array(
						'type' => 'sectionend',
						'id'   => 'yith_settings_tab_end',
					),
				);

				$settings = array_merge( $settings, $option );
			}

			return $settings;

		}

		/**
		 * Export sales report handler
		 */
		public function export_sales_report() {

			if ( isset( $_GET['nonce'] ) && ! wp_verify_nonce( $_GET['nonce'], 'export-sales-report' ) ) { // phpcs:ignore.
				die( 'nonce error' );
			}

			if ( ! isset( $_GET['action'] ) || 'export_sales_report' !== $_GET['action'] ) {
				return;
			}

			// Get the items data to be exported.
			global $wpdb;

			$filters = isset( $_GET['args'] ) ? $_GET['args'] : array(); // phpcs:ignore.

			$default_from  = apply_filters( 'yith_cog_default_from_datepicker', date ( 'd-m-Y', strtotime("first day of this month") ) );

			$from = isset( $filters['yith-cog-from-datepicker'] ) ? $filters['yith-cog-from-datepicker'] : $default_from;
			$to   = isset( $filters['yith-cog-to-datepicker'] ) ? $filters['yith-cog-to-datepicker'] : current_time( 'mysql' );

			$from = gmdate( 'Y-m-d h:i:s', strtotime( $from ) );
			$to   = gmdate( 'Y-m-d h:i:s', strtotime( $to ) );

			$product_lookup_table = $wpdb->prefix . 'yith_cog_sales_report_data';
			$query_string         = "
			select *
			from {$product_lookup_table}
			where order_item_id > 0
			and date_created >= '{$from}' 
			and date_created <= '{$to}'
			group by order_item_id
		";
			
			$products_data = $wpdb->get_results( $query_string ); // phpcs:ignore.

			$formatted_report_data = array();

			foreach ( $products_data as $item => $product_data ) {

				$order   = wc_get_order( $product_data->order_id );
				$product = wc_get_product( $product_data->product_id );

				if ( ! is_object( $product ) || ! is_object( $order ) || $product instanceof WC_Product_Gift_Card || ! in_array( $order->get_status(), array( 'on-hold', 'processing', 'completed', 'refunded' ), true ) ) {
					unset( $products_data[ $item ] );
					continue;
				}

				// Integration with YITH Bundle: if the product is inside a bundle, dont add it to the report
				$is_bundle = wc_get_order_item_meta( $product_data->order_item_id, '_bundled_by' );

				if ( 'refunded' == $order->get_status() || $is_bundle ){
					continue;
				}

				$refunded_item_id = wc_get_order_item_meta( $product_data->order_item_id, '_refunded_item_id' );

				if ( $refunded_item_id || $product_data->product_qty < 0 ) {
					$item_cost = wc_get_order_item_meta( $refunded_item_id, '_yith_cog_item_cost' );

					$product_data->item_cost = (float) $item_cost * (int) $product_data->product_qty;
				}

				if ( ! isset( $product_data->item_cost ) || $product_data->item_cost <= 0 ) {
					continue;
				}

				$product_id = $product_data->variation_id > 0 ? $product_data->variation_id : $product_data->product_id;

				$formatted_report_data[ $product_id ] = $formatted_report_data[ $product_id ] ?? array();

				$formatted_report_data[ $product_id ]['product_name'] = $product->get_name();

				// total sold quantity.
				if ( isset( $formatted_report_data[ $product_id ]['quantity'] ) ) {
					$formatted_report_data[ $product_id ]['quantity'] += $product_data->product_qty;
				} else {
					$formatted_report_data[ $product_id ]['quantity'] = $product_data->product_qty;
				}

				// total revenue.
				if ( isset( $formatted_report_data[ $product_id ]['revenue'] ) ) {
					$formatted_report_data[ $product_id ]['revenue'] += $product_data->product_net_revenue;
				} else {
					$formatted_report_data[ $product_id ]['revenue'] = $product_data->product_net_revenue;
				}

				// total cost.
				if ( isset( $formatted_report_data[ $product_id ]['total_cost'] ) ) {
					$formatted_report_data[ $product_id ]['total_cost'] += $product_data->item_cost * $product_data->product_qty;
				} else {
					$formatted_report_data[ $product_id ]['total_cost'] = $product_data->item_cost * $product_data->product_qty;
				}

				$filter_product_id = isset( $filters['_product_id'] ) ? $filters['_product_id'] : '';

				// product filter.
				if ( '' !== $filter_product_id && $product_id !== $filter_product_id ) {
					unset( $formatted_report_data[ $product_id ] );
				}

				$category_ids = isset( $filters['_category_id'] ) ? $filters['_category_id'] : array();

				// category filter.
				if ( isset( $category_ids ) && ! empty( $category_ids ) && is_object( $product ) ) {

					$product_categories = $product->get_category_ids();
					foreach ( $category_ids as $category_filter ) { // phpcs:ignore

						if ( ! in_array( $category_filter, $product_categories, false ) ) { // phpcs:ignore
							unset( $formatted_report_data[ $product_id ] );
						}
					}
				}
			}

			$columns_labels = array();

			$columns_labels['0'][] = _x( 'Product', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'Quantity', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'AVG Price', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'Revenue', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'AVG Cost', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'Cost', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'AVG Gross Profit', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'Gross Profit', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'Margin %', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );

			/**
			 * APPLY_FILTERS: yith_cog_sales_report_csv_columns_labels
			 *
			 * Filter the columns names exported in the sales report CSV.
			 *
			 * @param array $columns_labels the array with the columns names
			 *
			 * @return array
			 */
			$columns_labels = apply_filters( 'yith_cog_sales_report_csv_columns_labels', $columns_labels );

			$csv_data = array();

			foreach ( $formatted_report_data as $product_id => $item_data ) {

				$name              = $item_data['product_name'];
				$quantity          = $item_data['quantity'];
				$revenue           = $item_data['revenue'];
				$cost              = $item_data['total_cost'];
				$avg_price         = $revenue / $quantity;
				$avg_cost          = $item_data['total_cost'] / $quantity;
				$margin            = $revenue - $cost;
				$avg_margin        = $margin / $quantity;
				$margin_percentage = 0 != $revenue ? round( ( $margin / $revenue ) * 100, 2 ) : 0;

				$csv_data[ $product_id ][] = $name;
				$csv_data[ $product_id ][] = $quantity;
				$csv_data[ $product_id ][] = number_format( $avg_price, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );
				$csv_data[ $product_id ][] = number_format( $revenue, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );
				$csv_data[ $product_id ][] = number_format( $avg_cost, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );
				$csv_data[ $product_id ][] = number_format( $cost, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );
				$csv_data[ $product_id ][] = number_format( $avg_margin, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );
				$csv_data[ $product_id ][] = number_format( $margin, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );
				$csv_data[ $product_id ][] = $margin_percentage;

				/**
				 * APPLY_FILTERS: yith_cog_sales_report_csv_product_item
				 *
				 * Filter the product data exported in the sales report CSV.
				 *
				 * @param array $csv_data   the array with the CSV product data
				 * @param int   $product_id current product ID
				 * @param array $item_data  the array with product information
				 *
				 * @return array
				 */
				$csv_data = apply_filters( 'yith_cog_sales_report_csv_product_item', $csv_data, $product_id, $item_data );

			}

			$data = array_merge( $columns_labels, $csv_data );

			if ( ! empty( $data ) ) {

				header( 'Content-disposition: attachment; filename=sales-report.csv' );
				header( 'Content-Type: text/csv' );

				$fp = fopen( 'php://output', 'w' );

				fputcsv( $fp, array_keys( reset( $data ) ) );

				foreach ( $data as $row ) {
					fputcsv( $fp, $row );
				}

				fclose( $fp ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fclose
			}

			exit();

		}

		/**
		 * Export stock report handler
		 */
		public function export_stock_report() {

			if ( isset( $_GET['nonce'] ) && ! wp_verify_nonce( $_GET['nonce'], 'export-stock-report' ) ) { // phpcs:ignore.
				die( 'nonce error' );
			}

			if ( ! isset( $_GET['action'] ) || 'export_stock_report' !== $_GET['action'] ) {
				return;
			}

			// Get the items data to be exported.

			global $wpdb;

			$query_from = "FROM {$wpdb->posts} as posts
			INNER JOIN {$wpdb->postmeta} AS postmeta ON posts.ID = postmeta.post_id
			INNER JOIN {$wpdb->postmeta} AS postmeta2 ON posts.ID = postmeta2.post_id
			INNER JOIN {$wpdb->postmeta} AS postmeta3 ON posts.ID = postmeta3.post_id

			WHERE 1=1
			AND posts.post_type IN ( 'product' , 'product_variation' )
			AND posts.post_status = 'publish'
			AND postmeta.meta_key = '_manage_stock'
			AND postmeta.meta_value = 'yes'
			AND postmeta2.meta_key = '_stock'
			AND postmeta2.meta_value > '0'
			AND postmeta3.meta_key = 'yith_cog_cost'
			AND postmeta3.meta_value > '0'
			";

			$filters = isset( $_GET['args'] ) ? $_GET['args'] : array(); // phpcs:ignore.

			$filter_product_id = isset( $filters['_product_id'] ) ? $filters['_product_id'] : '';

			if ( '' !== $filter_product_id ) {
				$query_from .= "AND postmeta.post_id = {$filter_product_id} ";
			}

			$filter_category_ids = isset( $filters['_category_id'] ) ? $filters['_category_id'] : array();

			if ( ! empty( $filter_category_ids ) ) {
				$categories  = implode( ',', $filter_category_ids );
				$query_from .= "AND tr.term_taxonomy_id IN ( {$categories} ) ";
			}

			$items = $wpdb->get_results( "SELECT posts.ID as id, posts.post_parent as parent {$query_from} GROUP BY posts.ID", ARRAY_A ); // phpcs:ignore

			$columns_labels = array();

			$columns_labels['0'][] = _x( 'Product', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'Stock Quantity', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'Price', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'Total Price', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'Cost', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'Total Cost', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );
			$columns_labels['0'][] = _x( 'Potential Profit', '[ADMIN] Sales report heading', 'yith-cost-of-goods-for-woocommerce' );

			/**
			 * APPLY_FILTERS: yith_cog_stock_report_csv_columns_labels
			 *
			 * Filter the columns names exported in the stock report CSV.
			 *
			 * @param array $columns_labels the array with the columns names
			 *
			 * @return array
			 */
			$columns_labels = apply_filters( 'yith_cog_stock_report_csv_columns_labels', $columns_labels );

			$csv_data = array();

			foreach ( $items as $item ) {

				$product    = wc_get_product( $item['id'] );
				$product_id = $product->get_id();

				if ( $product->is_type( 'gift-card' ) ) {
					continue;
				}

				if ( defined( 'ICL_LANGUAGE_CODE' ) ) {

					$language = apply_filters( 'wpml_post_language_details', '', $product->get_id() );

					if ( $language['language_code'] != ICL_LANGUAGE_CODE ) { // phpcs:ignore.
						continue;
					}
				}

				$name        = $product->get_name();
				$quantity    = $product->get_stock_quantity();
				$price       = (float) $product->get_price();
				$total_price = $price * $quantity;
				$cost        = floatval( get_cost( $product ) );
				$total_cost  = $cost * $quantity;
				$profit      = $total_price - $total_cost;
				
				$csv_data[ $product_id ][] = $name;
				$csv_data[ $product_id ][] = $quantity;
				$csv_data[ $product_id ][] = number_format( $price, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );
				$csv_data[ $product_id ][] = number_format( $total_price, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );
				$csv_data[ $product_id ][] = number_format( $cost, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );
				$csv_data[ $product_id ][] = number_format( $total_cost, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );
				$csv_data[ $product_id ][] = number_format( $profit, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );

				/**
				 * APPLY_FILTERS: yith_cog_stock_report_csv_product_item
				 *
				 * Filter the product data exported in the stock report CSV.
				 *
				 * @param array $csv_data   the array with the CSV product data
				 * @param int   $product_id current product ID
				 *
				 * @return array
				 */
				$csv_data = apply_filters( 'yith_cog_stock_report_csv_product_item', $csv_data, $product_id );

			}

			$data = array_merge( $columns_labels, $csv_data );

			if ( ! empty( $data ) ) {

				header( 'Content-disposition: attachment; filename=stock-report.csv' );
				header( 'Content-Type: text/csv' );

				$fp = fopen( 'php://output', 'w' );

				fputcsv( $fp, array_keys( reset( $data ) ) );

				foreach ( $data as $row ) {
					fputcsv( $fp, $row );
				}

				fclose( $fp ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fclose
			}

			exit();

		}

		/**
		 * Enqueue scripts.
		 */
		public function enqueue_scripts() {

			$screen = get_current_screen();

			if ( isset( $_REQUEST['page'] ) && 'yith_cog_setting' === $_REQUEST['page'] || 'edit-product' === $screen->id ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended

				/* ====== Style ====== */
				wp_register_style( 'yith-cog-style', YITH_COG_ASSETS_URL . 'css/yith-cog-style.css', array(), YITH_COG_ENQUEUE_VERSION );
				wp_enqueue_style( 'yith-cog-style' );

				/* ====== Script ====== */
				wp_register_script(
					'yith-cog-admin-js',
					YITH_COG_ASSETS_URL . 'js/yith-cog-admin.js',
					array(
						'jquery',
						'jquery-ui-sortable',
						'jquery-ui-datepicker',
					),
					YITH_COG_ENQUEUE_VERSION,
					true
				);
				wp_enqueue_script( 'yith-cog-admin-js' );

				wp_localize_script(
					'yith-cog-admin-js',
					'cog_data',
					array(
						'ajaxurl'          => admin_url( 'admin-ajax.php' ),
						'apply_cost_modal' => array(
							'title'   => esc_html__( 'Apply cost to previous orders', 'yith-cost-of-goods-for-woocommerce' ),
							'content' => yith_cog_get_view_html( 'modals/apply-cost/content.php' ),
						),
					)
				);

			}
		}

	}
}
