<?php

if (! defined('ABSPATH')) {
	exit; // Exit if accessed directly.
}

add_shortcode('prwfr_recently_viewed_products_front', 'prwfr_recently_viewed_products_front');

/**
 * To showcase Recently viewed items in a single row, use a shortcode that arranges and displays the products accordingly.
 */
function prwfr_recently_viewed_products_front()
{

	global $wpdb;
	$user_id                = get_current_user_id();
	$rvp_product_ids_temp   = array();
	$rvp_product_ids_array  = array();
	$desktop_products_limit = get_option('prwfr_rvps_desktop_limit');
	$tab_products_limit     = get_option('prwfr_rvps_tab_limit');
	$mobile_products_limit  = get_option('prwfr_rvps_mobile_limit');
	$products_array_temp    = array();
	$current_date           = gmdate('Y-m-d');
	$date_before_15days     = gmdate('Y-m-d', strtotime('-15 days', strtotime($current_date)));
	$table_name             = $wpdb->prefix . 'sft_user_product_interactions';

	if (intval($desktop_products_limit) === 0) {
		$desktop_products_limit = '4';
	}

	// nonce verification.
	$secure_nonce      = wp_create_nonce('sft-product-recommendations-for-woocommerce');
	$id_nonce_verified = wp_verify_nonce($secure_nonce, 'sft-product-recommendations-for-woocommerce');

	if (! $id_nonce_verified) {
		wp_die(esc_html__('Nonce Not verified', 'sft-product-recommendations-for-woocommerce'));
	}

	ob_start();

	if (is_user_logged_in()) {
		// $products_array stores rvps product id for logged in users.

		// Prepare and execute the query safely using wpdb->prepare for values only.
		$result = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT product_details FROM `$table_name` WHERE interaction_type=%s AND DATE(interaction_timestamp) BETWEEN %s AND %s AND customer_id=%d",
				'recently-viewed-products',
				$date_before_15days,
				$current_date,
				$user_id
			)
		);

		$rvp_products = array();

		if (! is_array($result)) {
			$result = array();
		}

		foreach ($result as $row) {
			$prdoucts     = json_decode($row->product_details, true);
			$rvp_products = array_merge($rvp_products, $prdoucts['product_ids']);
		}

		$products_array       = array_reverse($rvp_products);
		$products_array       = array_unique($products_array);
		$rvp_product_ids_temp = $products_array;

?>
		<!-- Displays title for rvps -->
		<div class="prwfr-rvps-front-title prwfr-widget-title-container">
			<?php
			$title = get_option('prwfr_rvps_title');
			?>
			<?php
			if (! $title) {
				echo '<h2>' . esc_html__('Recently Viewed Products', 'sft-product-recommendations-for-woocommerce') . '</h2>';
			} else {
				echo '<h2>' . esc_html($title) . '</h2>';
			}

			$page_id            = get_option('prwfr_rvps_page_id');
			$translated_page_id = prwfr_translate_woocommerce_title($page_id);
			?>

			<div class="prwfr-widget-inner-container">

				<!-- See more link to redirect to page containig all recently viewed prdoucts -->
				<div class="prwfr-see-more">
					<a href="<?php echo esc_url(get_permalink($translated_page_id)); ?>" onMouseOver="this.style.color='#CD5C5C'"
						onMouseOut="this.style.color='#4682B4'" style="text-decoration: underline; color: #4682B4; font-size: small !important;"><?php esc_html_e('See more', 'sft-product-recommendations-for-woocommerce'); ?></a>
				</div>

				<!-- Displays pagination and start over on right corner of row -->
				<!-- <div style="float: right; display: flex;gap: 15px;"> -->
				<div class="prwfr-pagination-container">
					<div class="prwfr-rvps-page-display prwfr-page-display" style="font-size: medium;"><?php esc_html_e('Page no', 'sft-product-recommendations-for-woocommerce'); ?></div>
					<div class="prwfr-rvps-start-over prwfr-start-over" onMouseOver="this.style.color='#CD5C5C'"
						onMouseOut="this.style.color='#4682B4'" style="font-size: small; color: #4682B4; display:none; z-index:200; cursor: pointer;" data-name="rvps"><?php esc_html_e('Start over', 'sft-product-recommendations-for-woocommerce'); ?></div>
				</div>

			</div>


		</div>
		<?php

		foreach ($rvp_product_ids_temp as $product_id) {
			array_push($products_array_temp, $product_id);
		}

		$rvp_product_ids_temp = $products_array_temp;

		if (! empty($rvp_product_ids_temp) && ! intval($rvp_product_ids_temp[count($rvp_product_ids_temp) - 1])) {
			array_pop($rvp_product_ids_temp);
		}

		if (count($rvp_product_ids_temp) < intval($desktop_products_limit)) {

		?>
			<!-- If there is no element in $rvp_product_ids_temp array, rvps will be hidden in shortcode -->
			<script>
				jQuery(document).ready(function() {
					jQuery(".prwfr-rvps-front-title").hide();
				})
			</script>
			<?php
		} else {

			foreach ($rvp_product_ids_temp as $product_id) {
				if (intval($product_id)) {
					array_push($rvp_product_ids_array, $product_id);
				}
			}
			if (is_product()) {
				$curr_products         = (array) get_the_ID();
				$rvp_product_ids_array = array_diff($rvp_product_ids_array, $curr_products);
			}
			prwfr_display_products($rvp_product_ids_array, intval($desktop_products_limit), intval($tab_products_limit), intval($mobile_products_limit), 'rvps', 'rvps');
		}
	} else {

		// If admin donot toggle hide switch.
		if (! intval(get_option('prwfr_rvps_hide_cookie'))) {

			if (isset($_SERVER['SERVER_NAME'])) {

				// Sanitize the server name to create a safe cookie name.
				$recently_viewed_products_cookie_name = sanitize_key($_SERVER['SERVER_NAME']);
				$recently_viewed_products_cookie_name = str_replace('.', '_', $recently_viewed_products_cookie_name);

				// Retrieve the option value using the sanitized cookie name.
				$recently_viewed_products_cookie_name = get_option('prwfr_' . $recently_viewed_products_cookie_name);
			}

			if (isset($_COOKIE[$recently_viewed_products_cookie_name])) {

				// $products_array stores rvps product id for non logged in users.
				$products_array = sanitize_text_field(wp_unslash($_COOKIE[$recently_viewed_products_cookie_name]));
				$products_array = explode(',', $products_array);
				$products_array = array_reverse($products_array);
				$products_array = array_unique($products_array);

				if (count($products_array)) {
			?>

					<!-- Title to diaplay rvps for non logged in users in shortcode container  -->
					<div class="prwfr-cookie-rvps-front-title prwfr-widget-title-container">

						<?php
						$title = get_option('prwfr_rvps_title');

						if (! $title) {
							echo '<h2>' . esc_html__('Recently Viewed Products', 'sft-product-recommendations-for-woocommerce') . '</h2>';
						} else {
							echo '<h2>' . esc_html($title) . '</h2>';
						}

						$page_id            = get_option('prwfr_rvps_page_id');
						$translated_page_id = prwfr_translate_woocommerce_title($page_id);
						?>

						<div class="prwfr-widget-inner-container">

							<span class="prwfr-see-more">
								<a href="<?php echo esc_url(get_permalink($translated_page_id)); ?>" onMouseOver="this.style.color='#CD5C5C'"
									onMouseOut="this.style.color='#4682B4'" style="text-decoration: underline; color: #4682B4; font-size: small !important;"><?php esc_html_e('See more', 'sft-product-recommendations-for-woocommerce'); ?>
								</a>
							</span>

							<div class="prwfr-pagination-container">

								<div class="prwfr-cookie-rvps-page-display prwfr-page-display" style="font-size: medium;"><?php esc_html_e('Page no', 'sft-product-recommendations-for-woocommerce'); ?></div>
								<div class="prwfr-cookie-rvps-start-over prwfr-start-over" onMouseOver="this.style.color='#CD5C5C'"
									onMouseOut="this.style.color='#4682B4'" style="font-size: small; color: #4682B4; display:none; z-index:200;" data-name="cookie-rvps"><?php esc_html_e('Start over', 'sft-product-recommendations-for-woocommerce'); ?></div>

							</div>

						</div>

					</div>
					<?php

					// Call function if no of elements in array is greater than or equal to the desktop limit set.
					if (count($products_array) >= intval($desktop_products_limit)) {

						if (is_product()) {
							$curr_products  = (array) get_the_ID();
							$products_array = array_diff($products_array, $curr_products);
						}

						prwfr_display_products($products_array, intval($desktop_products_limit), intval($tab_products_limit), intval($mobile_products_limit), 'cookie-rvps', 'rvps');
					} else {
					?>
						<script>
							jQuery('.prwfr-cookie-rvps-front-title').hide();
						</script>
			<?php
					}
				}
			}
		}
	}

	$content = ob_get_clean();
	return $content;
}

