<?php

namespace PPU\Helpers;

if ( ! defined( 'ABSPATH' ) ) :
	exit; // Exit if accessed directly.
endif;
/** Class containing WPML serving functions */
if ( !class_exists( 'PPU\Helpers\WPMLHelper' ) ) {
	class WPMLHelper {

		public $hook_priority = 1010;
		/** Class instance */
		private static $instance = null;

		/**
		 * Returns instance of the class.
		 *
		 * @since 2.1.2
		 */
		public static function get_instance() {
			if ( null == self::$instance ) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		/**
         * The Constructor!
         *
         * @since 2.1.2
         */
        public function __construct()
        {
            $hook_priority = intval(get_option('_mcmp_ppu_hook_priority'));
            if(!empty($hook_priority)) {
                $this->hook_priority = $hook_priority;
			}
			// Handling global options strings.
			add_filter( 'woocommerce_admin_settings_sanitize_option', array( $this, 'ppu_handle_general_options_strings' ), 10, 3 );
			// Adding strings to translation.
			add_action( 'mcmp_ppu_reregister_wpml_strings', array( $this, 'ppu_reregister_wpml_strings' ), 10, 4 );
			// Translation of the weight option name.
			add_filter( 'mcmp_ppu_translate_wpml_reg_string', array( $this, 'ppu_translate_wpml_reg_string' ), 10, 3 );
			// Runs WPML string maintenance on Ajax button.
			add_action( 'wp_ajax_run_ppu_wpml_strings_maintenance', array($this, 'wpml_strings_maintenance'));
			// Reregisters all WPML related options.
			add_action( 'mcmp_ppu_wpml_reregister_ppu_options', array( $this, 'wpml_reregister_ppu_options' ), 10, 4 );
		}

		/**
		 * Handles general settings modification
		 * Used for WPML updating strings
		 *
		 * @param mixed $value - Option value - filtered.
		 * @param array $option - Option data.
		 * @param mixed $raw_value - Option value - unfiltered.
		 * @return mixed
		 * @since 2.1.2
		 */
		public function ppu_handle_general_options_strings( $value, $option, $raw_value ) {
			if ( '_mcmp_ppu_recalc_text_options' === $option['id'] ) {
				do_action( 'mcmp_ppu_reregister_wpml_strings', 'Price per Unit PRO', 'Predefined Recalculated price suffix text', $value, true );
			}
			if ( '_mcmp_ppu_custom_unit_options' === $option['id'] ) {
				do_action( 'mcmp_ppu_reregister_wpml_strings', 'Price per Unit PRO', 'Predefined custom units names', $value, true );
			}
			return $value;
		}
	
		/**
		 * Registers weight options in WPML strings for translation
		 *
		 * @since 2.1.2
		 * @param string $context - WPML domain of the plugin.
		 * @param string $name - Name of the option under which the string will be registered.
		 * @param string $options - String of options to register in WPML.
		 * @param string $delete_strings - Decides if the WPML Predefined weight options strings not contained in the other setting should be deleted.
		 */
		public function ppu_reregister_wpml_strings( $context, $name, $options, $delete_strings = false ) {
			$registered_options = $this->ppu_get_wpml_registered_strings( $context, $name );
			$options = empty( $options ) ? array() : explode( '|', $options );
			if ( $registered_options !== $options ) {
				if ( true === $delete_strings && function_exists( 'icl_unregister_string' ) ) {
					$del_strings = array_diff( $registered_options, $options );
					foreach ( $del_strings as $string ) {
						icl_unregister_string( $context, $name . ' [' . $string . ']' );
					}
				}
				$add_strings = array_diff( $options, $registered_options );
				foreach ( $add_strings as $string ) {
					do_action( 'wpml_register_single_string', $context, $name . ' [' . $string . ']', $string );
				}
			}
		}

		public function ppu_get_wpml_strings_names($context, $name, $exact = false) {
			global $wpdb;
			$escaped_name = $wpdb->esc_like($name);
			if( false === $exact){
				$escaped_name .= '%';
				$sql_prep = $wpdb->prepare( "SELECT name FROM {$wpdb->prefix}icl_strings
						WHERE context=%s AND name LIKE %s", $context, $escaped_name);
			}else{
				$sql_prep = $wpdb->prepare( "SELECT name FROM {$wpdb->prefix}icl_strings
						WHERE context=%s AND name=%s",	$context, $escaped_name	);
			}
			$reg_strings = $wpdb->get_results($sql_prep, ARRAY_A);
			if( $reg_strings ){
				return array_column( $reg_strings, 'name' );
			}
		}

		public function ppu_get_wpml_registered_strings( $context, $name, $exact = false ) {
			$registered_strings = $this->ppu_get_wpml_strings_names( $context, $name, $exact );
			if( !empty( $registered_strings ) ){
				$registered_strings =  array_map(
					function( $strings ) {
						$from = strpos( $strings, '[');
						$from = false == $from ? 0 : $from + 1;
						$to = strpos( $strings, ']');
						$to = false == $to ? 0 : $to - $from ;
						$return = substr ( $strings , $from, $to );
						return $return;
					},
					$registered_strings
				);
			}else{
				$registered_strings = array();
			}
			return $registered_strings;
		}

		public function mcmp_del_wpml_strings_by_domain($context) {
			global $wpdb;
			$sql_prep = $wpdb->prepare( "DELETE FROM {$wpdb->prefix}icl_strings
				WHERE context=%s", $context);
			$wpdb->query($sql_prep);
		}
	
		/**
		 * Translates string of selected option with WPML
		 *
		 * @since 2.1.2
		 * @param string $context - WPML domain of the plugin.
		 * @param string $name - Name of the option under which the string will be registered.
		 * @param string $string - The registered option string.
		 * @return string Translated option text - if not found, then the original.
		 */
		public function ppu_translate_wpml_reg_string( $string, $context, $name ) {
			$key  = $name . ' [' . $string . ']';
			$string = apply_filters( 'wpml_translate_single_string', $string, $context, $key );
			return $string;
		}
		/**
		 * Runs AJAX on script
		 * @since 2.1.2
		 */
		public function wpml_strings_maintenance()
		{
			do_action( 'mcmp_ppu_wpml_reregister_ppu_options');
			esc_html_e( 'WPML strings maintenance finished!', 'woo-price-per-unit-pro' );
			wp_die();
		}

		/**
		 * Re-registers all PPU options in WPML
		 * @since 2.1.2
		 */
		public function wpml_reregister_ppu_options()
		{
			$options = get_option( '_mcmp_ppu_custom_unit_options' );
			$this->ppu_reregister_wpml_strings('Price per Unit PRO', 'Predefined custom units names', $options, true );
			$options = get_option( '_mcmp_ppu_recalc_text_options' );
			$this->ppu_reregister_wpml_strings('Price per Unit PRO', 'Predefined Recalculated price suffix text', $options, true );
		}

	}
}
return WPMLHelper::get_instance();