<?php

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

add_shortcode('prwfr_recently_viewed_products_back', 'prwfr_recently_viewed_products_back');

/**
 * Function to display all recently viewed products in a page.
 */
function prwfr_recently_viewed_products_back()
{

	global $wpdb;
	$user_id             = get_current_user_id();
	$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';
	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();

		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;

		$browse_history = get_user_meta($user_id, 'browsing_history_on_off_' . $user_id, true);
?>

		<div class="prwfr-products-wrapdiv-back">
			<!-- Manage history container appears on top right corner of page  -->

			<div class="prwfr-manage-history-div" style="margin: 20px 0px;">
				<div class="prwfr-manage-history" onMouseOver="this.style.color='#CD5C5C'"
					onMouseOut="this.style.color='#4682B4'" style="text-decoration: underline; cursor: pointer;"><?php esc_html_e('Manage History', 'sft-product-recommendations-for-woocommerce'); ?></div>
				<div class="prwfr-browsing-history-switch-div" style="display: flex; align-items:center; gap: 8px; margin: 10px 0px;"><?php echo esc_html__('Turn On or Off Browsing History', 'sft-product-recommendations-for-woocommerce'); ?>

					<label class="switch" style="margin: 0px;">
						<!-- Switch for browsing history -->
						<input type="checkbox" class="prwfr-browsing-history-switch-display" name="<?php echo esc_html('browsing_history_on_off_') . esc_attr($user_id); ?>" value="1" <?php echo checked('1', esc_attr($browse_history), false); ?> style="padding-right: 12px;">
						<span class="slider round prwfr-browing-history-user"></span>
					</label>
				</div>

				<!-- Button to remove all products from the page -->
				<div>
					<input type="button" class="prwfr-rvps-remove-all-btn" value="<?php esc_html_e('Remove All Products', 'sft-product-recommendations-for-woocommerce'); ?>" style="padding: 10px; margin-bottom: 7px;" />
				</div>

			</div>

			<div class="prwfr-back-product-parent">
				<?php

				// If last element of $rvp_product_ids_temp is empty.
				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)) {
					echo '<p>' . esc_html__('These items were viewed recently. We use them to personalise recommendations.', 'sft-product-recommendations-for-woocommerce') . '</p>';

				?>

					<div class="prwfr-products-wrapdiv-back">
						<div class="prwfr-back-product-parent">
							<div class="prwfr-back-product-container">
								<?php
								prwfr_get_back_shortcode_products($rvp_product_ids_temp, 'rvps');
								?>
							</div>
						</div>
					</div>
				<?php
				} else {
				?>
					<div class="prwfr-back-page-text-container">
						<?php echo esc_html__('You Have No Recently Viewed Items.', 'sft-product-recommendations-for-woocommerce'); ?>
					</div>
				<?php
				}
				?>
			</div>
		</div>
		<?php

	} else {

		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);
		?>

			<div class="prwfr-products-wrapdiv-back">
				<div class="prwfr-back-product-parent">
					<div class="prwfr-back-product-container">
						<?php
						prwfr_get_back_shortcode_products($products_array, 'rvps');
						?>
					</div>
				</div>
			</div>
		<?php

		} else {
		?>
			<div class="prwfr-back-page-text-container">
				<?php echo esc_html__('You Have Not Viewed Any Product Yet!', 'sft-product-recommendations-for-woocommerce'); ?>
			</div>
			<?php
		}
	}

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

add_shortcode('prwfr_onsale_recently_viewed_products_back', 'prwfr_onsale_recently_viewed_products_back');

/**
 * Function to display all recently viewed products and realted on sale.
 */