add_shortcode('prwfr_onsale_recently_viewed_products_front', 'prwfr_onsale_recently_viewed_products_front');

/**
 * To showcase Related products and Recently viewed items on sale in a single row, use a shortcode that arranges and displays the products accordingly.
 */
function prwfr_onsale_recently_viewed_products_front()
{

	global $wpdb;
	$user_id                   = get_current_user_id();
	$onsale_products_with_slug = array();
	$rvp_onsale_products_array = array();
	$products_onsale_ids       = wc_get_product_ids_on_sale();
	$rvps_onsale_products_id   = array();

	$desktop_products_limit = get_option('prwfr_rvps_onsale_desktop_limit');
	$tab_products_limit     = get_option('prwfr_rvps_onsale_tab_limit');
	$mobile_products_limit  = get_option('prwfr_rvps_onsale_mobile_limit');

	$current_date       = gmdate('Y-m-d');
	$date_before_15days = gmdate('Y-m-d', strtotime('-15 days', strtotime($current_date)));
	$table_name         = $wpdb->prefix . 'sft_user_product_interactions';

	if (intval($desktop_products_limit) === 0) {
		$desktop_products_limit = '4';
	}

	// nonce verification.
	$secure_nonce      = wp_create_nonce('sft-product-recommendations-for-woocommerce');
	$id_nonce_verified = wp_verify_nonce($secure_nonce, 'sft-product-recommendations-for-woocommerce');

	if (! $id_nonce_verified) {
		wp_die(esc_html__('Nonce Not verified', 'sft-product-recommendations-for-woocommerce'));
	}

	ob_start();

	if (! empty($products_onsale_ids)) {

		if (is_user_logged_in()) {

			// Prepare and execute the query safely using wpdb->prepare for values only.
			$result = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT product_details FROM $table_name WHERE interaction_type=%s AND DATE(interaction_timestamp) BETWEEN %s AND %s AND customer_id=%d",
					'recently-viewed-products',
					$date_before_15days,
					$current_date,
					$user_id
				)
			);

			$rvp_products = array();
			foreach ($result as $row) {
				$prdoucts     = json_decode($row->product_details, true);
				$rvp_products = array_merge($rvp_products, $prdoucts['product_ids']);
			}

			$products_array = array_reverse($rvp_products);
			$products_array = array_unique($products_array);

			?>
			<div class="prwfr-rvps-onsale-front-title prwfr-widget-title-container">
				<?php
				$title = get_option('prwfr_rvps_onsale_title');

				if (! $title) {
					echo '<h2>' . esc_html__('Trending Deals', 'sft-product-recommendations-for-woocommerce') . '</h2>';
				} else {
					echo '<h2>' . esc_html($title) . '</h2>';
				}
				$page_id            = get_option('prwfr_rvps_onsale_page_id');
				$translated_page_id = prwfr_translate_woocommerce_title($page_id);
				?>

				<div class="prwfr-widget-inner-container">
					<!-- See more link to redirect to page containig all recently viewed prdoucts and related on sale -->
					<span class="prwfr-see-more">
						<a href="<?php echo esc_url(get_permalink($translated_page_id)); ?>" onMouseOver="this.style.color='#CD5C5C'"
							onMouseOut="this.style.color='#4682B4'" style="text-decoration: underline; color: #4682B4; font-size: small !important;"><?php esc_html_e('See more', 'sft-product-recommendations-for-woocommerce'); ?></a>
					</span>

					<!-- Displays pagination and <?php esc_html_e('Start over', 'sft-product-recommendations-for-woocommerce'); ?> on right corner of row -->
					<div class="prwfr-pagination-container">
						<div class="prwfr-rvps-onsale-page-display prwfr-page-display" style="font-size: medium;"><?php esc_html_e('Page no', 'sft-product-recommendations-for-woocommerce'); ?></div>
						<div class="prwfr-rvps-onsale-start-over prwfr-start-over" onMouseOver="this.style.color='#CD5C5C'"
							onMouseOut="this.style.color='#4682B4'" style="font-size: small; color: #4682B4; display:none; z-index:200; cursor:pointer;" data-name="rvps-onsale"><?php esc_html_e('Start over', 'sft-product-recommendations-for-woocommerce'); ?></div>
					</div>
				</div>
			</div>
			<?php
			// If the variable $products_array has elements, then the slugs of the categories associated with products in the rvps will be stored in $onsale_products_with_slug.
			if (count($products_array)) {

				foreach ($products_array as $product_id) {

					if (intval($product_id) !== 0) {
						$product_categories = wp_get_post_terms($product_id, 'product_cat');
						foreach ($product_categories as $product) {
							array_push($onsale_products_with_slug, $product->slug);
						}
					}
				}

				// Get all the products that have categories from $onsale_products_with_slug included in them.
				$onsale_products_with_slug = array_unique($onsale_products_with_slug);
				$args_rvps_onsale          = array(
					'posts_per_page' => -1,
					'post_type'      => 'product',
					'post__in'       => $products_onsale_ids,
					'tax_query'      => array(
						array(
							'taxonomy' => 'product_cat',
							'field'    => 'slug',
							'terms'    => $onsale_products_with_slug,
						),
					),
				);

				$query_rvps_onsale = new WP_Query($args_rvps_onsale);

				// $rvp_onsale_products_array contains all products on sale which are related to rvps
				foreach ($query_rvps_onsale->posts as $post) {
					array_push($rvp_onsale_products_array, $post->ID);
				}

				$rvps_onsale_products_id = $rvp_onsale_products_array;
			}

			// Function is called to display rvps and realted on sale in shortcode container.
			if (count($rvps_onsale_products_id) >= intval($desktop_products_limit)) {
				// Limit is no of products to display in single row in shortcode container, get the limit from setting page.

				if (is_product()) {
					$curr_products           = (array) get_the_ID();
					$rvps_onsale_products_id = array_diff($rvps_onsale_products_id, $curr_products);
				}

				prwfr_display_products($rvps_onsale_products_id, intval($desktop_products_limit), intval($tab_products_limit), intval($mobile_products_limit), 'rvps-onsale', 'rvps_onsale');
			} else {
			?>
				<!-- If there is no element in $rvp_product_ids_temp array, rvps will be hidden in shortcode -->
				<script>
					jQuery(document).ready(function() {
						jQuery(".prwfr-rvps-onsale-front-title").hide();
					})
				</script>
				<?php
			}
		} else {
			if (! intval(get_option('prwfr_rvps_onsale_hide_cookie'))) {

				if (isset($_SERVER['SERVER_NAME'])) {

					// Sanitize the server name to create a safe cookie name.
					$recently_viewed_products_cookie_name = sanitize_key($_SERVER['SERVER_NAME']);
					$recently_viewed_products_cookie_name = str_replace('.', '_', $recently_viewed_products_cookie_name);

					// Retrieve the option value using the sanitized cookie name.
					$recently_viewed_products_cookie_name = get_option('prwfr_' . $recently_viewed_products_cookie_name);
				}

				if (isset($_COOKIE[$recently_viewed_products_cookie_name])) {

					// $products_array stores recently viewed prdoucts for non logge in users.
					$products_array = sanitize_text_field(wp_unslash($_COOKIE[$recently_viewed_products_cookie_name]));
					$products_array = explode(',', $products_array);
					$products_array = array_reverse($products_array);
					$products_array = array_unique($products_array);

					if (count($products_array)) {
				?>

						<!-- Title for rvps and realted products onsale for non logged in users  -->
						<div class="prwfr-cookie-rvps-onsale-front-title prwfr-widget-title-container">

							<?php
							$title = get_option('prwfr_rvps_onsale_title');
							if (! $title) {
								// $title = 'Trending Deals';
								echo '<h2>' . esc_html__('Trending Deals', 'sft-product-recommendations-for-woocommerce') . '</h2>';
							} else {
								echo '<h2>' . esc_html($title) . '</h2>';
							}

							$page_id            = get_option('prwfr_rvps_onsale_page_id');
							$translated_page_id = prwfr_translate_woocommerce_title($page_id);
							?>

							<div class="prwfr-widget-inner-container">

								<!-- See more redirects to the page caintaing all the products of rvps and realted products onsale -->
								<span class="prwfr-see-more">
									<a href="<?php echo esc_url(get_permalink($translated_page_id)); ?>" onMouseOver="this.style.color='#CD5C5C'"
										onMouseOut="this.style.color='#4682B4'" style="text-decoration: underline; color: #4682B4; font-size: small !important;"><?php esc_html_e('See more', 'sft-product-recommendations-for-woocommerce'); ?></a>
								</span>

								<div class="prwfr-pagination-container">
									<div class="prwfr-cookie-rvps-onsale-page-display prwfr-page-display" style="font-size: medium;"><?php esc_html_e('Page no', 'sft-product-recommendations-for-woocommerce'); ?></div>
									<div class="prwfr-cookie-rvps-onsale-start-over prwfr-start-over" onMouseOver="this.style.color='#CD5C5C'"
										onMouseOut="this.style.color='#4682B4'" style="font-size: small; color: #4682B4; display:none; z-index:200;" data-name="cookie-rvps-onsale"><?php esc_html_e('Start over', 'sft-product-recommendations-for-woocommerce'); ?></div>
								</div>

							</div>
						</div>
						<?php
						// rvps and related on sale non logged in user.
						foreach ($products_array as $product_id) {

							if (intval($product_id) !== 0) {
								$product            = wc_get_product($product_id);
								$product_categories = wp_get_post_terms($product_id, 'product_cat');
								foreach ($product_categories as $product) {
									array_push($onsale_products_with_slug, $product->slug);
								}
							}
						}

						$onsale_products_with_slug = array_unique($onsale_products_with_slug);

						// Retrieves all the products containing slugs from $onsale_products_with_slug.
						$args  = array(
							'posts_per_page' => -1,
							'post_type'      => 'product',
							'post__in'       => $products_onsale_ids,
							'tax_query'      => array(
								array(
									'taxonomy' => 'product_cat',
									'field'    => 'slug',
									'terms'    => $onsale_products_with_slug,
								),
							),
						);
						$query = new WP_Query($args);

						foreach ($query->posts as $post) {
							array_push($rvp_onsale_products_array, $post->ID);
						}

						if (count($rvp_onsale_products_array) >= intval($desktop_products_limit)) {

							if (is_product()) {
								$curr_products             = (array) get_the_ID();
								$rvp_onsale_products_array = array_diff($rvp_onsale_products_array, $curr_products);
							}

							prwfr_display_products($rvp_onsale_products_array, intval($desktop_products_limit), intval($tab_products_limit), intval($mobile_products_limit), 'cookie-rvps-onsale', 'rvps_onsale');
						} else {
						?>
							<script>
								jQuery('.prwfr-cookie-rvps-onsale-front-title').hide();
							</script>
		<?php
						}
					}
				}
			}
		}
	}

	$content = ob_get_clean();
	return $content;
}

