<?php
/**
 * Get list of default widgets names
 * @return array
 */
function ysm_get_default_widgets_ids() {
	$list = array();

	if ( defined( 'AVADA_VERSION' ) ) {
		$list['avada'] = 'avada';
	}

	$list['product'] = 'product';
	$list['default'] = 'default';

	return $list;
}

/**
 * Get list of default widgets names
 * @param string $id
 * @return array|string
 */
function ysm_get_default_widgets_names( $id = '' ) {
	$list = array(
		'default' => __( 'WordPress Default Search Widget', 'smart-woocommerce-search' ),
		'product' => __( 'WooCommerce Product Search Widget', 'smart-woocommerce-search' ),
		'avada'   => __( 'Avada Search Widget', 'smart-woocommerce-search' ),
		'divi'    => __( 'DIVI Search Widget', 'smart-woocommerce-search' ),
	);

	if ( '' !== $id ) {
		if ( isset( $list[ $id ] ) ) {
			return $list[ $id ];
		} else {
			return '';
		}
	}

	return $list;
}

/**
 * Get option by $id
 * @param $w_id
 * @param $id
 * @return string|null
 */
function ysm_get_option( $w_id, $id ) {
	return Ysm_Widget_Manager::get( $w_id, $id );
}

/**
 * Get setting output
 * @param $w_id
 * @param $id
 * @param $args
 */
function ysm_setting( $w_id, $id, $args ) {

	$value = ysm_get_option( $w_id, $id );

	if ( null !== $value ) {
		$args['value'] = $value;
	}

	\YummyWP\App\Field::output( $id, $args );
}

/**
 * Add messages and errors
 * @param $text
 * @param string $type
 */
function ysm_add_message( $text, $type = 'message' ) {
	\YummyWP\App\Notification::add( $text, $type );
}

/**
 * Retrieve custom widgets list row template
 * @param array $args
 * @return string
 */
function ysm_get_widget_list_row_template( $args ) {

	$id               = $args['id'];
	$enhance_checked  = ! empty( $args['enhance_checked'] );
	$enhance_disabled = ! empty( $args['enhance_disabled'] );
	$enhance_id       = 'sws-enhance-' . $id;

	$template = '<tr>
					<td>' . esc_html( $id ) . '</td>
					<td>
						<a href="' . esc_url( admin_url( 'admin.php?page=smart-search&action=edit&id=' ) ) . esc_attr( $id ) . '">
							' . ( ! empty( $args['name'] ) ? esc_html( $args['name'] ) : 'no name' ) . '
						</a>
					</td>
					<td>
						<span class="sws-shortcode-wrap">
							<input type="text" class="sws-shortcode-input" value="[smart_search id=&quot;' . esc_attr( $id ) . '&quot;]" readonly title="' . esc_attr__( 'Click to copy', 'smart-woocommerce-search' ) . '" />
							<span class="sws-shortcode-copied">' . esc_html__( 'Copied!', 'smart-woocommerce-search' ) . '</span>
						</span>
					</td>
					<td>
						<input type="checkbox" value="1"
						       id="' . esc_attr( $enhance_id ) . '"
						       class="ymapp-switcher sws-enhance-toggle' . ( $enhance_disabled ? ' sws-enhance-locked' : '' ) . '"
						       data-widget-id="' . esc_attr( $id ) . '"
						       ' . ( $enhance_checked ? 'checked' : '' ) . '
						/>
						<label for="' . esc_attr( $enhance_id ) . '"></label>
						<span class="sws-enhance-spinner spinner"></span>
					</td>
					<td>
						<a href="#" class="ysm-widget-duplicate" data-id="' . esc_attr( $id ) . '" title="' . __( 'Duplicate', 'smart-woocommerce-search' ) . '">
							<span class="dashicons dashicons-admin-page"></span>
						</a>
						<a href="#" class="ysm-widget-remove" data-id="' . esc_attr( $id ) . '" title="' . __( 'Delete', 'smart-woocommerce-search' ) . '">
							<span class="dashicons dashicons-trash"></span>
						</a>
						<span class="spinner ysm-action-spinner"></span>
					</td>
				</tr>';

	return $template;
}

