<?php
/**
 * Plugin Actions, Filters
 *
 * @author     D-THEMES
 * @package    WP Alpha Core Framework
 * @subpackage Core
 * @version    1.0
 */
defined( 'ABSPATH' ) || die;

add_action( 'after_setup_theme', 'alpha_setup_make_script_async' );
add_action( 'wp_enqueue_scripts', 'alpha_enqueue_core_framework_scripts', 2 );
add_action( 'admin_print_footer_scripts', 'alpha_print_footer_scripts', 30 );
add_action( 'wp_ajax_alpha_load_creative_layout', 'alpha_load_creative_layout' );
add_action( 'wp_ajax_nopriv_alpha_load_creative_layout', 'alpha_load_creative_layout' );

// update image srcset meta
add_filter( 'wp_calculate_image_srcset', 'alpha_image_srcset_filter_sizes', 10, 2 );

// post filter
add_filter( 'posts_clauses', 'alpha_cpt_query_post_clauses', 10, 2 );

if ( ! function_exists( 'alpha_print_footer_scripts' ) ) {
	/**
	 * Print footer scripts
	 *
	 * @since 1.0
	 */
	function alpha_print_footer_scripts() {
		echo '<script id="alpha-core-admin-js-extra">';
		echo 'var alpha_core_vars = ' . json_encode(
			apply_filters(
				'alpha_core_admin_localize_vars',
				array(
					'ajax_url'   => esc_url( admin_url( 'admin-ajax.php' ) ),
					'nonce'      => wp_create_nonce( 'alpha-core-nonce' ),
					'assets_url' => ALPHA_CORE_URI,
					'theme'      => ALPHA_NAME,
				)
			)
		) . ';';
		echo '</script>';
	}
}

if ( ! function_exists( 'alpha_enqueue_core_framework_scripts' ) ) {

	/**
	 * Enqueue framework required scripts
	 *
	 * @since 1.2.0
	 */
	function alpha_enqueue_core_framework_scripts() {
		wp_register_script( 'jquery-floating', alpha_core_framework_uri( '/assets/js/jquery.floating.min.js' ), array( 'jquery-core' ), false, true );
		wp_register_script( 'jquery-skrollr', alpha_core_framework_uri( '/assets/js/skrollr.min.js' ), array(), '0.6.30', true );
		wp_register_script( 'alpha-chart-lib', alpha_core_framework_uri( '/assets/js/chart.min.js' ), array(), false, true );
		wp_register_script( 'three-sixty', alpha_core_framework_uri( '/assets/js/threesixty.min.js' ), array(), false, true );
		wp_register_script( 'jquery-countdown', alpha_core_framework_uri( '/assets/js/jquery.countdown.min.js' ), array(), false, true );
	}
}

if ( ! function_exists( 'alpha_setup_make_script_async' ) ) {
	/**
	 * Add a filter to make scripts async.
	 *
	 * @since 1.0
	 */
	function alpha_setup_make_script_async() {
		// Set scripts as async
		if ( ! alpha_is_wpb_preview() && function_exists( 'alpha_get_option' ) && alpha_get_option( 'resource_async_js' ) ) {
			add_filter( 'script_loader_tag', 'alpha_make_script_async', 10, 2 );
		}
	}
}

if ( ! function_exists( 'alpha_make_script_async' ) ) {
	/**
	 * Set scripts as async
	 *
	 * @since 1.0
	 *
	 * @param string $tag
	 * @param string $handle
	 * @return string Async script tag
	 */
	function alpha_make_script_async( $tag, $handle ) {
		$async_scripts = apply_filters(
			'alpha_async_scripts',
			array(
				'jquery-autocomplete',
				'jquery-countdown',
				'alpha-magnific-popup',
				'jquery-cookie',
				'alpha-framework-async',
				'alpha-theme',
				'alpha-shop',
				'alpha-woocommerce',
				'alpha-single-product',
				'alpha-ajax',
				'alpha-countdown',
				'alpha-shop-show-type',
			)
		);

		if ( in_array( $handle, $async_scripts ) ) {
			return str_replace( ' src', ' async="async" src', $tag );
		}
		return $tag;
	}
}

add_filter(
	'alpha_core_filter_doing_ajax',
	function() {
		// check ajax doing on others
		return ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && mb_strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' ) ? true : false;
	}
);

if ( ! function_exists( 'alpha_load_creative_layout' ) ) {
	function alpha_load_creative_layout() {
		// phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification

		$mode = isset( $_POST['mode'] ) ? $_POST['mode'] : 0;

		if ( $mode ) {
			echo json_encode( alpha_creative_layout( $mode ) );
		} else {
			echo json_encode( array() );
		}

		exit();

		// phpcs:enable
	}
}