add_shortcode('prwfr_related_recently_viewed_products_front', 'prwfr_related_recently_viewed_products_front');

/**
 * To showcase Related products for Recently viewed items in a single row, use a shortcode that arranges and displays the products accordingly.
 */
function prwfr_related_recently_viewed_products_front()
{

	global $wpdb;
	$user_id                    = get_current_user_id();
	$product_categories         = array();
	$rvp_related_products_array = array();
	$products_array             = array();
	$rvp_related_products       = array();
	$desktop_products_limit     = get_option('prwfr_viewed_related_desktop_limit');
	$tab_products_limit         = get_option('prwfr_viewed_related_tab_limit');
	$mobile_products_limit      = get_option('prwfr_viewed_related_mobile_limit');
	$current_date               = gmdate('Y-m-d');
	$date_before_15days         = gmdate('Y-m-d', strtotime('-15 days', strtotime($current_date)));
	$table_name                 = $wpdb->prefix . 'sft_user_product_interactions';

	if (intval($desktop_products_limit) === 0) {
		$desktop_products_limit = '4';
	}

	// nonce verification.
	$secure_nonce      = wp_create_nonce('sft-product-recommendations-for-woocommerce');
	$id_nonce_verified = wp_verify_nonce($secure_nonce, 'sft-product-recommendations-for-woocommerce');

	if (! $id_nonce_verified) {
		wp_die(esc_html__('Nonce Not verified', 'sft-product-recommendations-for-woocommerce'));
	}

	ob_start();

	if (is_user_logged_in()) {

		// Prepare and execute the query safely using wpdb->prepare for values only.
		$result = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT product_details FROM $table_name WHERE interaction_type=%s AND DATE(interaction_timestamp) BETWEEN %s AND %s AND customer_id=%d",
				'recently-viewed-products',
				$date_before_15days,
				$current_date,
				$user_id
			)
		);

		$rvp_products = array();
		foreach ($result as $row) {
			$prdoucts     = json_decode($row->product_details, true);
			$rvp_products = array_merge($rvp_products, $prdoucts['product_ids']);
		}

		$products_array = array_reverse($rvp_products);
		$products_array = array_unique($products_array);

		?>
		<!-- Title of Rvps related shortcode container -->
		<div class="prwfr-viewed-related-front-title prwfr-widget-title-container">
			<?php
			$title = get_option('prwfr_viewed_related_title');

			if (! $title) {
				echo '<h2>' . esc_html__('Related to items you\'ve viewed', 'sft-product-recommendations-for-woocommerce') . '</h2>';
			} else {
				echo '<h2>' . esc_html($title) . '</h2>';
			}

			$page_id            = get_option('prwfr_viewed_related_page_id');
			$translated_page_id = prwfr_translate_woocommerce_title($page_id);
			?>

			<div class="prwfr-widget-inner-container">

				<!-- See more link to redirect to page containig all recently viewed prdoucts -->
				<div class="prwfr-see-more">
					<a href="<?php echo esc_url(get_permalink($translated_page_id)); ?>" onMouseOver="this.style.color='#CD5C5C'"
						onMouseOut="this.style.color='#4682B4'" style="text-decoration: underline; color: #4682B4; font-size: small !important;"><?php esc_html_e('See more', 'sft-product-recommendations-for-woocommerce'); ?></a>
				</div>

				<!-- Displays pagination and start over on right corner of row -->
				<div class="prwfr-pagination-container">
					<div class="prwfr-viewed-related-page-display prwfr-page-display" style="font-size: medium;"><?php esc_html_e('Page no', 'sft-product-recommendations-for-woocommerce'); ?></div>
					<div class="prwfr-viewed-related-start-over prwfr-start-over" onMouseOver="this.style.color='#CD5C5C'"
						onMouseOut="this.style.color='#4682B4'" style="font-size: small; display:none; color: #4682B4; z-index:200; cursor:pointer;" data-name="viewed-related"><?php esc_html_e('Start over', 'sft-product-recommendations-for-woocommerce'); ?></div>
				</div>

			</div>

		</div>
		<?php

		// if ( get_option( 'prwfr_rvp_related_recommendation_mode' ) ) {

		// 	$args = array(
		// 		'post_type'      => 'any',  // Adjust to target specific post types.
		// 		'post_status'    => 'any',
		// 		'posts_per_page' => -1,     // Retrieve all posts.
		// 		'meta_key'       => 'ai_generated_product_recommendations_sft', // The meta key you want to delete.
		// 		'fields'         => 'ids',   // Only get post IDs to improve performance.
		// 	);

		// 	$posts_with_meta = get_posts( $args );

		// 	$rvp_ai_recommendations            = array_intersect( $products_array, $posts_with_meta );
		// 	$ai_viewed_related_recommendations = array();
		// 	// Loop through each post ID.
		// 	foreach ( $rvp_ai_recommendations as $post_id ) {

		// 		// Retrieve the specific post meta data for the current post ID.
		// 		$ai_recommendations = get_post_meta( $post_id, 'ai_generated_product_recommendations_sft', true );
		// 		// Check if there is any data retrieved.
		// 		if ( ! empty( $ai_recommendations ) ) {
		// 			$ai_viewed_related_recommendations = array_merge( $ai_viewed_related_recommendations, $ai_recommendations );
		// 		}
		// 	}
		// 	$rvp_related_products = array_values( array_unique( array_diff( $ai_viewed_related_recommendations, $products_array ) ) );
		// } else {
		// 	// Get category slug of rvps products.
		// 	foreach ( $products_array as $product_id ) {

		// 		if ( intval( $product_id ) !== 0 ) {
		// 			$product_category = wp_get_post_terms( $product_id, 'product_cat' );

		// 			foreach ( $product_category as $product ) {
		// 				array_push( $product_categories, $product->slug );
		// 			}
		// 		}
		// 	}

		// 	$product_categories = array_unique( $product_categories );

		// 	$args_viewed_related  = array(
		// 		'posts_per_page' => -1,
		// 		'post_type'      => 'product',
		// 		'post__not_in'   => $products_array,
		// 		'tax_query'      => array(
		// 			array(
		// 				'taxonomy' => 'product_cat',
		// 				'field'    => 'slug',
		// 				'terms'    => $product_categories,
		// 			),
		// 		),
		// 	);
		// 	$query_viewed_related = new WP_Query( $args_viewed_related );

		// 	foreach ( $query_viewed_related->posts as $post ) {
		// 		array_push( $rvp_related_products_array, $post->ID );
		// 	}

		// 	$rvp_related_products = $rvp_related_products_array;
		// }

		if (get_option('prwfr_rvp_related_recommendation_mode') == 'ai_only') {

			$rvp_related_products = prwfr_get_ai_recommendation($products_array, 'ai_generated_product_recommendations_sft');
		} else {
			$rvp_related_products = prwfr_get_combine_recommendation($products_array, 'ai_generated_product_recommendations_sft');
		}

		if (count($rvp_related_products) >= intval($desktop_products_limit)) {
			if (is_product()) {
				$curr_products        = (array) get_the_ID();
				$rvp_related_products = array_diff($rvp_related_products, $curr_products);
			}

			prwfr_display_products($rvp_related_products, intval($desktop_products_limit), intval($tab_products_limit), intval($mobile_products_limit), 'viewed-related', 'viewed_related');
		} else {
		?>
			<script>
				jQuery(document).ready(function() {
					jQuery('.prwfr-viewed-related-front-title').hide();
				})
			</script>
			<?php
		}
	} else {
		if (! intval(get_option('prwfr_viewed_related_hide_cookie'))) {

			if (isset($_SERVER['SERVER_NAME'])) {

				// Sanitize the server name to create a safe cookie name.
				$recently_viewed_products_cookie_name = sanitize_key($_SERVER['SERVER_NAME']);
				$recently_viewed_products_cookie_name = str_replace('.', '_', $recently_viewed_products_cookie_name);

				// Retrieve the option value using the sanitized cookie name.
				$recently_viewed_products_cookie_name = get_option('prwfr_' . $recently_viewed_products_cookie_name);
			}

			if (isset($_COOKIE[$recently_viewed_products_cookie_name])) {

				// Cookie array stores ids of products viewed by non logged in user.
				$products_array = sanitize_text_field(wp_unslash($_COOKIE[$recently_viewed_products_cookie_name]));
				$products_array = explode(',', $products_array);
				$products_array = array_reverse($products_array);
				$products_array = array_unique($products_array);

				if (count($products_array)) {
			?>

					<!-- Title for rvps related products in shortcode container -->
					<div class="prwfr-cookie-viewed-related-front-title prwfr-widget-title-container">
						<?php
						$title = get_option('prwfr_viewed_related_title');

						if (! $title) {
							// $title = 'Related to items you\'ve viewed';
							echo '<h2>' . esc_html__('Related to items you\'ve viewed', 'sft-product-recommendations-for-woocommerce') . '</h2>';
						} else {
							echo '<h2>' . esc_html($title) . '</h2>';
						}

						$page_id            = get_option('prwfr_viewed_related_page_id');
						$translated_page_id = prwfr_translate_woocommerce_title($page_id);
						?>

						<div class="prwfr-widget-inner-container">

							<span class="prwfr-see-more">
								<a href="<?php echo esc_url(get_permalink($translated_page_id)); ?>" onMouseOver="this.style.color='#CD5C5C'"
									onMouseOut="this.style.color='#4682B4'" style="text-decoration: underline; color: #4682B4; font-size: small !important;"><?php esc_html_e('See more', 'sft-product-recommendations-for-woocommerce'); ?></a>
							</span>

							<div class="prwfr-pagination-container">
								<div class="prwfr-cookie-viewed-related-page-display prwfr-page-display" style="font-size: medium;"><?php esc_html_e('Page no', 'sft-product-recommendations-for-woocommerce'); ?></div>
								<div class="prwfr-cookie-viewed-related-start-over prwfr-start-over" onMouseOver="this.style.color='#CD5C5C'"
									onMouseOut="this.style.color='#4682B4'" style="font-size: small; color: #4682B4; display:none; z-index:200;" data-name="cookie-viewed-related"><?php esc_html_e('Start over', 'sft-product-recommendations-for-woocommerce'); ?></div>
							</div>

						</div>
					</div>
					<?php

					// // Initialize an array to store all product category slugs.
					// $all_product_categories = array();

					// // Retrieves category slugs for rvps products.
					// foreach ( $products_array as $product_id ) {
					// 	if ( intval( $product_id ) !== 0 ) {
					// 		$product_categories = wp_get_post_terms( $product_id, 'product_cat' );
					// 		foreach ( $product_categories as $category ) {
					// 			// Add the category slug to the array of all slugs.
					// 			array_push( $all_product_categories, $category->slug );
					// 		}
					// 	}
					// }

					// // Remove duplicate slugs from the array.
					// $product_categories = array_unique( $all_product_categories );

					// // Retrieves all products containing acaltegories stored in $product_categories .
					// $args_viewed_related  = array(
					// 	'posts_per_page' => -1,
					// 	'post_type'      => 'product',
					// 	'post__not_in'   => $products_array,
					// 	'tax_query'      => array(
					// 		array(
					// 			'taxonomy' => 'product_cat',
					// 			'field'    => 'slug',
					// 			'terms'    => $product_categories,
					// 		),
					// 	),
					// );
					// $query_viewed_related = new WP_Query( $args_viewed_related );
					// foreach ( $query_viewed_related->posts as $post ) {
					// 	array_push( $rvp_related_products_array, $post->ID );
					// }

					if (get_option('prwfr_rvp_related_recommendation_mode') == 'ai_only') {

						$rvp_related_products_array = prwfr_get_ai_recommendation($products_array, 'ai_generated_product_recommendations_sft');
					} else {
						$rvp_related_products_array = prwfr_get_combine_recommendation($products_array, 'ai_generated_product_recommendations_sft');
					}

					if (count($rvp_related_products_array) >= intval($desktop_products_limit)) {

						if (is_product()) {
							$curr_products              = (array) get_the_ID();
							$rvp_related_products_array = array_diff($rvp_related_products_array, $curr_products);
						}

						prwfr_display_products($rvp_related_products_array, intval($desktop_products_limit), intval($tab_products_limit), intval($mobile_products_limit), 'cookie-viewed-related', 'viewed_related');
					} else {

					?>
						<script>
							jQuery(document).ready(function() {
								jQuery('.prwfr-cookie-viewed-related-front-title').hide();
							})
						</script>
		<?php

					}
				}
			}
		}
	}

	$content = ob_get_clean();
	return $content;
}