/**
 * Get list of custom widgets
 * @return array
 */
function ysm_get_custom_widgets() {
	return Ysm_Widget_Manager::get_all_widgets( 'custom' );
}

/**
 * Get list of default widgets
 * @return array
 */
function ysm_get_default_widgets() {
	return Ysm_Widget_Manager::get_all_widgets( 'default' );
}

/**
 * Get list of custom and default widgets
 * @return array
 */
function ysm_get_all_widgets() {
	static $all_widgets = [];

	if ( ! empty( $all_widgets ) ) {
		return $all_widgets;
	}

	$custom_widgets  = ysm_get_custom_widgets();
	$default_widgets = ysm_get_default_widgets();

	$all_widgets = $custom_widgets;

	$available_default_widgets_ids = ysm_get_default_widgets_ids();

	foreach ( $default_widgets as $w_key => $default_widget ) {
		if ( isset( $available_default_widgets_ids[ $w_key ] ) ) {
			$enable_key = ( 'default' === $w_key ) ? 'enable_search' : 'enable_' . $w_key . '_search';
			if ( ! empty( $default_widget['settings'][ $enable_key ] ) ) {
				$all_widgets[ $w_key ] = $default_widget;
			}
		}
	}

	return $all_widgets;
}

function ysm_get_post_types() {
	static $saved_pt;

	if ( $saved_pt && is_array( $saved_pt ) ) {
		return $saved_pt;
	}

	$pt = [
		'post' => 'post',
		'page' => 'page',
		'product' => 'product',
	];

	foreach ( ysm_get_all_widgets() as $v ) {
		if ( ! empty( $v['settings']['custom_post_types'] ) ) {
			$pt = array_merge( $pt, (array) $v['settings']['custom_post_types'] );
		}
	}

	$pt = array_unique( $pt );

	$pt_exists = [];
	foreach ( $pt as $pt_name ) {
		if ( $pt_name && 'product_variation' !== $pt_name && post_type_exists( $pt_name ) ) {
			$pt_exists[ $pt_name ] = $pt_name;
		}
	}

	$pt_exists = array_values( $pt_exists );
	$saved_pt = $pt_exists;

	return $pt_exists;
}

function ysm_get_post_types_enabled() {
	static $saved_pt;

	if ( $saved_pt && is_array( $saved_pt ) ) {
		return $saved_pt;
	}

	$pt = [];

	foreach ( ysm_get_all_widgets() as $v ) {
		if ( ! empty( $v['settings']['post_type_post'] ) ) {
			$pt[] = 'post';
		}
		if ( ! empty( $v['settings']['post_type_page'] ) ) {
			$pt[] = 'page';
		}
		if ( ! empty( $v['settings']['post_type_product'] ) ) {
			$pt[] = 'product';
		}
		if ( ! empty( $v['settings']['custom_post_types'] ) ) {
			$pt = array_merge( $pt, (array) $v['settings']['custom_post_types'] );
		}
	}

	$pt = array_unique( $pt );

	if ( ! $pt ) {
		$pt[] = 'product';
	}

	$pt_exists = [];
	foreach ( $pt as $pt_name ) {
		if ( $pt_name && 'product_variation' !== $pt_name && post_type_exists( $pt_name ) ) {
			$pt_exists[ $pt_name ] = $pt_name;
		}
	}

	$pt_exists = array_values( $pt_exists );
	$saved_pt = $pt_exists;

	return $pt_exists;
}