if ( ! function_exists( 'alpha_image_srcset_filter_sizes' ) ) {
	/**
	 * Remove srcset in img tag.
	 *
	 * @since 1.2.0
	 */
	function alpha_image_srcset_filter_sizes( $sources, $size_array ) {
		foreach ( $sources as $width => $source ) {
			if ( isset( $source['descriptor'] ) && 'w' == $source['descriptor'] && ( $width < apply_filters( 'alpha_mini_screen_size', 320 ) || (int) $width > (int) $size_array[0] ) ) {
				unset( $sources[ $width ] );
			}
		}
		return $sources;
	}
}

if ( ! function_exists( 'alpha_cpt_query_post_clauses' ) ) {

	/**
	 * Add extra clauses to the cpt query.
	 *
	 * @param array    $args CPT query clauses.
	 * @param WP_Query $wp_query The current cpt query.
	 * @return array The updated cpt query clauses array.
	 */
	function alpha_cpt_query_post_clauses( $args, $wp_query ) {
		global $wpdb;

		if ( ! $wp_query->is_main_query() ) {
			return $args;
		}

		$attributes = array();
		if ( ! empty( $_GET ) ) {
			foreach ( $_GET as $key => $value ) {
				if ( 0 === strpos( $key, 'filter_' ) ) {
					$taxonomy     = urldecode( sanitize_title( urldecode( str_replace( 'filter_', '', $key ) ?? '' ) ) );
					$filter_terms = ! empty( $value ) ? explode( ',', wp_unslash( $value ) ) : array();

					if ( empty( $filter_terms ) || ! taxonomy_exists( $taxonomy ) ) {
						continue;
					}

					$query_type                            = ! empty( $_GET[ 'query_type_' . $taxonomy ] ) && in_array( $_GET[ 'query_type_' . $taxonomy ], array( 'and', 'or' ), true ) ? wp_unslash( $_GET[ 'query_type_' . $taxonomy ] ) : '';
					$attributes[ $taxonomy ]['terms']      = array_map( 'sanitize_title', $filter_terms ); // Ensures correct encoding.
					$attributes[ $taxonomy ]['query_type'] = $query_type;
				}
			}
		}

		// The extra derived table ("SELECT object_id FROM") is needed for performance
		// (causes the filtering subquery to be executed only once).
		$clause_root = " {$wpdb->posts}.ID IN ( SELECT object_id FROM (";

		$attribute_ids_for_and_filtering = array();

		foreach ( $attributes as $taxonomy => $data ) {
			$all_terms                  = get_terms( $taxonomy, array( 'hide_empty' => false ) );
			$term_ids_by_slug           = wp_list_pluck( $all_terms, 'term_id', 'slug' );
			$term_ids_to_filter_by      = array_values( array_intersect_key( $term_ids_by_slug, array_flip( $data['terms'] ) ) );
			$term_ids_to_filter_by      = array_map( 'absint', $term_ids_to_filter_by );
			$term_ids_to_filter_by_list = '(' . join( ',', $term_ids_to_filter_by ) . ')';
			$is_and_query               = 'and' === $data['query_type'];

			$count = count( $term_ids_to_filter_by );

			if ( 0 !== $count ) {
				if ( $is_and_query && $count > 1 ) {
					$attribute_ids_for_and_filtering = array_merge( $attribute_ids_for_and_filtering, $term_ids_to_filter_by );
				} else {
					$clauses[] = "
							{$clause_root}
							SELECT object_id
							FROM {$wpdb->term_relationships} lt
							WHERE term_taxonomy_id in {$term_ids_to_filter_by_list}
						)";
				}
			}
		}

		if ( ! empty( $attribute_ids_for_and_filtering ) ) {
			$count                      = count( $attribute_ids_for_and_filtering );
			$term_ids_to_filter_by_list = '(' . join( ',', $attribute_ids_for_and_filtering ) . ')';
			$clauses[]                  = "
				{$clause_root}
				SELECT object_id
				FROM {$wpdb->term_relationships} lt
				WHERE term_taxonomy_id in {$term_ids_to_filter_by_list}
				GROUP BY object_id
				HAVING COUNT(object_id)={$count}
			)";
		}

		if ( ! empty( $clauses ) ) {
			// "temp" is needed because the extra derived tables require an alias.
			$args['where'] .= ' AND (' . join( ' temp ) AND ', $clauses ) . ' temp ))';
		} elseif ( ! empty( $attributes ) ) {
			$args['where'] .= ' AND 1=0';
		}

		return $args;
	}
}