// ========================================= Product Discovery Features =========================================


add_shortcode('prwfr_all_onsale_products_front', 'prwfr_all_onsale_products_front');

/**
 * To showcase All items on sale in a single row, use a shortcode that arranges and displays the products accordingly.
 */
function prwfr_all_onsale_products_front()
{
	$all_onsale_product_ids  = array();
	$all_products_on_sale_id = wc_get_product_ids_on_sale(); // Retrieve all products on sale.
	$limit_desktop           = get_option('prwfr_all_onsale_desktop_limit');
	$limit_tab               = get_option('prwfr_all_onsale_tab_limit');
	$limit_mobile            = get_option('prwfr_all_onsale_mobile_limit');
	$page_id                 = get_option('prwfr_all_onsale_products_back_page_id');
	$translated_page_id      = prwfr_translate_woocommerce_title($page_id);
	if (intval($limit_desktop) === 0) {
		$limit_desktop = '4';
	}

	ob_start();

	if ($all_products_on_sale_id[0]) {

		$args = array(
			'posts_per_page' => -1,
			'post_type'      => 'product',
			'post__in'       => $all_products_on_sale_id,
		);

		$query = new WP_Query($args);

		$all_products_on_sale_id = array();
		foreach ($query->posts as $post) {
			array_push($all_products_on_sale_id, $post->ID);
		}

		$all_onsale_product_ids = $all_products_on_sale_id;

		?>
		<!-- Title for All products on sale in shortcode  container -->
		<div class="prwfr-all-onsale-front-title prwfr-widget-title-container">
			<?php
			$title = get_option('prwfr_all_onsale_title');
			if (! $title) {

				echo '<h2>' . esc_html__('Blockbuster deals', 'sft-product-recommendations-for-woocommerce') . '</h2>';
			} else {
				echo '<h2>' . esc_html($title) . '</h2>';
			}

			?>

			<div class="prwfr-widget-inner-container">
				<span class="prwfr-see-more">
					<a href="<?php echo esc_url(get_permalink($translated_page_id)); ?>" onMouseOver="this.style.color='#CD5C5C'" onMouseOut="this.style.color='#4682B4'" style="text-decoration: underline; color: #4682B4; font-size: small !important;"><?php esc_html_e('See more', 'sft-product-recommendations-for-woocommerce'); ?></a>
				</span>

				<div class="prwfr-pagination-container">
					<div class="prwfr-all-onsale-page-display prwfr-page-display" style="font-size: medium;"><?php esc_html_e('Page no', 'sft-product-recommendations-for-woocommerce'); ?></div>
					<div class="prwfr-all-onsale-start-over prwfr-start-over" onMouseOver="this.style.color='#CD5C5C'" onMouseOut="this.style.color='#4682B4'" style="font-size: small; display:none; z-index:200;" data-name="all-onsale"><?php esc_html_e('Start over', 'sft-product-recommendations-for-woocommerce'); ?></div>
				</div>
			</div>

		</div>

		<?php
		// Limit is no of products to display in single row in shortcode container, get the limit from setting page.
		if ((! is_user_logged_in() && (intval(get_option('prwfr_all_onsale_cookie_display')) || count($all_onsale_product_ids) < intval($limit_desktop))) || (is_user_logged_in() && count($all_onsale_product_ids) < intval($limit_desktop))) {
		?>
			<script>
				jQuery(document).ready(function() {
					jQuery(".prwfr-all-onsale-front-title").hide();
				})
			</script>
	<?php
		} else {
			if (is_product()) {
				$curr_product           = (array) get_the_ID();
				$all_onsale_product_ids = array_diff($all_onsale_product_ids, $curr_product);
			}

			prwfr_display_products($all_onsale_product_ids, intval($limit_desktop), intval($limit_tab), intval($limit_mobile), 'all-onsale', 'all_onsale');
		}
	}

	$content = ob_get_clean();
	return $content;
}

