<?php // phpcs:ignore WordPress.Files.FileName
/**
 * This class manage all plugin features
 *
 * @class   YITH_Funds
 * @author  YITH <plugins@yithemes.com>
 * @package YITH\AccountFunds\Classes
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Pelago\Emogrifier\CssInliner;
use Pelago\Emogrifier\HtmlProcessor\CssToAttributeConverter;
use Pelago\Emogrifier\HtmlProcessor\HtmlPruner;

if ( ! class_exists( 'YITH_Funds' ) ) {
	/**
	 * Class YITH_Funds
	 */
	class YITH_Funds {

		/**
		 * The unique access of the class
		 *
		 * @var YITH_Funds
		 */
		protected static $instance;
		/**
		 * This is the instance of the YITH WooCommerce Panel class.
		 *
		 * @var YIT_Plugin_Panel_WooCommerce
		 */
		protected $panel;
		/**
		 * This is the name of the panel page
		 *
		 * @var string
		 */
		protected $panel_page = 'yith_funds_panel';

		/**
		 * Check the WooCommerce version
		 *
		 * @var bool
		 */
		public $is_wc_2_7;

		/**
		 * YITH_Funds constructor.
		 */
		public function __construct() {

			$this->is_wc_2_7 = version_compare( WC()->version, '2.7.0', '>=' );

			// Load Plugin Framework.
			add_action( 'plugins_loaded', array( $this, 'load_privacy' ), 20 );
			// Add action links.
			add_filter( 'plugin_action_links_' . plugin_basename( YITH_FUNDS_DIR . '/' . basename( YITH_FUNDS_FILE ) ), array(
				$this,
				'action_links'
			) );
			// Add row meta.
			add_filter( 'yith_show_plugin_row_meta', array( $this, 'plugin_row_meta' ), 10, 5 );

			// Add action for register and update plugin.
			add_action( 'wp_loaded', array( $this, 'register_plugin_for_activation' ), 99 );
			add_action( 'wp_loaded', array( $this, 'register_plugin_for_updates' ), 99 );

			// Add YITH FUNDS menu.
			add_action( 'admin_menu', array( $this, 'add_menu' ), 5 );

			// Add admin style and script.
			add_action( 'admin_enqueue_scripts', array( $this, 'include_admin_scripts' ) );

			if ( apply_filters( 'ywf_user_enable_edit_funds', true ) ) {
				// Add deposit column in user table.
				add_action( 'manage_users_columns', array( $this, 'add_user_deposit_column' ) );
				add_action( 'manage_users_custom_column', array( $this, 'show_user_deposit_column' ), 10, 3 );
				add_action( 'yith_account_funds_user_log', array( $this, 'users_log_table' ) );
			}

			add_action( 'wp_enqueue_scripts', array( $this, 'include_frontend_scripts' ), 20 );

			// Add custom gateway.
			add_filter( 'woocommerce_payment_gateways', array( $this, 'add_gateway_funds_class' ) );
			add_action( 'widgets_init', array( $this, 'register_ywf_widgets' ) );

			$how_show = get_option( 'yith_funds_dashboard_content', array() );

			$priority = 10;
			if ( in_array( 'balance', $how_show, true ) ) {
				add_action( 'woocommerce_before_my_account', array( $this, 'show_customer_funds' ), $priority );
				$priority += 10;
			}
			if ( in_array( 'add_funds', $how_show, true ) ) {
				add_action( 'woocommerce_before_my_account', array(
					$this,
					'show_customer_make_deposit_form'
				), $priority );
				$priority += 10;
			}

			if ( in_array( 'history', $how_show, true ) ) {
				add_action( 'woocommerce_before_my_account', array(
					$this,
					'show_customer_recent_history'
				), $priority );
			}


			// Customer email.
			add_filter( 'woocommerce_email_classes', array( $this, 'add_woocommerce_emails' ) );
			add_action( 'admin_init', array( $this, 'create_deposit_product' ), 15 );
			add_filter( 'product_type_selector', array( $this, 'add_product_type' ) );
			add_filter( 'product_type_options', array( $this, 'add_type_option' ) );
			YITH_Fund_EndPoints();
			YITH_YWF_Modules::init();
			YITH_YWF_Cart_Process();
			YITH_YWF_Deposit_Fund_Checkout();
			YWF_Log();
			YITH_YWF_Order();

			add_action( 'init', array( $this, 'fund_compatibility_subscription' ), 5 );
			add_action( 'init', array( $this, 'fund_compatibility' ), 25 );


			/*GDPR integration*/

			add_filter( 'wp_privacy_personal_data_exporters', array(
				$this,
				'register_export_account_fund_info'
			), 10, 2 );
			add_filter( 'wp_privacy_personal_data_erasers', array(
				$this,
				'register_eraser_account_fund_info'
			), 10, 2 );


			$show_checkbox = get_option( 'ywf_user_privacy', 'no' );

			if ( 'yes' === $show_checkbox ) {

				add_action( 'woocommerce_edit_account_form', array( $this, 'show_checkbox' ), 15 );
				add_action( 'woocommerce_save_account_details', array( $this, 'register_customer_choose' ), 20 );
			}


			add_action( 'wp_ajax_yith_funds_edit_funds', array( $this, 'load_edit_fund_template' ) );
			add_action( 'wp_ajax_yith_funds_save_funds', array( $this, 'save_funds' ) );
			add_action( 'wp_ajax_yith_funds_update_email', array( $this, 'update_email' ) );
			add_action( 'wp_ajax_yith_funds_switch_email_activation', array( $this, 'switch_email_activation' ) );
			add_action( 'wp_ajax_yith_funds_reload_email_preview', array( $this, 'reload_email_preview' ) );

			add_action( 'yith_ywf_print_emails_tab', array( $this, 'print_emails_tab' ) );
		}

		/**
		 * Create or return the instance
		 *
		 * @return YITH_Funds
		 * @since  1.0.0
		 */
		public static function get_instance() {

			if ( is_null( self::$instance ) ) {

				self::$instance = new self();
			}

			return self::$instance;
		}

		/**
		 * Action Links.
		 * Add the action links to plugin admin page.
		 *
		 * @param array $links array with plugin links.
		 *
		 * @return array
		 * @since    1.0
		 */
		public function action_links( $links ) {

			$links = yith_add_action_links( $links, $this->panel_page, true, YITH_FUNDS_SLUG );

			return $links;
		}

		/**
		 * Plugin_row_meta.
		 *
		 * Add the action links to plugin admin page.
		 *
		 * @param array  $new_row_meta_args The new plugin meta.
		 * @param array  $plugin_meta The plugin meta.
		 * @param string $plugin_file The filename of plugin.
		 * @param array  $plugin_data The plugin data.
		 * @param string $status The plugin status.
		 * @param string $init_file The filename of plugin.
		 *
		 * @return   array
		 * @since    1.0
		 * @use plugin_row_meta
		 */
		public function plugin_row_meta( $new_row_meta_args, $plugin_meta, $plugin_file, $plugin_data, $status, $init_file = 'YITH_FUNDS_INIT' ) {

			if ( defined( $init_file ) && constant( $init_file ) === $plugin_file ) {
				$new_row_meta_args['slug']       = YITH_FUNDS_SLUG;
				$new_row_meta_args['is_premium'] = true;
			}

			return $new_row_meta_args;
		}

		/**
		 * Add a panel under YITH Plugins tab.
		 *
		 * @return   void
		 * @since    1.0
		 * @use      /Yit_Plugin_Panel class
		 * @see      plugin-fw/lib/yit-plugin-panel.php
		 */
		public function add_menu() {

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

			$admin_tabs = apply_filters(
				'yith_funds_add_tab',
				array(
					'general-settings'  => array(
						'title'       => __( 'Settings', 'yith-woocommerce-account-funds' ),
						'icon'        => 'settings',
						'description' => __( 'Set the general behaviour of the plugin', 'yith-woocommerce-account-funds' ),
					),
					'user-log-settings' => array(
						'title'       => __( 'Users & funds', 'yith-woocommerce-account-funds' ),
						'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="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z" /></svg>',
						'description' => __( 'Monitor and manage the funds of your site\'s users.', 'yith-woocommerce-account-funds' )
					),
					'emails'            => array(
						'title'       => __( 'Emails', 'yith-woocommerce-account-funds' ),
						'icon'        => 'email',
						'description' => __( 'Manage all the emails sent by the plugin.', 'yith-woocommerce-account-funds' ),
					)
				)
			);

			$args = array(
				'create_menu_page'   => true,
				'parent_slug'        => '',
				'page_title'         => 'YITH WooCommerce Account Funds',
				'plugin_description' => __( 'Let customers deposit funds in their online wallet in your store and use them at any time to proceed with faster checkout', 'yith-woocommerce-account-funds' ),
				'menu_title'         => 'Account Funds',
				'capability'         => apply_filters( 'yith_funds_menu_capability', 'manage_options' ),
				'parent'             => '',
				'parent_page'        => 'yith_plugin_panel',
				'class'              => yith_set_wrapper_class(),
				'ui_version'         => 2,
				'page'               => $this->panel_page,
				'admin-tabs'         => apply_filters( 'yith_funds_admin_tabs', $admin_tabs ),
				'options-path'       => YITH_FUNDS_DIR . '/plugin-options',
				'plugin_slug'        => YITH_FUNDS_SLUG,
				'plugin_version'     => YITH_FUNDS_VERSION,
				'plugin_icon'        => YITH_FUNDS_ASSETS_URL . 'images/plugins/account-funds.svg',
				'is_premium'         => true,
				'your_store_tools'   => array(
					'items' => array(
						'ajax-search'                   => array(
							'name'           => 'Ajax Search',
							'icon_url'       => YITH_FUNDS_ASSETS_URL . '/images/plugins/ajax-search.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-ajax-search/',
							// translators: Description of "YITH WooCommerce Ajax Search" plugin in the "Your Store Tools" tab.
							'description'    => __(
								'Add an intelligent search engine to your store so that your customers can quickly find the products they are looking for.',
								'yith-woocommerce-account-funds'
							),
							'is_active'      => defined( 'YITH_WCAS_PREMIUM' ),
							'is_recommended' => true,
						),
						'gift-cards'                    => array(
							'name'           => 'Gift Cards',
							'icon_url'       => YITH_FUNDS_ASSETS_URL . '/images/plugins/gift-card.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-gift-cards/',
							// translators: Description of "YITH WooCommerce Gift Cards" plugin in the "Your Store Tools" tab.
							'description'    => __(
								'Sell gift cards to increase your store\'s revenue and win new customers.',
								'yith-woocommerce-account-funds'
							),
							'is_active'      => defined( 'YITH_YWGC_PREMIUM' ),
							'is_recommended' => true,
						),
						'ajax-product-filter'           => array(
							'name'           => 'Ajax Product Filter',
							'icon_url'       => YITH_FUNDS_ASSETS_URL . '/images/plugins/ajax-product-filter.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-ajax-product-filter/',
							// translators: Description of "YITH WooCommerce Ajax Product Filter" plugin in the "Your Store Tools" tab.
							'description'    => __(
								'Help your customers to easily find the products they are looking for and improve the user experience of your shop.',
								'yith-woocommerce-account-funds'
							),
							'is_active'      => defined( 'YITH_WCAN_PREMIUM' ),
							'is_recommended' => false,
						),
						'wishlist'                      => array(
							'name'           => 'Wishlist',
							'icon_url'       => YITH_FUNDS_ASSETS_URL . '/images/plugins/wishlist.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-wishlist/',
							// translators: Description of "YITH WooCommerce Wishlist" plugin in the "Your Store Tools" tab.
							'description'    => __( 'Allow your customers to create lists of products they want and share them with family and friends.',
								'yith-woocommerce-account-funds'
							),
							'is_active'      => defined( 'YITH_WCWL_PREMIUM' ),
							'is_recommended' => false,
						),
						'product-addons'                => array(
							'name'           => 'Product Add-Ons & Extra Options',
							'icon_url'       => YITH_FUNDS_ASSETS_URL . '/images/plugins/product-add-ons.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-product-add-ons/',
							// translators: Description of "YITH WooCommerce Product Add-Ons & Extra Options" plugin in the "Your Store Tools" tab.
							'description'    => __(
								'Add paid or free advanced options to your product pages using fields like radio buttons, checkboxes, drop-downs, custom text inputs, and more.',
								'yith-woocommerce-account-funds'
							),
							'is_active'      => defined( 'YITH_WAPO_PREMIUM' ),
							'is_recommended' => false,
						),
						'dynamic-pricing-and-discounts' => array(
							'name'           => 'Dynamic Pricing & Discounts',
							'icon_url'       => YITH_FUNDS_ASSETS_URL . '/images/plugins/dynamic-pricing-and-discounts.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-dynamic-pricing-and-discounts/',
							// translators: Description of "YITH WooCommerce Dynamic Pricing & Discounts" plugin in the "Your Store Tools" tab.
							'description'    => __(
								'The best-selling plugin for creating promotions and upsell strategies in your store: 3x2, 2x1, BOGO, free products in the cart, quantity discounts, last-minute offers, and more.',
								'yith-woocommerce-account-funds'
							),
							'is_active'      => defined( 'YITH_YWDPD_PREMIUM' ),
							'is_recommended' => false,
						),
						'customize-my-account'          => array(
							'name'           => 'Customize My Account Page',
							'icon_url'       => YITH_FUNDS_ASSETS_URL . '/images/plugins/customize-myaccount-page.svg',
							'url'            => '//yithemes.com/themes/plugins/yith-woocommerce-customize-my-account-page/',
							// translators: Description of "YITH WooCommerce Customize My Account Page" plugin in the "Your Store Tools" tab.
							'description'    => __(
								'Customize the My Account page of your customers by creating custom sections with promotions and ad-hoc content based on your needs.',
								'yith-woocommerce-account-funds'
							),
							'is_active'      => defined( 'YITH_WCMAP_PREMIUM' ),
							'is_recommended' => false,
						),
					),
				),
				'help_tab'           => array(),
				'welcome_modals'     => array(
					'on_close' => function () {
						update_option( 'yith-funds-welcome-modal', 'no' );
					},
					'modals'   => array(
						'welcome' => array(
							'type'        => 'welcome',
							'description' => __( 'Allows your customers to buy credits which can be used to purchase your products and/or your services.', 'yith-woocommerce-account-funds' ),
							'show'        => get_option( 'yith-funds-welcome-modal', 'welcome' ) === 'welcome',
							'items'       => array(
								'documentation'    => array(
									'title'       => __( 'Read the plugin documentation', 'yith-woocommerce-account-funds' ),
									'description' => __( 'Learn what you can really do with this tool', 'yith-woocommerce-account-funds' ),
									'url'         => '//docs.yithemes.com/yith-woocommerce-account-funds/'
								),
								'add-notification' => array(
									'title'       => __( 'Set-up of the fund deposit options', 'yith-woocommerce-account-funds' ),
									'description' => __( 'and embark on this new adventure!', 'yith-woocommerce-account-funds' ),
									'url'         => add_query_arg( array(
										'page' => 'yith_funds_panel',
										'tab'  => 'general-settings'
									), admin_url( 'admin.php' ) ),
								),

							),
						)
					)
				)
			);

			if ( ! class_exists( 'YIT_Plugin_Panel_WooCommerce' ) ) {
				require_once YITH_FUNDS_DIR . 'plugin-fw/lib/yith-plugin-panel-wc.php';
			}

			$this->panel = new YIT_Plugin_Panel_WooCommerce( $args );
		}

		/**
		 * Register plugins for activation tab.
		 *
		 * @since  1.0.0
		 */
		public function register_plugin_for_activation() {
			if ( ! class_exists( 'YIT_Plugin_Licence' ) ) {
				require_once YITH_FUNDS_DIR . 'plugin-fw/licence/lib/yit-licence.php';
				require_once YITH_FUNDS_DIR . 'plugin-fw/licence/lib/yit-plugin-licence.php';
			}
			YIT_Plugin_Licence()->register( YITH_FUNDS_INIT, YITH_FUNDS_SECRET_KEY, YITH_FUNDS_SLUG );
		}

		/**
		 * Register plugins for update tab.
		 *
		 * @since  1.0.0
		 */
		public function register_plugin_for_updates() {
			if ( ! class_exists( 'YIT_Upgrade' ) ) {
				require_once YITH_FUNDS_DIR . 'plugin-fw/lib/yit-upgrade.php';
			}
			YIT_Upgrade()->register( YITH_FUNDS_SLUG, YITH_FUNDS_INIT );
		}

		/**
		 * Add custom gateway
		 *
		 * @param array $methods The gateways.
		 *
		 * @return array
		 * @since  1.0.0
		 */
		public function add_gateway_funds_class( $methods ) {

			$methods[] = 'WC_Gateway_YITH_Funds';

			return $methods;
		}


		/**
		 * Check if user profile is complete
		 *
		 * @return bool
		 * @since  1.0.0
		 */
		public function check_user_profile() {

			$billing_country         = WC()->customer->get_billing_country();
			$customer_country_fields = WC()->countries->get_address_fields( $billing_country );
			$user_id                 = get_current_user_id();
			/**
			 * The user
			 *
			 * @var WP_User $user
			 */
			$user = get_user_by( 'id', $user_id );

			foreach ( $customer_country_fields as $key => $value ) {

				if ( isset( $value['required'] ) && $value['required'] ) {

					$current_field = $user->get( $key );

					if ( empty( $current_field ) ) {
						return false;
					}
				}
			}

			return true;
		}


		/**
		 * Add deposit column in user table
		 *
		 * @param array $columns The wp table list columns.
		 *
		 * @return array
		 * @since  1.0.0
		 */
		public function add_user_deposit_column( $columns ) {

			$columns['user_deposit'] = __( 'Deposit', 'yith-woocommerce-account-funds' );

			return $columns;
		}

		/**
		 * Show user deposit in user table
		 *
		 * @param string $value The value to show.
		 * @param string $column_name The column name.
		 * @param int    $user_id The user id.
		 *
		 * @return string
		 * @since  1.0.0
		 */
		public function show_user_deposit_column( $value, $column_name, $user_id ) {

			if ( 'user_deposit' === $column_name ) {

				$customer = new YITH_YWF_Customer( $user_id );
				$funds    = apply_filters( 'yith_admin_user_deposit_column', $customer->get_funds() );
				$value    = wc_price( $funds );

				$show_log_params = array(
					'page'    => 'yith_funds_panel',
					'user_id' => $user_id,
					'tab'     => 'user-log-settings',
					'action'  => 'update',
				);

				$show_log_link       = esc_url( add_query_arg( $show_log_params, admin_url( 'admin.php' ) ) );
				$actions['show_log'] = sprintf( '<a href="%s">%s</a>', $show_log_link, __( 'Show logs', 'yith-woocommerce-account-funds' ) );

				$value .= $this->row_actions( $actions );
			}

			return $value;
		}

		/**
		 * Show the row action in user fund table
		 *
		 * @param array $actions The actions.
		 * @param bool  $always_visible If is visible.
		 *
		 * @return string
		 */
		public function row_actions( $actions, $always_visible = false ) {
			$action_count = count( $actions );
			$i            = 0;

			if ( ! $action_count ) {
				return '';
			}

			$out = '<div class="' . ( $always_visible ? 'row-actions visible' : 'row-actions' ) . '">';
			foreach ( $actions as $action => $link ) {
				++ $i;
				$sep = ( $i === $action_count ) ? '' : ' | ';
				$out = $out . "<span class='$action'>$link$sep</span>";
			}
			$out .= '</div>';

			$out .= '<button type="button" class="toggle-row"><span class="screen-reader-text">' . __( 'Show more details' ) . '</span></button>';

			return $out;
		}

		/**
		 * Register the widgets
		 *
		 * @since  1.0.0
		 */
		public function register_ywf_widgets() {
			require_once 'includes/widgets/class.yith-ywf-make-a-deposit-widget.php';
			require_once 'includes/widgets/class.yith-ywf-view-user-funds-widget.php';
			register_widget( 'YITH_YWF_Make_a_Deposit_Widget' );
			register_widget( 'YITH_YWF_View_User_Funds_Widget' );
		}


		/**
		 * Include admin style and script
		 *
		 * @since  1.0.0
		 */
		public function include_admin_scripts() {

			$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';

			wp_register_style( 'ywf_admin_email', YITH_FUNDS_ASSETS_URL . 'css/ywf-admin-emails.css', array(), YITH_FUNDS_VERSION );
			wp_register_script( 'ywf_admin_email', YITH_FUNDS_ASSETS_URL . 'js/' . yit_load_js_file( 'ywf-admin-emails.js' ), array( 'jquery' ), YITH_FUNDS_VERSION, true );
			$email_args = array(
				'ajax_url' => admin_url( 'admin-ajax.php', is_ssl() ? 'https' : 'http' ),
				'actions'  => array(
					'update_email'            => 'yith_funds_update_email',
					'switch_email_activation' => 'yith_funds_switch_email_activation',
					'reload_email_preview'    => 'yith_funds_reload_email_preview',
				),
				'nonces'   => array(
					'update_email'            => wp_create_nonce( 'yith-funds-update-email' ),
					'switch_email_activation' => wp_create_nonce( 'yith-funds-switch-email-activation' ),
					'reload_email_preview'    => wp_create_nonce( 'yith-funds-reload-email-preview' ),
				)
			);

			wp_localize_script( 'ywf_admin_email', 'ywf_admin_email', $email_args );
			if ( isset( $_GET['page'] ) && 'yith_funds_panel' === wp_unslash( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
				$is_customize_active = defined( 'YITH_WCMAP_PREMIUM' ) && YITH_WCMAP_PREMIUM;
				wp_enqueue_script( 'ywf_admin_script', YITH_FUNDS_ASSETS_URL . 'js/ywf-admin' . $suffix . '.js', array( 'jquery' ), YITH_FUNDS_VERSION, true );

				$params = apply_filters( 'yith_funds_js_params', array(
						'ajax_url'            => admin_url( 'admin-ajax.php', is_ssl() ? 'https' : 'http' ),
						'actions'             => array(
							'edit_funds' => 'yith_funds_edit_funds',
							'save_funds' => 'yith_funds_save_funds',
						),
						'nonces'              => array(
							'edit_funds' => wp_create_nonce( 'yith-funds-edit-funds' ),
							'save_funds' => wp_create_nonce( 'yith-funds-save-funds' ),
						),
						'editModal'           => array(
							// translators: %s is the username.
							'title' => __( 'Edit Funds for %s', 'yith-woocommerce-account-funds' ),
						),
						'is_customize_active' => $is_customize_active,
						'wc_currency'         => get_woocommerce_currency_symbol(),
					)
				);
				wp_localize_script( 'ywf_admin_script', 'ywf_admin', $params );

				wp_enqueue_style( 'ywf_admin_style', YITH_FUNDS_ASSETS_URL . 'css/ywf_backend.css', array(), YITH_FUNDS_VERSION );
				wp_enqueue_style( 'ywf_admin_email' );
				wp_enqueue_script( 'ywf_admin_email' );
			}

			if ( isset( $_GET['page'] ) && $_GET['page'] == 'wc-settings' && isset( $_GET['tab'] ) && $_GET['tab'] == 'email' ) {
				wp_enqueue_style( 'ywf_admin_email' );
				wp_enqueue_script( 'ywf_admin_email' );
			}
			if ( ( isset( $_GET['post'] ) && get_post_type( wp_unslash( $_GET['post'] ) ) === 'shop_order' ) || ( isset( $_GET['page'], $_GET['action'] ) && 'wc-orders' === $_GET['page'] && 'edit' === $_GET['action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
				wp_enqueue_script( 'ywf_order_admin_script', YITH_FUNDS_ASSETS_URL . 'js/ywf-order-admin' . $suffix . '.js', array( 'jquery' ), YITH_FUNDS_VERSION, true );

				$params = array(
					'ajax_url' => admin_url( 'admin-ajax.php', is_ssl() ? 'https' : 'http' ),
					'messages' => array(
						'tot_av_refund_tip'    => __( 'You cannot refund an amount greater than user\'s total funds available.', 'yith-woocommerce-account-funds' ),
						'error_message_refund' => __( 'Attention! User\'s current funds are lower than the amount you are entering', 'yith-woocommerce-account-funds' ),
						'no_automatic_refund'  => __( 'Attention! It is not possible to refund this order automatically because it was partially paid with funds. Only the manual refund option is available.', 'yith-woocommerce-account-funds' ),
						'error_wrong_funds'    => __( 'Attention! It is not possible to set a value < 0', 'yith-woocommerce-account-funds' ),
					),
					'actions'  => array(
						'add_funds' => 'add_funds',
					),
				);
				wp_localize_script( 'ywf_order_admin_script', 'ywf_params', $params );
			}
		}

		/**
		 * Include style and script
		 *
		 * @since  1.0.0
		 */
		public function include_frontend_scripts() {

			$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';

			wp_enqueue_style( 'ywf_style', YITH_FUNDS_ASSETS_URL . 'css/ywf_frontend.css', array(), YITH_FUNDS_VERSION );
			wp_register_style( 'ywf-shortcodes', YITH_FUNDS_ASSETS_URL . 'css/ywf-shortcodes.css', array(), YITH_FUNDS_VERSION );
			wp_register_script( 'ywf_script', YITH_FUNDS_ASSETS_URL . 'js/ywf-frontend' . $suffix . '.js', array( 'jquery' ), YITH_FUNDS_VERSION, true );
			$params = array(
				'min'         => wc_format_decimal( ywf_get_min_fund_rechargeable() ),
				'max'         => ywf_get_max_fund_rechargeable(),
				'step'        => get_option( 'yith_funds_step', 1 ),
				'minDepError' => sprintf( _x( 'Minimum required for funds deposit: %s', 'Minimum required for funds deposit: $70', 'yith-woocommerce-account-funds' ), wc_price( ywf_get_min_fund_rechargeable() ) ),
				'maxDepError' => sprintf( _x( 'Maximum allowed for funds deposit: %s', 'Maximum allowed for funds deposit: $170', 'yith-woocommerce-account-funds' ), wc_price( ywf_get_max_fund_rechargeable() ) ),
			);
			wp_localize_script( 'ywf_script', 'ywf_frontend', $params );

			if ( is_account_page() ) {
				wp_enqueue_style( 'ywf-shortcodes' );
				wp_enqueue_script( 'ywf_script' );
			}
			global $post;
			$gateway = get_option( 'ywf_select_gateway', array() );
			$gateway = ! is_array( $gateway ) ? array() : $gateway;
			if ( has_block( 'woocommerce/checkout', $post ) && count( $gateway ) > 0 ) {
				$deps = include YITH_FUNDS_DIR . 'assets/js/wc-blocks/available-gateways/index.asset.php';

				wp_enqueue_script(
					'yith-funds-available-gateway',
					YITH_FUNDS_ASSETS_URL . 'js/wc-blocks/available-gateways/index.js',
					$deps['dependencies'],
					$deps['version'],
					true
				);


				wp_localize_script( 'yith-funds-available-gateway', 'yith_allowed_gateway_args', array(
					'gateways'           => $gateway,
					'deposit_product_id' => apply_filters('translate_object_id', get_option( '_ywf_deposit_id' ) , 'product' ),
					'all_gateways'       => array_keys( WC()->payment_gateways()->get_available_payment_gateways() )
				) );
			}


		}

		/**
		 * Add custom email class
		 *
		 * @param array $emails The WooCommerce emails.
		 *
		 * @return array
		 * @since  1.0.0
		 */
		public function add_woocommerce_emails( $emails ) {

			require_once YITH_FUNDS_INC . '/emails/class.yith-ywf-email.php';

			$emails['YITH_YWF_Customer_Email']        = include YITH_FUNDS_INC . 'emails/class.yith-ywf-customer-email.php';
			$emails['YITH_YWF_Advise_Customer_Email'] = include YITH_FUNDS_INC . 'emails/class.yith-ywf-advise-customer-email.php';

			return apply_filters( 'ywf_woocommerce_emails', $emails );
		}

		/**
		 * Show the users log table in admin
		 *
		 * @since  1.0.0
		 */
		public function users_log_table() {

			require_once YITH_FUNDS_TEMPLATE_PATH . 'admin/user-log-table.php';

		}


		/**
		 * Initialize compatibility class
		 *
		 * @since  1.0.1
		 */
		public function fund_compatibility() {
			YITH_FUNDS_Compatibility();
		}

		/**
		 * Add the integration with YITH WooCommerce Subscription plugin.
		 *
		 * @since  1.1.2
		 */
		public function fund_compatibility_subscription() {
			/**YITH WooCommerce Subscription*/
			if ( defined( 'YITH_YWSBS_PREMIUM' ) && version_compare( YITH_YWSBS_VERSION, '1.5.2', '>' ) ) {
				require_once YITH_FUNDS_INC . 'compatibility/yith-woocommerce-subscription/class.yith-funds-yith-subscription-integration.php';
				require_once YITH_FUNDS_INC . 'compatibility/yith-woocommerce-subscription/class.yith-funds-yith-subscription.php';
				YITH_Funds_YITH_Subscription_Integration();
			}elseif ( defined( 'BH_SUBSCRIPTIONS_VERSION' ) ) {
				require_once YITH_FUNDS_INC . 'compatibility/bh-subscriptions/class.yith-funds-bh-subscriptions-integration.php';
				require_once YITH_FUNDS_INC . 'compatibility/bh-subscriptions/class.yith-funds-bh-subscriptions.php';
				YITH_Funds_BH_Subscriptions_Integration();
			}
		}


		/**
		 * Create the default deposit product
		 *
		 * @since  1.0.0
		 */
		public function create_deposit_product() {

			$deposit_id       = get_option( '_ywf_deposit_id', - 1 );
			$deposit_image_id = get_option( '_ywf_deposit_image_id', false );
			$deposit_product  = wc_get_product( $deposit_id );

			if ( - 1 === intval( $deposit_id ) || ! $deposit_product ) {

				$deposit_id = wp_insert_post(
					array(
						'post_title'   => _x( 'Funds deposit', 'Is the default product name','yith-woocommerce-account-funds' ),
						'post_type'    => 'product',
						'post_status'  => 'private',
						'post_content' => __( 'This product has been created by YITH Account Funds Plugin, please not remove', 'yith-woocommerce-account-funds' ),
					)
				);

				wp_set_object_terms( $deposit_id, 'ywf_deposit', 'product_type' );

				$product = wc_get_product( $deposit_id );

				$product->set_sold_individually( 'yes' );
				$product->set_virtual( 'yes' );
				$product->set_catalog_visibility( 'hidden' );
				$product->save();
				update_option( '_ywf_deposit_id', $deposit_id );
			}

			if ( ! $deposit_product->get_image_id() ) {

				if ( ! $deposit_image_id ) {
					$deposit_image_id = yith_funds_upload_product_image();
					update_option( '_ywf_deposit_image_id', $deposit_image_id );
				}
				if ( $deposit_image_id ) {
					$deposit_product->set_image_id( $deposit_image_id );
					$deposit_product->save();
				}
			}

		}

		/**
		 * Add the custom product type
		 *
		 * @param array $product_type The supported product type.
		 *
		 * @return array
		 * @since  1.0.0
		 */
		public function add_product_type( $product_type ) {

			$product_type['ywf_deposit'] = __( 'Deposit', 'yith-woocommerce-account-funds' );

			return $product_type;
		}

		/**
		 * Add in the product metabox a custom class
		 *
		 * @param array $array The metabox classes.
		 *
		 * @return array
		 * @since  1.0.0
		 */
		public function add_type_option( $array ) {
			if ( isset( $array['virtual'] ) ) {
				$css_class     = $array['virtual']['wrapper_class'];
				$add_css_class = 'show_if_ywf_deposit';
				$class         = empty( $css_class ) ? $add_css_class : $css_class .= ' ' . $add_css_class;

				$array['virtual']['wrapper_class'] = $class;
			}
			if ( isset( $array['downloadable'] ) ) {
				$css_class     = $array['downloadable']['wrapper_class'];
				$add_css_class = 'show_if_ywf_deposit';
				$class         = empty( $css_class ) ? $add_css_class : $css_class .= ' ' . $add_css_class;

				$array['downloadable']['wrapper_class'] = $class;
			}

			return $array;
		}

		/**
		 * Register export action
		 *
		 * @param array $exporters The GDPR exporters.
		 *
		 * @return array
		 * @since  1.0.22
		 */
		public function register_export_account_fund_info( $exporters ) {

			$exporters['ywsfl-export-list'] = array(
				'exporter_friendly_name' => __( 'Account Funds Info', 'yith-woocommerce-account-funds' ),
				'callback'               => array(
					$this,
					'export_account_fund_info',
				),
			);

			return $exporters;
		}

		/**
		 * Export account fund info
		 *
		 * @param string $email_address The user email.
		 * @param int    $page The current page number.
		 *
		 * @return array
		 * @since  1.0.22
		 *
		 */
		public function export_account_fund_info( $email_address, $page = 1 ) {
			$data_to_export = array();

			$user = get_user_by( 'email', $email_address );

			$account_info = array();
			if ( $user instanceof WP_User ) {

				$user_id = $user->ID;

				global $wpdb;

				$table_name = $wpdb->prefix . 'ywf_user_fund_log';
				$query      = $wpdb->prepare( "SELECT type_operation, COUNT(*) as total_op, SUM( ABS( fund_user ) ) as total FROM {$table_name} WHERE user_id = %d GROUP BY type_operation", $user_id ); //phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared

				$list = $wpdb->get_results( $query, ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared

				if ( count( $list ) > 0 ) {
					$type_operation = ywf_get_operation_type();

					foreach ( $list as $data ) {

						$type_operation_name = isset( $type_operation[ $data['type_operation'] ] ) ? $type_operation[ $data['type_operation'] ] : 'N/A';
						$total_info          = __( 'for a total of ', 'yith-woocommerce-account_funds' );
						$value               = sprintf( '%d x %s %s %s', $data['total_op'], _n( $type_operation_name, $type_operation_name . 's', $data['total_op'], 'yith-woocommerce-account-funds' ), $total_info, wc_price( $data['total'] ) ); // phpcs:ignore
						$account_info[]      = array(
							'name'  => $type_operation_name,
							'value' => $value,
						);

					}
				}

				$available_funds = get_user_meta( $user_id, '_customer_fund', true );

				$account_info[] = array(
					'name'  => __( 'Available fund', 'yith-woocommerce-account-funds' ),
					'value' => wc_price( $available_funds ),
				);

			}
			$data_to_export[] = array(
				'group_id'    => 'ywf_fund_info',
				'group_label' => __( 'Account Funds Log', 'yith-woocommerce-account-funds' ),
				'data'        => $account_info,
				'item_id'     => 'account_fund_id',
			);

			return array(
				'data' => $data_to_export,
				'done' => true,
			);

		}

		/**
		 * Register the eraser fund information
		 *
		 * @param array $erasers The erasers.
		 *
		 * @return array
		 * @since  1.0.22
		 */
		public function register_eraser_account_fund_info( $erasers ) {

			$erasers['ywsfl-export-list'] = array(
				'eraser_friendly_name' => __( 'Account funds', 'yith-woocommerce-account-funds' ),
				'callback'             => array(
					$this,
					'eraser_account_fund_info',
				),
			);

			return $erasers;

		}


		/**
		 * Erase the info
		 *
		 * @param string $email_address The user email.
		 * @param int    $page The current page id.
		 *
		 * @return array
		 * @since  1.0.22
		 */
		public function eraser_account_fund_info( $email_address, $page = 1 ) {

			$response = array(
				'items_removed'  => false,
				'items_retained' => false,
				'messages'       => array(),
				'done'           => true,
			);

			$user = get_user_by( 'email', $email_address ); // Check if user has an ID in the DB to load stored personal data.

			if ( ! $user instanceof WP_User ) {
				return $response;
			}

			$user_id = $user->ID;

			global $wpdb;

			$deleted = $wpdb->delete( $wpdb->prefix . 'ywf_user_fund_log', array( 'user_id' => $user_id ), array( '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery

			if ( $deleted > 0 ) {
				$response['items_removed'] = true;
				$response['messages'][]    = sprintf( '%d %s', $deleted, _n( 'Item removed from Account Fund log', 'Items removed from Account Fund log', $deleted, 'yith-woocommerce-account-funds' ) );
			}

			delete_user_meta( $user_id, '_customer_fund' );

			$response['messages'][] = __( 'Removed user meta _customer_fund properly', 'yith-woocommerce-account-funds' );

			return $response;
		}

		/**
		 * Add a checkbox in my account
		 *
		 * @since  YITH
		 */
		public function show_checkbox() {

			wc_get_template( 'ywf-email-checkbox-agree.php', array(), '', YITH_FUNDS_TEMPLATE_PATH . 'woocommerce/myaccount/' );
		}

		/**
		 * Save the customer choose
		 *
		 * @param int $user_id The user d.
		 *
		 */
		public function register_customer_choose( $user_id ) {

			$agree_choose = isset( $_POST['ywf_agree_send_email'] ); // phpcs:ignore

			update_user_meta( $user_id, '_ywf_agree_to_send_email', $agree_choose );
		}

		/**
		 * Show the privacy policy
		 *
		 * @since  1.0.0
		 */
		public function load_privacy() {
			require_once YITH_FUNDS_INC . '/class.yith-ywf-privacy-policy.php';
		}

		/**
		 * Return the edit fund template
		 * @return void
		 * @since 2.0.0
		 */
		public function load_edit_fund_template() {
			check_ajax_referer( 'yith-funds-edit-funds', 'security' );

			$user_id = isset( $_POST['user_id'] ) ? wp_unslash( sanitize_text_field( $_POST['user_id'] ) ) : '';
			if ( ! empty( $user_id ) ) {
				ob_start();
				include YITH_FUNDS_TEMPLATE_PATH . 'admin/user-edit-fund.php';
				$template = ob_get_clean();
				wp_send_json_success( $template );
			}
			wp_send_json_error();
		}

		public function save_funds() {
			check_ajax_referer( 'yith-funds-save-funds', 'security' );

			global $sitepress;

			$user_id = isset( $_POST['user_id'] ) ? wp_unslash( sanitize_text_field( $_POST['user_id'] ) ) : '';
			$funds   = isset( $_POST['funds'] ) ? floatVal( wp_unslash( sanitize_text_field( $_POST['funds'] ) ) ) : 0;
			$desc    = ! empty( $_POST['desc'] ) ? wp_unslash( sanitize_text_field( $_POST['desc'] ) ) : 'admin edit';

			if ( ! empty( $user_id ) ) {
				$fund_user = new YITH_YWF_Customer( $user_id );
				$old_funds = floatval( $fund_user->get_funds() );

				if ( $funds !== $old_funds ) {
					$diff_funds = $funds - $old_funds;

					$fund_user->set_funds( $funds );

					$log_args = array(
						'user_id'        => $user_id,
						'editor_id'      => get_current_user_id(),
						'type_operation' => 'admin_op',
						'fund_user'      => $diff_funds,
						'description'    => $desc,
					);

					$user = get_user_by( 'id', $user_id );


					$order_id = ywf_get_user_currency( $user_id );
					$order    = wc_get_order( $order_id );

					if ( $order ) {
						$currency = $order->get_currency();
						$lang = $sitepress ? $order->get_meta('wpml_language' ) : false;
					} else {
						$currency = get_woocommerce_currency();
						$lang = false;

					}

					$before_funds = apply_filters( 'yith_fund_into_customer_email', $old_funds, $currency );
					$after_funds  = apply_filters( 'yith_fund_into_customer_email', $funds, $currency );
					$email_data   = array(
						'user'       => array(
							'customer_name'      => $user->get( 'billing_first_name' ),
							'customer_last_name' => $user->get( 'billing_last_name' ),
							'customer_email'     => $user->get( 'billing_email' ),
							'user_id'            => $user_id,
						),
						'user_funds' => array(
							'before_funds_formatted' => wc_price( $before_funds, array( 'currency' => $currency ) ),
							'after_funds_formatted'  => wc_price( $after_funds, array( 'currency' => $currency ) ),
							'change_reason'          => $desc,
							'log_date'               => date_i18n( wc_date_format(), gmdate( wc_date_format() ) ),
						),
						'language' => $lang
					);

					WC()->mailer();
					do_action( 'ywf_send_advise_user_fund_email_notification', $email_data );
					YWF_Log()->add_log( $log_args );
				}
			}

			$message = yith_plugin_fw_get_component(
				array(
					'type'        => 'notice',
					'notice_type' => 'success',
					'message'     => __( 'User funds edited successfully', 'yith-woocommerce-account-funds' ),
				),
				false
			);
			wp_send_json_success( $message );
		}

		/**
		 * Show user balance in dashboard
		 *
		 * @return void
		 */
		public function show_customer_funds() {
			echo '<div class="yith-funds-dashboard">';
			echo apply_shortcodes( '[yith_ywf_show_user_fund layout="inline"]' );
			echo '</div>';
		}

		/**
		 * Show make deposit in dashboard
		 *
		 * @return void
		 */
		public function show_customer_make_deposit_form() {
			echo '<div class="yith-funds-dashboard">';
			echo apply_shortcodes( '[yith_ywf_make_a_deposit_form]' );
			echo '</div>';
		}

		/**
		 * Show funds history in dashboard
		 *
		 * @return void
		 */
		public function show_customer_recent_history() {
			echo '<div class="yith-funds-dashboard">';
			echo apply_shortcodes( '[yith_ywf_show_history per_page="5" show_all="yes" show_filter="no"]' );
			echo '</div>';
		}

		/**
		 * Return true if is a plugin email.
		 *
		 * @param string $email_class The email class name.
		 *
		 * @return bool
		 * @since  2.0.0
		 */
		private function is_plugin_email( string $email_class ): bool {
			return 0 === strpos( $email_class, 'YITH_YWF_' );
		}

		/**
		 * Show the custom email tab
		 *
		 * @return void
		 */
		public function print_emails_tab() {
			$mailer             = wc()->mailer();
			$woocommerce_emails = $mailer->get_emails();
			$emails             = array_filter(
				$woocommerce_emails,
				function ( $value, $key ) {
					return $this->is_plugin_email( $key );
				},
				ARRAY_FILTER_USE_BOTH
			);

			include YITH_FUNDS_TEMPLATE_PATH . 'admin/emails-tab.php';
		}

		/**
		 * Update the email
		 *
		 * @return void
		 */
		public function update_email() {
			check_ajax_referer( 'yith-funds-update-email', 'security' );
			$email_class_name   = sanitize_text_field( wp_unslash( $_REQUEST['email'] ?? '' ) );
			$data               = wp_unslash( $_REQUEST['data'] ?? array() ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			$mailer             = wc()->mailer();
			$woocommerce_emails = $mailer->get_emails();

			if ( ! $this->is_plugin_email( $email_class_name ) || ! in_array( $email_class_name, array_keys( $woocommerce_emails ), true ) ) {
				wp_send_json_error();
			}

			$email       = $woocommerce_emails[ $email_class_name ];
			$enabled_key = $email->get_field_key( 'enabled' );
			if ( $email->is_enabled() ) {
				$data[ $enabled_key ] = 1;
			} else {
				unset( $data[ $enabled_key ] );
			}
			$data['ywf_panel'] = 'yes';

			$email->set_post_data( $data );
			$email->process_admin_options();

			wp_send_json_success();
		}

		/**
		 * Toggle enable email
		 *
		 * @return void
		 */
		public function switch_email_activation() {
			check_ajax_referer( 'yith-funds-switch-email-activation', 'security' );
			$email_class_name   = sanitize_text_field( wp_unslash( $_REQUEST['email'] ?? '' ) );
			$enabled            = sanitize_title( wp_unslash( $_REQUEST['enabled'] ?? '' ) );
			$mailer             = wc()->mailer();
			$woocommerce_emails = $mailer->get_emails();

			if ( ! $this->is_plugin_email( $email_class_name ) || ! in_array( $email_class_name, array_keys( $woocommerce_emails ), true ) || ! in_array( $enabled, array(
					'yes',
					'no'
				), true ) ) {
				wp_send_json_error();
			}

			$email = $woocommerce_emails[ $email_class_name ];
			$data  = array();

			foreach ( $email->get_form_fields() as $key => $field ) {
				if ( 'title' !== $email->get_field_type( $field ) ) {
					$field_key  = $email->get_field_key( $key );
					$field_type = $email->get_field_type( $field );
					$value      = $email->settings[ $key ] ?? $field['default'] ?? '';

					if ( 'checkbox' === $field_type ) {
						if ( 'yes' === $value ) {
							$data[ $field_key ] = 1;
						}
					} else {
						$data[ $field_key ] = $value;
					}
				}
			}

			$field_key = $email->get_field_key( 'enabled' );
			if ( 'yes' === $enabled ) {
				$data[ $field_key ] = 1;
			} else {
				unset( $data[ $field_key ] );
			}

			$email->set_post_data( $data );
			$email->process_admin_options();

			wp_send_json_success();

		}

		/**
		 * Reload the email template
		 *
		 * @return void
		 */
		public function reload_email_preview() {
			check_ajax_referer( 'yith-funds-reload-email-preview', 'security' );
			$email_class_name   = sanitize_text_field( wp_unslash( $_REQUEST['email'] ?? '' ) );
			$mail_body          = wp_kses_post( wp_unslash( $_REQUEST['body'] ?? '' ) );
			$mail_heading       = wp_kses_post( wp_unslash( $_REQUEST['heading'] ?? '' ) );
			$custom_data        = array(
				'body'    => $mail_body,
				'heading' => $mail_heading,
			);
			$mailer             = wc()->mailer();
			$woocommerce_emails = $mailer->get_emails();

			if ( ! $this->is_plugin_email( $email_class_name ) || ! in_array( $email_class_name, array_keys( $woocommerce_emails ), true ) ) {
				wp_send_json_error();
			}

			$email         = $woocommerce_emails[ $email_class_name ];
			$email->object = array_merge( yith_ywf_get_test_values( $email->id ), $custom_data );
			$email->init_placeholders_before_sending();
			$content = $email->get_content();

			ob_start();
			wc_get_template( 'emails/email-styles.php' );
			$css = apply_filters( 'woocommerce_email_styles', ob_get_clean(), $email );

			try {
				$css_inliner = CssInliner::fromHtml( $content )->inlineCss( $css );

				do_action( 'woocommerce_emogrifier', $css_inliner, $email );

				$dom_document = $css_inliner->getDomDocument();

				HtmlPruner::fromDomDocument( $dom_document )->removeElementsWithDisplayNone();
				$content = CssToAttributeConverter::fromDomDocument( $dom_document )->convertCssToVisualAttributes()->render();
			} catch ( Exception $e ) {
				error_log( $e->getMessage() );
			}

			$content = yith_ywf_prune_preview_email_content( $content );

			wp_send_json_success( $content );
		}
	}
}