function ysm_get_all_widgets_custom_fields() {
	static $custom_fields = [];

	if ( ! empty( $custom_fields ) ) {
		return $custom_fields;
	}

	foreach ( ysm_get_all_widgets() as $v ) {
		if ( ! empty( $v['settings']['field_product_sku'] ) ) {
			$custom_fields['_sku'] = '_sku';
		}
		if ( ! empty( $v['settings']['custom_fields'] ) ) {
			$cf_list = $v['settings']['custom_fields'];
			if ( false !== strpos( $cf_list, ',' ) ) {
				$cf_list = explode( ',', $cf_list );
				$cf_list = implode( "\n", $cf_list );
			}
			$cf_list = explode( "\n", $cf_list );
			foreach ( $cf_list as $cf ) {
				$cf = trim( $cf );
				if ( $cf ) {
					$custom_fields[$cf] = $cf;
				}
			}
		}
	}

	if ( isset( $custom_fields['_product_attributes'] ) ) {
		unset( $custom_fields['_product_attributes'] );
	}

	return $custom_fields;
}

function ysm_get_all_widgets_taxonomy_terms() {
	static $taxonomy_terms = [];

	if ( ! empty( $taxonomy_terms ) ) {
		return $taxonomy_terms;
	}

	foreach ( ysm_get_all_widgets() as $v ) {
		if ( ! empty( $v['settings']['field_tag'] ) ) {
			$taxonomy_terms['post_tag'] = 'post_tag';
		}
		if ( ! empty( $v['settings']['field_category'] ) ) {
			$taxonomy_terms['category'] = 'category';
		}
		if ( ! empty( $v['settings']['field_product_tag'] ) ) {
			$taxonomy_terms['product_tag'] = 'product_tag';
		}
		if ( ! empty( $v['settings']['field_product_cat'] ) ) {
			$taxonomy_terms['product_cat'] = 'product_cat';
		}
		if ( ! empty( $v['settings']['custom_tax'] ) && is_array( $v['settings']['custom_tax'] ) ) {
			foreach ( $v['settings']['custom_tax'] as $custom_t ) {
				$taxonomy_terms[ $custom_t ] = $custom_t;
			}
		}
	}

	$taxonomy_terms['product_cat'] = 'product_cat';

	return $taxonomy_terms;
}

/**
 * Get 's' query var
 * @return string
 */
function ysm_get_s() {
	$s = filter_input( INPUT_GET, 's', FILTER_DEFAULT );
	$woof_text = filter_input( INPUT_GET, 'woof_text', FILTER_DEFAULT );
	if ( ! empty( $woof_text ) ) {
		$s = $woof_text;
	}
	if ( $s ) {
		$s = html_entity_decode( $s );
		$s = wp_strip_all_tags( $s );
		$s = sanitize_text_field( $s );
	}

	return $s;
}

/**
 * Wrap search terms in <strong> tag on search page
 * @param $text
 * @return mixed
 */
function ysm_accent_search_term( $text ) {
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
		return $text;
	}

	if ( ! is_search() ) {
		return $text;
	}

	$w_id = filter_input( INPUT_GET, 'search_id', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
	$s    = ysm_get_s();

	if ( empty( $w_id ) || empty( $s ) ) {
		return $text;
	}

	\Ysm_Search::set_widget_id( $w_id );
	\Ysm_Search::parse_settings();

	if ( empty( ysws_get_var( 'search_page_default_output' ) ) && ! empty( ysws_get_var( 'accent_words_on_search_page' ) ) ) {
		$text = ysm_text_replace( wp_strip_all_tags( $text ) );
	}

	return $text;
}

/**
 * Replace variation title on search page
 * @param $text
 * @param $id
 * @return string
 */
function ysm_replace_variation_title( $text, $id ) {
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
		return $text;
	}

	if ( ! is_search() ) {
		return $text;
	}

	$w_id = filter_input( INPUT_GET, 'search_id', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
	$s    = ysm_get_s();

	if ( empty( $w_id ) || empty( $s ) ) {
		return $text;
	}

	\Ysm_Search::set_widget_id( $w_id );
	\Ysm_Search::parse_settings();

	if ( empty( ysws_get_var( 'search_page_default_output' ) ) ) {
		if ( 'product_variation' === get_post_type( $id ) ) {
			$text = ysws_get_variation_title( $id );
		}
	}

	return $text;
}