add_shortcode('prwfr_best_selling_front', 'prwfr_best_selling_front');

/**
 * To showcase  in a Best selling products in a single row, use a shortcode that arranges and displays the products accordingly.
 */
function prwfr_best_selling_front()
{
	$best_selling_id  = array();
	$best_selling_ids = array();
	$limit_desktop    = get_option('prwfr_best_selling_desktop_limit');
	$limit_tab        = get_option('prwfr_best_selling_tab_limit');
	$limit_mobile     = get_option('prwfr_best_selling_mobile_limit');

	if (intval($limit_desktop) === 0) {
		$limit_desktop = '4';
	}

	ob_start();

	$args = array(
		'post_type'      => 'product',
		'meta_key'       => 'total_sales', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		'orderby'        => 'meta_value_num',
		'order'          => 'DESC',
		'posts_per_page' => -1,
		'meta_query'     => array(
			array(
				'key'     => 'total_sales',
				'value'   => 1,
				'compare' => '>',
				'type'    => 'NUMERIC',
			),
		),
	);
	$loop = new WP_Query($args);

	foreach ($loop->posts as $post) {
		array_push($best_selling_id, $post->ID);
	}

	?>
	<div class="prwfr-best-selling-front-title prwfr-widget-title-container">
		<?php

		$title = get_option('prwfr_best_selling_title');
		if (! $title) {
			echo '<h2>' . esc_html__('Best Seller', 'sft-product-recommendations-for-woocommerce') . '</h2>';
		} else {
			echo '<h2>' . esc_html($title) . '</h2>';
		}
		$page_id            = get_option('prwfr_best_selling_back_page_id');
		$translated_page_id = prwfr_translate_woocommerce_title($page_id);
		?>

		<div class="prwfr-widget-inner-container">
			<span class="prwfr-see-more">
				<a href="<?php echo esc_url(get_permalink($translated_page_id)); ?>" onMouseOver="this.style.color='#CD5C5C'" onMouseOut="this.style.color='#4682B4'" style="text-decoration: underline; color: #4682B4; font-size: small !important;"><?php esc_html_e('See more', 'sft-product-recommendations-for-woocommerce'); ?></a>
			</span>

			<div class="prwfr-pagination-container">
				<div class="prwfr-best-selling-page-display prwfr-page-display" style="font-size: medium;"><?php esc_html_e('Page no', 'sft-product-recommendations-for-woocommerce'); ?></div>
				<div class="prwfr-best-selling-start-over prwfr-start-over" onMouseOver="this.style.color='#CD5C5C'" onMouseOut="this.style.color='#4682B4'" style="font-size: small; display:none; z-index:200;" data-name="best-selling"><?php esc_html_e('Start over', 'sft-product-recommendations-for-woocommerce'); ?></div>
			</div>
		</div>

	</div>
	<?php

	if ((! is_user_logged_in() && (intval(get_option('prwfr_best_selling_cookie_display')) || count($best_selling_id) < intval($limit_desktop)) || (is_user_logged_in() && count($best_selling_id) < intval($limit_desktop)))) {
	?>
		<script>
			jQuery(document).ready(function() {
				jQuery(".prwfr-best-selling-front-title").hide();
			})
		</script>
	<?php
	} else {
		if (is_product()) {
			$curr_product    = (array) get_the_ID();
			$best_selling_id = array_diff($best_selling_id, $curr_product);
		}

		prwfr_display_products($best_selling_id, intval($limit_desktop), intval($limit_tab), intval($limit_mobile), 'best-selling', 'best_selling');
	}

	$content = ob_get_clean();
	return $content;
}