function prwfr_onsale_recently_viewed_products_back()
{

	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();
	$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';
	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);

			// Store the categories slug of recently viewed products.
			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);

			// Retrieve all products on sale which have categories from $onsale_products_with_slug in them.
			$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);
			}

			$rvps_onsale_products_id = $rvp_onsale_products_array;

			if (! count($rvps_onsale_products_id)) {
			?>
				<div class="prwfr-back-page-text-container">
					<?php echo esc_html__('Please View More Products!', 'sft-product-recommendations-for-woocommerce'); ?>
				</div>
			<?php
			} else {
			?>
				<div class="prwfr-products-wrapdiv-back">
					<div class="prwfr-back-product-parent">
						<div class="prwfr-back-product-container">
							<?php
							prwfr_get_back_shortcode_products($rvps_onsale_products_id, 'rvps_onsale');
							?>
						</div>
					</div>
				</div>
				<?php
			}
		} else {

			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);

				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);

				// Get products which are on sale and have categories 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)) {
				?>
					<div class="prwfr-back-page-text-container">
						<?php echo esc_html__('Please View More Products!', 'sft-product-recommendations-for-woocommerce'); ?>
					</div>
				<?php
				} else {
				?>
					<div class="prwfr-products-wrapdiv-back">
						<div class="prwfr-back-product-parent">
							<div class="prwfr-back-product-container">
								<?php
								// Recently viewed prdoucts and related on sale displayed on a page.
								prwfr_get_back_shortcode_products($rvp_onsale_products_array, 'rvps_onsale');
								?>
							</div>
						</div>
					</div>
				<?php
				}
			} else {
				?>
				<div class="prwfr-back-page-text-container">
					<?php echo esc_html__('You Have Not Browsed Any Product Yet!', 'sft-product-recommendations-for-woocommerce'); ?>
				</div>
			<?php
			}
		}
	}

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

add_shortcode('prwfr_related_recently_viewed_products_back', 'prwfr_related_recently_viewed_products_back');

/**
 * Function to display Products related to recently viewed products.
 */
function prwfr_related_recently_viewed_products_back()
{

	global $wpdb;
	$user_id                    = get_current_user_id();
	$product_categories         = array();
	$rvp_related_products_array = array();
	$products_array             = array();
	$rvp_related_products       = 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';

	ob_start();

	if (is_user_logged_in()) {

		$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);

		// // Store category slug of products that are recently viewed.
		// foreach ( $products_array as $product_id ) {
		// 	if ( intval( $product_id ) !== 0 ) {
		// 		$product          = wc_get_product( $product_id );
		// 		$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 );

		// // Retrieve all the products having categories from $product_categories .
		// $args  = 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 = new WP_Query( $args );

		// foreach ( $query->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)) {
			?>
			<div class="prwfr-back-page-text-container">
				<?php echo esc_html__('Please View More Products!', 'sft-product-recommendations-for-woocommerce'); ?>
			</div>
		<?php
		} else {
		?>
			<div class="prwfr-products-wrapdiv-back">
				<div class="prwfr-back-product-parent">
					<div class="prwfr-back-product-container">
						<?php
						// Display all products related to recently viewed products in a page.
						prwfr_get_back_shortcode_products($rvp_related_products, 'viewed_related');
						?>
					</div>
				</div>
			</div>
			<?php
		}
	} else {

		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);

			// // 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 );

			// // Retrieve all the products having categories from $product_categories .
			// $args = 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 = new WP_Query( $args );

			// foreach ( $query->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)) {
			?>
				<div class="prwfr-back-page-text-container">
					<?php echo esc_html__('Please View More Products!', 'sft-product-recommendations-for-woocommerce'); ?>
				</div>
			<?php
			} else {
			?>
				<div class="prwfr-products-wrapdiv-back">
					<div class="prwfr-back-product-parent">
						<div class="prwfr-back-product-container">
							<?php
							prwfr_get_back_shortcode_products($rvp_related_products_array, 'viewed_related');
							?>
						</div>
					</div>
				</div>
			<?php
			}
		} else {
			?>
			<div class="prwfr-back-page-text-container">
				<?php echo esc_html__('You Have Not Browsed Any Product Yet!', 'sft-product-recommendations-for-woocommerce'); ?>
			</div>
		<?php
		}
	}

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

// --------------------------------------------------   Product Discovery Features -------------------------------------------

add_shortcode('prwfr_all_onsale_products_back', 'prwfr_all_onsale_products_back');

/**
 * Function to display all products on sale in one page.
 *
 * @return $content
 */
function prwfr_all_onsale_products_back()
{

	$all_onsale_product_ids = array();

	// Retrieve all products on sale.
	$all_products_on_sale_id = wc_get_product_ids_on_sale();

	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;

		if (! count($all_onsale_product_ids)) {
		?>
			<div class="prwfr-back-page-message-container">
				<?php echo esc_html__('Products on sale are not available currently!', 'sft-product-recommendations-for-woocommerce'); ?>
			</div>
		<?php
		} else {
		?>
			<div class="prwfr-products-wrapdiv-back">
				<div class="prwfr-back-product-parent">
					<div class="prwfr-back-product-container">
						<?php
						// Display all products on a page.
						prwfr_get_back_shortcode_products($all_onsale_product_ids, 'all_onsale');
						?>
					</div>
				</div>
			</div>
		<?php
		}
	} else {
		?>
		<div class="prwfr-back-page-message-container">
			<?php echo esc_html__('Products on sale are not available currently!', 'sft-product-recommendations-for-woocommerce'); ?>
		</div>
	<?php
	}

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