/**
 * Wrap search terms in <strong> tag
 * @param $text
 * @return string
 */
function ysm_text_replace( $text ) {
	$words = \Ysm_Search::get_search_terms();

	foreach ( $words as &$w ) {
		$w = preg_quote( trim( $w ) );
		$w = str_replace( '/', '\/', $w );
	}

	return preg_replace( '/' . implode( '|', $words ) . '/i', '<strong>$0</strong>', $text );
}

/**
 * Get variation title
 * @param $product
 * @return string
 */
function ysws_get_variation_title( $product ) {
	$product = get_post( $product );
	$title = '';
	if ( $product && 'product_variation' === $product->post_type && class_exists( 'WooCommerce' ) ) {
		$wc_product = wc_get_product( $product->ID );
		if ( $wc_product ) {
			$title = get_the_title( $product->post_parent );
			$variation_attributes = $wc_product->get_variation_attributes( false );
			if ( ! empty( $variation_attributes ) && is_array( $variation_attributes ) ) {
				$title .= ' - ';
				foreach ( $variation_attributes as $key => $attribute ) {
					$title .= $wc_product->get_attribute( str_replace( 'pa_', '', $key ) ) . ', ';
				}
				$title = trim( $title, ', ' );
			}
		}
	}
	return $title;
}

/**
 * Get woocommerce product rewrite base slug
 * @param $w_id
 * @return string|null
 */
function ysw_get_woocommerce_product_slug( $w_id ) {
	// product_slug
	$product_slug = ysm_get_option( $w_id, 'product_slug' );
	if ( ! $product_slug ) {
		$product_slug = 'product';
	}

	return $product_slug;
}

add_action('wp_ajax_ysm_search_products', 'ysm_search_products_callback');

function ysm_search_products_callback() {

	$search_term = isset( $_GET['term'] ) ? sanitize_text_field( $_GET['term'] ) : '';

	$args = [
		'post_type'      => 'product',
		'posts_per_page' => 10,
		'post_status'    => 'publish',
		'order'          => 'DESC',
		'orderby'        => 'relevance',
		's'              => $search_term,
	];

	$query = new WP_Query( $args );

	$results = [];

	if ( $query->have_posts() ) {
		while ( $query->have_posts() ) {
			$query->the_post();

			// Get WooCommerce product object
			$product = wc_get_product( get_the_ID() );

			if ( $product ) {
				$results[] = [
					'id'   => $product->get_id(),
					'text' => sprintf(
						'%s',
						$product->get_name(),
					)
				];
			}
		}
		wp_reset_postdata();
	}

	// Send results
	wp_send_json( $results );
	wp_die();
}

function ysws_get_var($name) {
	return \Ysm_Search::get_var($name);
}

function ysws_set_var($name, $value) {
	\Ysm_Search::set_var($name, $value);
}

function ysws_strip_punctuation( $string ) {
	$replace_map = [
		'&amp;' => '&',
		'&#038;' => '&',
		'&nbsp;' => ' ',
		'&#8217;' => "'",
	];
	$preserve_map = [
		'-' => 'DDDSSS',
		'_' => 'UUUSSS',
		'.' => 'DDDTTT',
		'/' => 'SSSLLL',
	];
	$string = str_replace( array_keys( $replace_map ), array_values( $replace_map ), $string );
	$string = str_replace( array_keys( $preserve_map ), array_values( $preserve_map ), $string );
	$string = preg_replace('/[[:punct:]]+/u', ' ', $string);
	$string = str_replace( array_values( $preserve_map ), array_keys( $preserve_map ), $string );
	$string = preg_replace('/\s+/', ' ', $string );
	$string = trim( $string );

	return $string;
}