add_shortcode('prwfr_featured_products_front', 'prwfr_featured_products_front');

/**
 * Function to display Featured Products in front shortcode
 */
function prwfr_featured_products_front()
{
	$featured_products_ids = wc_get_featured_product_ids();
	$featured_products_id  = array();
	$limit_desktop         = get_option('prwfr_featured_desktop_limit');
	$limit_tab             = get_option('prwfr_featured_tab_limit');
	$limit_mobile          = get_option('prwfr_featured_mobile_limit');

	if (intval($limit_desktop) === 0) {
		$limit_desktop = '4';
	}

	ob_start();

	?>

	<div class="prwfr-featured-front-title prwfr-widget-title-container">
		<?php

		$title = get_option('prwfr_featured_title');
		if (! $title) {
			echo '<h2>' . esc_html__('Featured Products', 'sft-product-recommendations-for-woocommerce') . '</h2>';
		} else {
			echo '<h2>' . esc_html($title) . '</h2>';
		}

		$page_id            = get_option('prwfr_featured_products_back_page_id');
		$translated_page_id = prwfr_translate_woocommerce_title($page_id);
		?>
		<div class="prwfr-widget-inner-container">

			<span class="prwfr-see-more">
				<a href="<?php echo esc_url(get_permalink($translated_page_id)); ?>" onMouseOver="this.style.color='#CD5C5C'" onMouseOut="this.style.color='#4682B4'" style="text-decoration: underline; color: #4682B4; font-size: small !important;"><?php esc_html_e('See more', 'sft-product-recommendations-for-woocommerce'); ?></a>
			</span>

			<div class="prwfr-pagination-container">
				<div class="prwfr-featured-page-display prwfr-page-display" style="font-size: medium;"><?php esc_html_e('Page no', 'sft-product-recommendations-for-woocommerce'); ?></div>
				<div class="prwfr-featured-start-over prwfr-start-over" onMouseOver="this.style.color='#CD5C5C'" onMouseOut="this.style.color='#4682B4'" style="font-size: small; display:none; z-index:200;" data-name="featured"><?php esc_html_e('Start over', 'sft-product-recommendations-for-woocommerce'); ?></div>
			</div>

		</div>

	</div>
	<?php

	if ((! is_user_logged_in() && (intval(get_option('prwfr_featured_cookie_display')) || count($featured_products_ids) < intval($limit_desktop))) || (is_user_logged_in() && count($featured_products_ids) < intval($limit_desktop))) {
	?>
		<script>
			jQuery(document).ready(function() {
				jQuery(".prwfr-featured-front-title").hide();
			})
		</script>
	<?php
	} else {
		if (is_product()) {
			$curr_product          = (array) get_the_ID();
			$featured_products_ids = array_diff($featured_products_ids, $curr_product);
		}

		prwfr_display_products($featured_products_ids, intval($limit_desktop), intval($limit_tab), intval($limit_mobile), 'featured', 'featured');
	}

	$content = ob_get_clean();
	return $content;
}