add_shortcode('prwfr_featured_products_back', 'prwfr_featured_products_back');

/**
 * Function to display Featured products in back shortcode
 */
function prwfr_featured_products_back()
{

	$featured_products_ids = wc_get_featured_product_ids();
	$featured_products_id  = array();

	ob_start();

	if (! empty($featured_products_ids)) {
	?>
		<div class="prwfr-products-wrapdiv-back">
			<div class="prwfr-back-product-parent">
				<div class="prwfr-back-product-container">
					<?php

					// Display all products on a page.
					prwfr_get_back_shortcode_products($featured_products_ids, 'featured');
					?>
				</div>
			</div>
		</div>
	<?php
	} else {
	?>
		<div class="prwfr-back-page-message-container">
			<?php echo esc_html__('Featured Products are currently unavailable!', 'sft-product-recommendations-for-woocommerce'); ?>
		</div>
	<?php
	}

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


add_shortcode('prwfr_new_arrivals_back', 'prwfr_new_arrivals_back');

/**
 * Function to display Newly Arrived Products
 */
function prwfr_new_arrivals_back()
{

	$new_arrival_id  = array();
	$new_arrival_ids = array();
	$date_filter     = intval(get_option('prwfr_new_arrivals_days_filter'));

	ob_start();

	// Retrieve all the products in desc order of their publish date.
	$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);
	}

	// Get option to filter product on the basis of categories, tags and individual pick.
	$check_mode = get_option('prwfr_new_arrivals_display_radio');

	if ('categories' === $check_mode || 'tags' === $check_mode) {
		$cat_include = 'prwfr_new_arrivals_category_selection';
		$tag_include = 'prwfr_new_arrivals_tag_selection';
		$cat_exclude = '';
		$tag_exclude = '';

		// $new_arrival_ids = prwfr_category_tag_filter( $new_arrival_id, $cat_include, $cat_exclude, $tag_include, $tag_exclude );
		if (intval($new_arrival_ids[0])) {
			$new_arrival_id = $new_arrival_ids;
		}
	}

	if ('individual' === $check_mode) {
		$new_arrival_ids = get_option('prwfr_new_arrivals_individual_selection');
		$new_arrival_id  = $new_arrival_ids;
	}

	if (! empty($new_arrival_id)) {
	?>
		<div class="prwfr-products-wrapdiv-back">
			<div class="prwfr-back-product-parent">
				<div class="prwfr-back-product-container">
					<?php

					// Display all products on a page.
					prwfr_get_back_shortcode_products($new_arrival_id, 'new_arrivals');
					?>
				</div>
			</div>
		</div>
	<?php
	} else {
	?>
		<div class="prwfr-back-page-message-container">
			<?php echo esc_html__('Newly Arrived Products are currently unavailable!', 'sft-product-recommendations-for-woocommerce'); ?>
		</div>
	<?php
	}

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


add_shortcode('prwfr_best_selling_back', 'prwfr_best_selling_back');

/**
 * Function to display Best Selling Products.
 */
function prwfr_best_selling_back()
{
	$best_selling_id  = array();
	$best_selling_ids = array();

	ob_start();

	// Retrieve all Products in desc order of their total sales.
	$args = array(
		'post_type'      => 'product',
		'meta_key'       => 'total_sales', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key.
		'order'          => 'DESC',
		'orderby'        => 'meta_value_num',
		'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);
	}

	if (! empty($best_selling_id)) {
	?>
		<div class="prwfr-products-wrapdiv-back">
			<div class="prwfr-back-product-parent">
				<div class="prwfr-back-product-container">
					<?php
					// Display all products on a page.
					prwfr_get_back_shortcode_products($best_selling_id, 'best_selling');
					?>
				</div>
			</div>
		</div>
	<?php
	} else {
	?>
		<div class="prwfr-back-page-message-container">
			<?php echo esc_html__('Best Selling Products are currently unavailable!', 'sft-product-recommendations-for-woocommerce'); ?>
		</div>
<?php
	}

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

?>