add_shortcode('prwfr_new_arrivals_front', 'prwfr_new_arrivals_front');

/**
 * To showcase  in a Best selling products in a single row, use a shortcode that arranges and displays the products accordingly.
 */
function prwfr_new_arrivals_front()
{
	$user_id         = get_current_user_id();
	$new_arrival_id  = array();
	$new_arrival_ids = array();
	$limit_desktop   = get_option('prwfr_new_arrivals_desktop_limit');
	$limit_tab       = get_option('prwfr_new_arrivals_tab_limit');
	$limit_mobile    = get_option('prwfr_new_arrivals_mobile_limit');
	$date_filter     = intval(get_option('prwfr_new_arrivals_days_filter'));

	if (intval($limit_desktop) === 0) {
		$limit_desktop = '4';
	}

	ob_start();

	$args = array(
		'post_type'      => 'product',
		'post_status'    => 'publish',
		'order_by'       => 'post_date',
		'order'          => 'DESC',
		'posts_per_page' => -1,
		'date_query'     => array(
			array(
				'after' => $date_filter . ' days ago',
			),
		),
	);
	$loop = new WP_Query($args);

	foreach ($loop->posts as $post) {
		array_push($new_arrival_id, $post->ID);
	}

	?>
	<div class="prwfr-new-arrival-front-title prwfr-widget-title-container">

		<?php
		// phrp - purchase history related.
		$title = get_option('prwfr_new_arrivals_title');
		if (! $title) {
			echo '<h2>' . esc_html__('New Arrivals', 'sft-product-recommendations-for-woocommerce') . '</h2>';
		} else {
			echo '<h2>' . esc_html($title) . '</h2>';
		}
		$page_id            = get_option('prwfr_new_arrivals_back_page_id');
		$translated_page_id = prwfr_translate_woocommerce_title($page_id);

		?>
		<div class="prwfr-widget-inner-container">

			<span class="prwfr-see-more">
				<a href="<?php echo esc_url(get_permalink($translated_page_id)); ?>" onMouseOver="this.style.color='#CD5C5C'" onMouseOut="this.style.color='#4682B4'" style="text-decoration: underline; color: #4682B4; font-size: small !important;"><?php esc_html_e('See more', 'sft-product-recommendations-for-woocommerce'); ?></a>
			</span>

			<div class="prwfr-pagination-container">
				<div class="prwfr-new-arrivals-page-display prwfr-page-display" style="font-size: medium;"><?php esc_html_e('Page no', 'sft-product-recommendations-for-woocommerce'); ?></div>
				<div class="prwfr-new-arrivals-start-over prwfr-start-over" onMouseOver="this.style.color='#CD5C5C'" onMouseOut="this.style.color='#4682B4'" style="font-size: small; display:none; z-index:200;" data-name="new-arrivals"><?php esc_html_e('Start over', 'sft-product-recommendations-for-woocommerce'); ?></div>
			</div>

		</div>

	</div>
	<?php

	if ((! is_user_logged_in() && (intval(get_option('prwfr_new_arrivals_cookie_display')) || count($new_arrival_id) < intval($limit_desktop))) || (is_user_logged_in() && count($new_arrival_id) < intval($limit_desktop))) {
	?>
		<script>
			jQuery(document).ready(function() {
				jQuery(".prwfr-new-arrival-front-title").hide();
			})
		</script>
<?php
	} else {
		if (is_product()) {
			$curr_product   = (array) get_the_ID();
			$new_arrival_id = array_diff($new_arrival_id, $curr_product);
		}
		prwfr_display_products($new_arrival_id, intval($limit_desktop), intval($limit_tab), intval($limit_mobile), 'new-arrivals', 'new_arrivals');
	}

	$content = ob_get_clean();
	return $content;
}

?>