<?php


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

/**
 * AI Popup showing.
 *
 * @return void
 */
function prwfr_ai_script()
{
	$all_products = prwfr_get_all_products();
	// Get all WooCommerce product categories.
	$product_categories    = get_terms(
		array(
			'taxonomy'   => 'product_cat',
			'hide_empty' => false,
		)
	);
	$selected_products     = get_option('prwfr_product_selection');
	$selected_categories   = get_option('prwfr_category_selection');
	$time_interval         = get_option('prwfr_ai_recommendations_weekly_time');
	$days_of_week          = array(__('Monday', 'sft-product-recommendations-for-woocommerce'), __('Tuesday', 'sft-product-recommendations-for-woocommerce'), __('Wednesday', 'sft-product-recommendations-for-woocommerce'), __('Thursday', 'sft-product-recommendations-for-woocommerce'), __('Friday', 'sft-product-recommendations-for-woocommerce'), __('Saturday', 'sft-product-recommendations-for-woocommerce'), __('Sunday', 'sft-product-recommendations-for-woocommerce'));
	$value                 = get_option('prwfr_ai_recommendations_everyweek');
	$display_prompt        = get_option('prwfr_ai_request_prompt') ? get_option('prwfr_ai_request_prompt') : get_option('prwfr_default_ai_prompt');
	$tokens_used           = get_option('prwfr_tokens_used') ? get_option('prwfr_tokens_used') : '2000';
	$validation_key_status = get_option('prwfr_api_valid_key_status') ? get_option('prwfr_api_valid_key_status') : '';

	// Response status.
	$key_response_status = get_option('prwfr_api_request_created_status') ? get_option('prwfr_api_request_created_status') : '';

	// Required data for module selection.
	$model_name = get_option('prwfr_openai_api_model') ? get_option('prwfr_openai_api_model') : '';

	$info                  = prwfr_get_token();
	$model_max_token_limit = prwfr_get_token('usable_input_tokens');

	// Api settings page url.
	$api_settings_page = admin_url('admin.php?page=prwfr_api_setting_page');

?>
	<script>
		modelName = "<?php echo esc_js($model_name); ?>";
		modelMaxTokenLimit = <?php echo (int) $model_max_token_limit; ?>;
		prwfrNonce = "<?php echo esc_attr(wp_create_nonce('sft-product-recommendations-for-woocommerce')); ?>";

		function prwfrAiPopup() {
			Swal.fire({
				title: '<div class="prwfr-ai-popup-header"><?php echo esc_html__('AI PRODUCT RECOMMENDATIONS', 'sft-product-recommendations-for-woocommerce'); ?></div>',
				showCloseButton: true,
				html: `
				<div class="prwfr-tabs-container">
					<!-- Tab Progress Indicators -->
					<div class="prwfr-tab-dots">
						<div class="prwfr-ai-page-progress-line"></div>
						<div class="prwfr-ai-page-progress-line-fill" style="width:0%;"></div>
						<span class="prwfr-ai-page-dot active" data-tab="tab1">1</span>
						<span class="prwfr-ai-page-dot" data-tab="tab2">2</span>
						<span class="prwfr-ai-page-dot" data-tab="tab3">3</span>
					</div>

					<!-- TAB 1 -->
					<div class="prwfr-tab-content active" data-tab="tab1">
						<?php // TAB 1: Product Selection and Store Info. 
						?>

						<?php
						do_action(
							'prwfr_ai_prompt_content_tab_1',
							$all_products,
							$product_categories,
							$selected_products,
							$selected_categories,
							$time_interval,
							$days_of_week,
							$value,
							$display_prompt,
							$tokens_used
						);
						?>
						<div class="prwfr-tab-actions" style="display:flex; justify-content:right;">
							<button id="prwfr-next-tab1" class="prwfr-btn">Next</button>
						</div>
					</div>

					<!-- TAB 2 -->
					<div class="prwfr-tab-content" data-tab="tab2">
						<?php // TAB 2: Schedule and Actions. 
						?>
						<?php
						do_action(
							'prwfr_ai_prompt_content_tab_2',
							$all_products,
							$product_categories,
							$selected_products,
							$selected_categories,
							$time_interval,
							$days_of_week,
							$value,
							$display_prompt,
							$tokens_used
						);
						?>
						<div class="prwfr-tab-actions" style="display: flex; justify-content: space-between; margin-top: 20px;">
							<button id="prwfr-back-tab2" class="prwfr-btn">Back</button>
							<button id="prwfr-next-tab2" class="prwfr-btn">Next</button>
						</div>
					</div>

					<!-- TAB 3 -->
					<div class="prwfr-tab-content" data-tab="tab3">
						<?php // TAB 3: Additional Instructions. 
						?>
						<?php
						do_action(
							'prwfr_ai_prompt_content_tab_3',
							$all_products,
							$product_categories,
							$selected_products,
							$selected_categories,
							$time_interval,
							$days_of_week,
							$value,
							$display_prompt,
							$tokens_used
						);
						?>
						<div class="prwfr-tab-actions" style="display: flex; justify-content: space-between; margin-top: 20px;">
							<button id="prwfr-back-tab3" class="prwfr-btn">Back</button>
						</div>
					</div>

				</div>`,
				customClass: "prwfr-popup",
				showConfirmButton: false,
				didOpen: function() {

					(function(jQuery) {
						$
						const totalTabs = jQuery('.prwfr-ai-page-dot').length; // 3 steps.

						function updateProgress(tabId) {
							const idx = parseInt(tabId.replace('tab', ''), 10); // 1-based.
							const pct = ((idx - 1) / (totalTabs - 1)) * 100; // 0-100.
							jQuery('.prwfr-ai-page-progress-line-fill').css('width', pct + '%');

							jQuery('.prwfr-ai-page-dot').each(function(i) {
								const step = i + 1;
								jQuery(this).removeClass('active completed');
								if (step < idx) {
									jQuery(this).addClass('completed');
								} else if (step === idx) {
									jQuery(this).addClass('active');
								}
							});
						}

						window.switchTab = function(tabId) {
							jQuery('.prwfr-tab-content').removeClass('active');
							jQuery('.prwfr-tab-content[data-tab="' + tabId + '"]').addClass('active');
							updateProgress(tabId);
						};

						/* ----- click handlers inside SweetAlert2 container ----- */
						jQuery('.swal2-container')

							// Clickable dots.
							.on('click', '.prwfr-ai-page-dot', function() {
								switchTab(jQuery(this).data('tab'));
							})

							// Next / Back buttons.
							.on('click', '#prwfr-next-tab1', () => switchTab('tab2'))
							.on('click', '#prwfr-back-tab2', () => switchTab('tab1'))
							.on('click', '#prwfr-next-tab2', () => switchTab('tab3'))
							.on('click', '#prwfr-back-tab3', () => switchTab('tab2'));

						// initialise.
						updateProgress('tab1');

					})(jQuery);

				}
			})
		}

		jQuery('.prwfr-ai-recommendations').click(function(e) {
			e.preventDefault();

			let validation_status = '<?php echo esc_js($validation_key_status); ?>';

			// Response status.
			let response_status = '<?php echo esc_js($key_response_status); ?>';

			if (validation_status != 1) {

				// For invalid Api key.
				Swal.fire({
					text: '<?php echo esc_html__('Please Enter Your Valid API Key First !', 'sft-product-recommendations-for-woocommerce'); ?>',
					icon: "warning",
					showCancelButton: true,
					confirmButtonColor: "#3085d6",
					cancelButtonColor: "#d33",
					confirmButtonText: '<?php echo esc_html__('Configure API Key', 'sft-product-recommendations-for-woocommerce'); ?>'
				}).then((result) => {
					if (result.isConfirmed) {

						// Move to Api key settings page.
						window.location.assign('<?php echo esc_url($api_settings_page); ?>');
					}
				});
			} else {

				if (response_status != 'insufficient_quota') {

					if ((response_status != 'created') && (response_status != 'pending')) {
						prwfrAiPopup();

						// jQuery( '.prwfr_product_selection').multiSelect();
						jQuery('#prwfr_product_selection').multipleSelect({
							filter: true,
							placeholder: "Select Products",
							selectAll: false, // disable select all
							single: false,
							minimumCountSelected: 1,

							onOpen: function() {
								setTimeout(function() {
									prwfrDisableProductOptionsAfterLimit();
								}, 50);
							},

							onFilter: function() {
								setTimeout(function() {
									prwfrDisableProductOptionsAfterLimit();
								}, 50);
							}
						});

						jQuery('#prwfr_ai_request_prompt').closest('div').css('pointer-events', 'none');
						//Disable all remaining products after limit is reached

						jQuery(document).on('keyup', '#prwfr_about_store', function() {
							prwfrUpdateAiToken();
							// prwfrUpdateAiToken();

						});

						jQuery('#prwfr_products_desc').change(function() {
							prwfrUpdateAiToken();
							// prwfrUpdateAiToken();

						});

						function prwfrDisableProductOptionsAfterLimit() {

							let selectedProducts = jQuery('#prwfr_product_selection').multipleSelect('getSelects');

							let $dropdown = jQuery('#prwfr_product_selection')
								.next('.ms-parent')
								.find('.ms-drop');

							if (selectedProducts.length >= 5) {

								$dropdown.find('input[type="checkbox"]').each(function() {

									let checkboxValue = jQuery(this).val();

									if (selectedProducts.indexOf(checkboxValue) === -1) {
										jQuery(this).prop('disabled', true);
										jQuery(this).closest('li').addClass('disabled');
									}
								});

							} else {

								$dropdown.find('input[type="checkbox"]').prop('disabled', false);
								$dropdown.find('li').removeClass('disabled');
							}
						}

						jQuery(document).on('keyup input', '.ms-search input', function() {
							setTimeout(function() {
								prwfrDisableProductOptionsAfterLimit();
							}, 50);
						});

						jQuery(document).on('change', 'select.prwfr_product_selection', function() {

							prwfrDisableProductOptionsAfterLimit();

							prwfrUpdateAiToken();
						});

						setTimeout(function() {
							prwfrDisableProductOptionsAfterLimit();
						}, 100);

						jQuery(document).on('change', 'input[name=prwfr_ai_prompt_type]', function() {
							if (jQuery('input[name=prwfr_ai_prompt_type]:checked').val() == 'default') {
								jQuery('textarea#prwfr_ai_request_prompt').val('')
								jQuery('textarea#prwfr_ai_request_prompt').val('<?php echo esc_js(get_option('prwfr_default_ai_prompt')); ?>').attr('disabled', 'disabled');
								jQuery('#prwfr_textarea_container.prwfr-ai-prompt-container, .prwfr-prompt-placeholder-container').slideUp();
							} else if (jQuery('input[name=prwfr_ai_prompt_type]:checked').val() == 'edit') {
								jQuery('#prwfr_textarea_container.prwfr-ai-prompt-container, .prwfr-prompt-placeholder-container').slideDown();
								jQuery('textarea#prwfr_ai_request_prompt').removeAttr('disabled');
							}
						})

						if (jQuery('input[name=prwfr_ai_prompt_type]:checked').val() == 'default') {
							jQuery('textarea#prwfr_ai_request_prompt').val('')
							jQuery('textarea#prwfr_ai_request_prompt').val('<?php echo esc_js(get_option('prwfr_default_ai_prompt')); ?>').attr('disabled', 'disabled');
							jQuery('#prwfr_textarea_container.prwfr-ai-prompt-container, .prwfr-prompt-placeholder-container').hide();

						} else if (jQuery('input[name=prwfr_ai_prompt_type]:checked').val() == 'edit') {
							jQuery('#prwfr_textarea_container.prwfr-ai-prompt-container, .prwfr-prompt-placeholder-container').show();
							jQuery('textarea#prwfr_ai_request_prompt').removeAttr('disabled');
							jQuery('textarea#prwfr_ai_request_prompt').val('');
							jQuery('textarea#prwfr_ai_request_prompt').val('<?php echo esc_js(get_option('prwfr_ai_request_prompt')); ?>');
						}

						jQuery(document).on('click', '#prwfr_undo_ai_changes', function() {
							jQuery(".prwfr-ai-recommendations").click();
						});

						jQuery(document).on('change', '#prwfr_multiple_categories_check', function() {
							if (jQuery('#prwfr_multiple_categories_check').is(':checked')) {
								jQuery('.prwfr-all-cat-selection').slideDown(200);
							} else {
								jQuery('.prwfr-all-cat-selection').slideUp(200);
							}
						})

						jQuery(document).on('change', '#prwfr_multiple_products_check', function() {
							if (jQuery('#prwfr_multiple_products_check').is(':checked')) {
								jQuery('.prwfr-products-selection').slideDown(200);
							} else {
								jQuery('.prwfr-products-selection').slideUp(200);
							}
						})

						if (jQuery('#prwfr_multiple_categories_check').is(':checked')) {
							jQuery('.prwfr-all-cat-selection').show();
						} else {
							jQuery('.prwfr-all-cat-selection').hide();
						}

						if (jQuery('#prwfr_multiple_products_check').is(':checked')) {
							jQuery('.prwfr-products-selection').show();
						} else {
							jQuery('.prwfr-products-selection').hide();
						}

						jQuery(document).on('click', '#prwfr_reset_ai_settings', function() {

							let saveSettings = prwfrGetSelectedOptions();

							jQuery('#prwfr_reset_ai_settings').empty().text('<?php echo esc_html__('Resetting..', 'sft-product-recommendations-for-woocommerce'); ?>');
							jQuery('input[name="prwfr_recurrence_period_ai"][value="one_time"]').prop('checked', true);
							jQuery('input[name="prwfr_all_products"]').prop('checked', true);
							jQuery('input[name="prwfr_multiple_products_check"]').prop('checked', true);
							jQuery('input[name="prwfr_fbt_data"]').prop('checked', false);
							jQuery('input[name="prwfr_products_name"]').prop('checked', true);
							jQuery('input[name="prwfr_products_desc"]').prop('checked', true);
							jQuery('input[name="prwfr_multiple_categories_check"]').prop('checked', false);
							jQuery('input[name="prwfr_products_price"]').prop('checked', false);
							jQuery('input[name="prwfr_products_url"]').prop('checked', false);
							jQuery('input[name="prwfr_products_desc_long"]').prop('checked', false);
							jQuery('input[name="prwfr_products_categories"]').prop('checked', false);
							jQuery('input[name=prwfr_weekly_save_recommendations]').prop('checked', false);

							jQuery.ajax({
								url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>', // Use a localized variable for the AJAX URL
								type: 'POST',
								data: {
									action: 'prwfr_ai_help',
									reset_settings: 1,
									prwfr_ajax_nonce: prwfrNonce,
								},
								success: function(response) {
									jQuery('#prwfr_reset_ai_settings').empty().text('<?php echo esc_html__('Reset to Default', 'sft-product-recommendations-for-woocommerce'); ?>');
								}
							})
						})


						// Get all category ids.
						let catIds = new Set();
						let productIds = new Set();

						// Example of how to populate productIds and catIds
						jQuery('#prwfr_product_selection').change(function() {

							productIds.clear();

							jQuery.each(jQuery('select.prwfr_product_selection option:selected'), function() {
								productIds.add(jQuery(this).val());
							});

						});

						// Initialize the parent checkbox state
						jQuery(document).on('click', '#prwfr_save_ai_settings', function() {

							let saveSettings = prwfrGetSelectedOptions();
							// Define the loader icon (replace with actual loader HTML or an <img> tag)
							let loaderIcon = '<span class="fa fa-spinner fa-spin"></span>'; // Example using FontAwesome
							let loaderElement = jQuery('.prwfr-ai-save-loader');

							// Clear the existing content and append the loader icon
							loaderElement.empty().append(loaderIcon);

							// Set a timeout to remove the loader after 2000ms
							setTimeout(function() {
								loaderElement.empty(); // Remove the loader after 2 seconds

								// Display "Saved" message
								// loaderElement.append('Saved');

								// Set another timeout to remove the "Saved" message after 2000ms
								setTimeout(function() {
									loaderElement.empty(); // Remove "Saved" after 2 seconds
								}, 5000);
							}, 5000); // This timeout is for the loader
						})

						jQuery('.prwfr-ai-request-warning').empty();

						jQuery(document).on('click', '#prwfr-send-prompt-btn', function(e) {
							e.preventDefault();
							console.log("HELLO");

							let createRequest = prwfrGetSelectedOptions();

							jQuery('#prwfr-send-prompt-btn').empty().text('<?php echo esc_html__('Requesting.......', 'sft-product-recommendations-for-woocommerce'); ?>');


							if (createRequest.sendPrompt == 1) {
								jQuery.ajax({
									url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>', // Use a localized variable for the AJAX URL.
									type: 'POST',
									data: {
										action: 'prwfr_ai_help',
										create_request: 1,
										prwfr_ajax_nonce: prwfrNonce,
									},
									success: function(response) {

										Swal.fire({
											title: "",
											text: "<?php echo esc_js(__('Your request was initiated successfully!', 'sft-product-recommendations-for-woocommerce')); ?>",

											icon: "success",
											customClass: "prwfr-request-sent",
										}).then(() => {
											location.reload(); // This will refresh the page after the Swal modal is closed
										});
									},
								})
							} else {
								jQuery('#prwfr-send-prompt-btn').empty().text('<?php echo esc_js(__('Create Request', 'sft-product-recommendations-for-woocommerce')); ?>');

								jQuery('.prwfr-ai-request-warning').empty().text(createRequest.invalidMessage);
							}
						});

						var tokensUsed = <?php echo (int) get_option('prwfr_tokens_used'); ?>;

						/* translators: %d: maximum token limit */
						jQuery('.prwfr-token-status').text(tokensUsed + ' <?php /* translators: %d: maximum token limit */ echo esc_js(sprintf(__('tokens will be used out of %d', 'sft-product-recommendations-for-woocommerce'), (int) $model_max_token_limit)); ?>');

						// Get selected product ids.
						function prwfrGetSelectedProductIds() {
							let selectedProducts = jQuery('#prwfr_product_selection').val();

							if (!Array.isArray(selectedProducts)) {
								selectedProducts = selectedProducts ? [selectedProducts] : [];
							}

							return selectedProducts;
						}

						// Save AI Info.
						function prwfr_SaveAiInfo() {

							let sendPrompt = {
								sendPrompt: 1,
								invalidMessage: ""
							};

							let productIdsArray = prwfrGetSelectedProductIds();

							// // Convert the Set to an array
							// let productIdsArray = Array.from(productIds);

							// // Convert the Set to an array
							let catIdsArray = Array.from(catIds);

							if (productIdsArray.length == 0) {
								productIdsArray = jQuery('#prwfr_product_selection').val();
							}

							if (catIdsArray.length == 0) {
								catIdsArray = jQuery('#prwfr_category_selection').val();
							}

							let prwfrRecurrencePeriod = jQuery('input[name=prwfr_recurrence_period_ai]:checked').val();
							let prwfrSaveWeeklyRecommendations = jQuery('input[name=prwfr_weekly_save_recommendations]:checked').val();
							let prwfrAllProducts = jQuery('input[name=prwfr_all_products]:checked').val();
							let prwfrMultipleProducts = jQuery('input[name=prwfr_multiple_products_check]:checked').val();
							let prwfrMultipleCategories = jQuery('input[name=prwfr_multiple_categories_check]:checked').val();
							let prwfrFbtData = jQuery('input[name=prwfr_fbt_data]:checked').val();
							let prwfrProductsUrl = jQuery('input[name=prwfr_products_url]:checked').val();
							let prwfrProductsPrice = jQuery('input[name=prwfr_products_price]:checked').val();
							let prwfrProductsName = jQuery('input[name=prwfr_products_name]:checked').val();
							let prwfrProductsDesc = jQuery('input[name=prwfr_products_desc]:checked').val();
							let prwfrProductsDescLong = jQuery('input[name=prwfr_products_desc_long]:checked').val();
							let prwfrProductsCategories = jQuery('input[name=prwfr_products_categories]:checked').val();
							let prwfrManualWeeklyDay = jQuery('select[name=prwfr_ai_recommendations_everyweek]').val();
							let prwfrManualWeeklyTime = jQuery('input[name=prwfr_ai_recommendations_weekly_time]').val();
							let prwfrManualWeeklyEmail = jQuery('input[name=prwfr_ai_admin_email]').val();
							let prwfrAboutStore = jQuery('textarea#prwfr_about_store').val();
							let prwfrPrompt = 'Here is selected products data set: {selected_products} and here is all products data set {all_products} and here is frequently purchased products data {fbt_products}  and suggest {recommendation_count} recommendations for each product from this selected products data set from the all products data set.';
							let prwfrAiPromptType = 'default';
							// let prwfrActivateAiRecommendations = jQuery( 'input[name=prwfr_activate_ai_recommendations]:checked').val();

							return jQuery.ajax({
								url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>', // Use a localized variable for the AJAX URL
								type: 'POST',
								data: {
									action: 'prwfr_ai_help',
									prwfr_ajax_nonce: prwfrNonce,
									save_settings: 1,
									prwfr_category_selection: catIdsArray,
									prwfr_product_selection: productIdsArray,
									prwfr_recurrence_period_ai: prwfrRecurrencePeriod,
									prwfr_save_weekly_recommendations: prwfrSaveWeeklyRecommendations,
									prwfr_all_products: prwfrAllProducts,
									prwfr_multiple_products_check: prwfrMultipleProducts,
									prwfr_multiple_categories_check: prwfrMultipleCategories,
									prwfr_fbt_data: prwfrFbtData,
									prwfr_products_url: prwfrProductsUrl,
									prwfr_products_price: prwfrProductsPrice,
									prwfr_products_name: prwfrProductsName,
									prwfr_products_desc: prwfrProductsDesc,
									prwfr_products_desc_long: prwfrProductsDescLong,
									prwfr_products_categories: prwfrProductsCategories,
									prwfr_ai_recommendations_everyweek: prwfrManualWeeklyDay,
									prwfr_ai_recommendations_weekly_time: prwfrManualWeeklyTime,
									prwfr_ai_admin_email: prwfrManualWeeklyEmail,
									prwfr_about_store: prwfrAboutStore,
									prwfr_ai_request_prompt: prwfrPrompt,
									prwfr_ai_prompt_type: prwfrAiPromptType,
									// prwfr_activate_ai_recommendations: prwfrActivateAiRecommendations == 1 ? 1 : 0,
								},
								success: function(response) {
									// jQuery( '.prwfr-ai-save-loader' ).empty();
								},
							});
						}

						// Save Settings. 
						function prwfrGetSelectedOptions() {

							let sendPrompt = {
								sendPrompt: 1,
								invalidMessage: ""
							};
							// Convert the Set to an array
							let productIdsArray = Array.from(productIds);

							// // Convert the Set to an array
							let catIdsArray = Array.from(catIds);

							if (productIdsArray.length == 0) {
								productIdsArray = jQuery('#prwfr_product_selection').val();
							}

							if (catIdsArray.length == 0) {
								catIdsArray = jQuery('#prwfr_category_selection').val();
							}

							let prwfrRecurrencePeriod = jQuery('input[name=prwfr_recurrence_period_ai]:checked').val();
							let prwfrSaveWeeklyRecommendations = jQuery('input[name=prwfr_weekly_save_recommendations]:checked').val();
							let prwfrAllProducts = jQuery('input[name=prwfr_all_products]:checked').val();
							let prwfrMultipleProducts = jQuery('input[name=prwfr_multiple_products_check]:checked').val();
							let prwfrMultipleCategories = jQuery('input[name=prwfr_multiple_categories_check]:checked').val();
							let prwfrFbtData = jQuery('input[name=prwfr_fbt_data]:checked').val();
							let prwfrProductsUrl = jQuery('input[name=prwfr_products_url]:checked').val();
							let prwfrProductsPrice = jQuery('input[name=prwfr_products_price]:checked').val();
							let prwfrProductsName = jQuery('input[name=prwfr_products_name]:checked').val();
							let prwfrProductsDesc = jQuery('input[name=prwfr_products_desc]:checked').val();
							let prwfrProductsDescLong = jQuery('input[name=prwfr_products_desc_long]:checked').val();
							let prwfrProductsCategories = jQuery('input[name=prwfr_products_categories]:checked').val();
							let prwfrManualWeeklyDay = jQuery('select[name=prwfr_ai_recommendations_everyweek]').val();
							let prwfrManualWeeklyTime = jQuery('input[name=prwfr_ai_recommendations_weekly_time]').val();
							let prwfrManualWeeklyEmail = jQuery('input[name=prwfr_ai_admin_email]').val();
							let prwfrAboutStore = jQuery('textarea#prwfr_about_store').val();
							let prwfrPrompt = 'Here is selected products data set: {selected_products} and here is all products data set {all_products} and here is frequently purchased products data {fbt_products}  and suggest {recommendation_count} recommendations for each product from this selected products data set from the all products data set.';
							let prwfrAiPromptType = 'default';
							// let prwfrActivateAiRecommendations = jQuery( 'input[name=prwfr_activate_ai_recommendations]:checked').val();

							jQuery.ajax({
								url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>', // Use a localized variable for the AJAX URL
								type: 'POST',
								data: {
									action: 'prwfr_ai_help',
									prwfr_ajax_nonce: prwfrNonce,
									save_settings: 1,
									prwfr_category_selection: catIdsArray,
									prwfr_product_selection: productIdsArray,
									prwfr_recurrence_period_ai: prwfrRecurrencePeriod,
									prwfr_save_weekly_recommendations: prwfrSaveWeeklyRecommendations,
									prwfr_all_products: prwfrAllProducts,
									prwfr_multiple_products_check: prwfrMultipleProducts,
									prwfr_multiple_categories_check: prwfrMultipleCategories,
									prwfr_fbt_data: prwfrFbtData,
									prwfr_products_url: prwfrProductsUrl,
									prwfr_products_price: prwfrProductsPrice,
									prwfr_products_name: prwfrProductsName,
									prwfr_products_desc: prwfrProductsDesc,
									prwfr_products_desc_long: prwfrProductsDescLong,
									prwfr_products_categories: prwfrProductsCategories,
									prwfr_ai_recommendations_everyweek: prwfrManualWeeklyDay,
									prwfr_ai_recommendations_weekly_time: prwfrManualWeeklyTime,
									prwfr_ai_admin_email: prwfrManualWeeklyEmail,
									prwfr_about_store: prwfrAboutStore,
									prwfr_ai_request_prompt: prwfrPrompt,
									prwfr_ai_prompt_type: prwfrAiPromptType,
									// prwfr_activate_ai_recommendations: prwfrActivateAiRecommendations == 1 ? 1 : 0,
								},
								success: function(response) {
									// jQuery( '.prwfr-ai-save-loader' ).empty();
								},
							});

							if ((prwfrProductsUrl == undefined && prwfrProductsPrice == undefined && prwfrProductsName == undefined && prwfrProductsDesc == undefined &&
									prwfrProductsDescLong == undefined && prwfrProductsCategories == undefined)) {
								return {
									sendPrompt: 0,
									invalidMessage: "Cannot send request, please select Product Details."
								};
							}

							// if( !prwfrPrompt ){
							// 	return { sendPrompt: 0, invalidMessage: "Cannot send request, AI Prompt is empty." };
							// }
							if ((prwfrMultipleProducts == 'on') && (productIdsArray.length == 0)) {
								return {
									sendPrompt: 0,
									invalidMessage: "Cannot send request, Invalid Product Selection."
								};
							}

							if ((!prwfrAboutStore)) {
								return {
									sendPrompt: 0,
									invalidMessage: "About Store is required. Please add your store description."
								};
							}


							// if(( prwfrMultipleCategories == 'on') && (catIdsArray.length == 0) ){
							// 	return { sendPrompt: 0, invalidMessage: "Cannot send request, Invalid Product Cat.." };
							// }

							if (productIdsArray == 0) {
								return {
									sendPrompt: 0,
									invalidMessage: "Cannot send request, Product Selection set individual products but no product IDs are selecetd."
								};
							}

							totaltoken = <?php echo intval($model_max_token_limit); ?>;

							if (tokensUsed > totaltoken) {
								return {
									sendPrompt: 0,
									invalidMessage: "Cannot process request; token usage exceeds the allowed limit.The maximum allowed is  " + "= <?php echo intval($model_max_token_limit); ?>" + " tokens. Reduce the number of selected products or the amount of data and try again."
								};
							}

							return {
								sendPrompt: 1,
								invalidMessage: ""
							};
						}

						// Update Token values.
						function prwfrUpdateAiToken() {
							jQuery('.prwfr-token-status').empty();
							// let createRequest = prwfrGetSelectedOptions();

							prwfr_SaveAiInfo().then(function() {
								return jQuery.ajax({
									type: "POST",
									url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
									data: {
										action: 'prwfr_ai_help',
										prompt_token: 1,
										prwfr_ajax_nonce: prwfrNonce,
									},
									beforeSend: function() {
										jQuery('#prwfr-send-prompt-btn').attr('disabled', 'disabled').css("opacity", "0.1");
									}
								})
							}).then(function(response) {
								tokensUsed = response;

								/* translators: %d: maximum token limit */
								jQuery('.prwfr-token-status').text(response + ' <?php /* translators: %d: maximum token limit */ echo esc_js(sprintf(__('tokens will be used out of %d', 'sft-product-recommendations-for-woocommerce'), (int) $model_max_token_limit)); ?>');



								jQuery('#prwfr-send-prompt-btn').removeAttr("disabled").css("opacity", "1");

								let totaltoken = <?php echo intval($model_max_token_limit); ?>;

								let usageRatio = tokensUsed / totaltoken;
								let color = "green";

								if (usageRatio > 1) {
									color = "red";
								} else if (usageRatio > 0.75) {
									color = "orange";
								}

								jQuery('.prwfr-token-status').css("color", color);
							});

						}

						jQuery('.swal2-container.swal2-center').css('z-index', '100000');
						jQuery('.prwfr-popup').css('width', '840px');
						jQuery('.prwfr-popup').css('text-align', 'left');
						jQuery('.prwfr-popup > .swal2-header').css('background', '#061727');
						jQuery('.prwfr-popup > .swal2-header').css('margin', '-20px');
						//jQuery('.prwfr-popup > .swal2-content').css('padding', '0px 0px 0px 10px');
						jQuery('.pro-alert-header').css('padding-top', '25px');
						jQuery('.pro-alert-header').css('padding-bottom', '20px');
						jQuery('.pro-alert-header').css('color', 'white');
					} else {
						Swal.fire('', 'Your Last request is Processing..!', 'warning');
					}
				} else {

					// For expired tokens status.
					Swal.fire({
						text: '<?php echo esc_html__('Your API token credit limit has expired !', 'sft-product-recommendations-for-woocommerce'); ?>',
						icon: "warning",
						showDenyButton: true,
						showCloseButton: true,
						confirmButtonText: '<?php echo esc_html__('Renew Credits', 'sft-product-recommendations-for-woocommerce'); ?>',
						denyButtonText: '<?php echo esc_html__('Configure API Key', 'sft-product-recommendations-for-woocommerce'); ?>',
						denyButtonColor: "#32CD32",
						confirmButtonColor: "#6CB4EE",
					}).then((result) => {

						if (result.isConfirmed) {

							// Move to billing page.
							window.location.assign('https://platform.openai.com/settings/organization/billing/');
						} else if (result.isDenied) {

							// Move to settings page.
							window.location.assign('<?php echo esc_url($api_settings_page); ?>');
						}
					});
				}
			}


		});
	</script>
<?php

}


// Action Hook to add tabs in the Ai Prompt.
add_action('prwfr_ai_prompt_content_tab_1', 'prwfr_ai_prompt_tab1', 10, 9);
add_action('prwfr_ai_prompt_content_tab_2', 'prwfr_ai_prompt_tab2', 10, 9);
add_action('prwfr_ai_prompt_content_tab_3', 'prwfr_ai_prompt_tab3', 10, 9);

/**
 * Display the first tab for AI Prompt.
 *
 * @param array  $all_products         All available products.
 * @param array  $product_categories   All product categories.
 * @param array  $selected_products    Products selected by the user.
 * @param array  $selected_categories  Categories selected by the user.
 * @param int    $time_interval        Time interval for the prompt.
 * @param int    $days_of_week         Selected days of the week.
 * @param string $value                Additional values for the prompt.
 * @param string $display_prompt       Prompt text to display.
 * @param int    $tokens_used          Number of tokens used.
 * @return void
 */
function prwfr_ai_prompt_tab1($all_products, $product_categories, $selected_products, $selected_categories, $time_interval, $days_of_week, $value, $display_prompt, $tokens_used)
{

	$token_message = prwfr_get_token('message');
?>
	<div class="prwfr-ai-popup ">
		<div class="prwfr-product-selection-section">
			<div class="prwfr-ai-section-heading">
				<?php echo esc_html__('Select Products / Product Categories for generating AI Recommendations :', 'sft-product-recommendations-for-woocommerce'); ?>
				<div class="prwfr-popup-btn-tooltip-container">
					<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
					<div class="prwfr-ai-popup-btn-tooltip"><?php echo esc_html__('Select specific products or categories for the AI to generate product recommendations.', 'sft-product-recommendations-for-woocommerce'); ?></div>
				</div>
			</div>

			<div class="prwfr-ai-sub-section-row prwfr-ai-prdt-selection">
				<div><?php echo esc_html__('Product Selection', 'sft-product-recommendations-for-woocommerce'); ?></div>

				<div class="prwfr-ai-checkbox-container">
					<div class="prwfr-ai-prod-select">
						<div class="prwfr-ai-prod-select-input">
							<input type="checkbox" id="prwfr_multiple_categories_check" name="prwfr_multiple_categories_check" value="on" <?php echo checked('on', get_option('prwfr_multiple_categories_check'), false); ?> disabled />

							<label class="prwfr-ai-checkbox-label" for="prwfr_multiple_categories_check"><?php echo esc_html__('Product Categories', 'sft-product-recommendations-for-woocommerce'); ?></label>
						</div>

						<div class="prwfr-pro-lock-tooltip-container">
							<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/pro-crown-logo.svg'); ?>" width="15px" height="15px" title="Available in Pro Version" class="prwfr-pro-version-lock" alt="lock icon">
							<div class="prwfr-pro-lock-btn-tooltip">
								<?php echo esc_html__('Complete Feature Available in ', 'sft-product-recommendations-for-woocommerce'); ?>
								<a href="https://www.saffiretech.com/woocommerce-product-recommendations-pro/" target="_blank">
									<?php echo esc_html__('Pro Version', 'sft-product-recommendations-for-woocommerce'); ?>
								</a>
							</div>
						</div>

					</div>

					<div>
						<input style="pointer-events:none;" type="checkbox" id="prwfr_multiple_products_check" name="prwfr_multiple_products_check" value="on" <?php echo checked('on', get_option('prwfr_multiple_products_check'), false); ?> />
						<label class="prwfr-ai-checkbox-label" for="prwfr_multiple_products_check"><?php echo esc_html__('Individual Products', 'sft-product-recommendations-for-woocommerce'); ?></label>
					</div>
				</div>

			</div>

			<div class="prwfr-ai-sub-section-row prwfr-align-start prwfr-all-cat-selection">

				<div><?php echo esc_html__('Choose Categories', 'sft-product-recommendations-for-woocommerce'); ?><span class="prwfr-required">*</span></div>

				<span>
					<select class="prwfr_category_selection" name="prwfr_category_selection[]" id="prwfr_category_selection" multiple>

						<?php
						foreach ($product_categories as $product_category) {

							if (! empty($selected_categories) && in_array($product_category->term_id, $selected_categories)) {
						?>
								<option selected="selected" value='<?php echo esc_attr($product_category->term_id); ?>'><?php echo esc_html($product_category->name); ?></option>
							<?php
							} else {
							?>
								<option value='<?php echo esc_attr($product_category->term_id); ?>'><?php echo esc_html($product_category->name); ?></option>
						<?php
							}
						}
						?>

					</select>
				</span>

			</div>

			<div class="prwfr-ai-sub-section-row prwfr-align-start prwfr-products-selection prwfr-ai-choose-individual-prdt">

				<div><?php echo esc_html__('Choose Individual Products', 'sft-product-recommendations-for-woocommerce'); ?><span class="prwfr-required">*</span></div>
				<div>
					<div class="prwfr-ai-settings-placeholder"><?php echo esc_html__('You can select only', 'sft-product-recommendations-for-woocommerce'); ?> <b><?php echo esc_html__('5 Products', 'sft-product-recommendations-for-woocommerce'); ?></b></div>

					<span class="prwfr-all-products-list">
						<select class="prwfr_product_selection" name="prwfr_product_selection[]" id="prwfr_product_selection" multiple>
							<?php
							foreach ($all_products as $product) {

								if (! empty($selected_products) && in_array($product['product_id'], $selected_products)) {
							?>
									<option selected="selected" value='<?php echo esc_attr($product['product_id']); ?>'><?php echo esc_html($product['label']); ?></option>
								<?php
								} else {
								?>
									<option value='<?php echo esc_attr($product['product_id']); ?>'><?php echo esc_html($product['label']); ?></option>
							<?php
								}
							}
							?>
						</select>
					</span>
				</div>
			</div>

			<div class="prwfr-ai-sub-section-row">
				<div>
					<?php echo esc_html__('Product Details to include in Ai Prompt', 'sft-product-recommendations-for-woocommerce'); ?><span class="prwfr-required">*</span>
					<div class="prwfr-pro-lock-tooltip-container">
						<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/pro-crown-logo.svg'); ?>" width="15px" height="15px" title="Available in Pro Version" class="prwfr-pro-version-lock alt">
						<div class="prwfr-pro-lock-btn-tooltip">
							<?php echo esc_html__('Complete Feature Available in ', 'sft-product-recommendations-for-woocommerce'); ?>
							<a href="https://www.saffiretech.com/woocommerce-product-recommendations-pro/" target="_blank">
								<?php echo esc_html__('Pro Version', 'sft-product-recommendations-for-woocommerce'); ?>
							</a>
						</div>
					</div>
				</div>

				<div class="prwfr-ai-checkbox-container" style="flex-direction: column; gap: 10px;">
					<div>
						<input type="checkbox" id="prwfr_products_url" name="prwfr_products_url" value="on" <?php echo checked('on', get_option('prwfr_products_url'), false); ?> disabled />
						<label for="prwfr_products_url"><?php echo esc_html__('Product URL', 'sft-product-recommendations-for-woocommerce'); ?></label>
					</div>
					<div>
						<input type="checkbox" id="prwfr_products_price" name="prwfr_products_price" value="on" <?php echo checked('on', get_option('prwfr_products_price'), false); ?> disabled />
						<label for="prwfr_products_price"><?php echo esc_html__('Product Price', 'sft-product-recommendations-for-woocommerce'); ?></label>
					</div>
					<div>
						<input type="checkbox" style="pointer-events:none;" id="prwfr_products_name" name="prwfr_products_name" value="on" <?php echo checked('on', get_option('prwfr_products_name'), false); ?> />
						<label for="prwfr_products_name"><?php echo esc_html__('Product Name', 'sft-product-recommendations-for-woocommerce'); ?></label>
					</div>
					<div>
						<input type="checkbox" id="prwfr_products_categories" name="prwfr_products_categories" value="on" <?php echo checked('on', get_option('prwfr_products_categories'), false); ?> disabled />
						<label for="prwfr_products_categories"><?php echo esc_html__('Product Category', 'sft-product-recommendations-for-woocommerce'); ?></label>
					</div>
					<div>
						<input type="checkbox" id="prwfr_products_desc" name="prwfr_products_desc" value="on" <?php echo checked('on', get_option('prwfr_products_desc'), false); ?> />
						<label for="prwfr_products_desc"><?php echo esc_html__('Product Description( Short Description )', 'sft-product-recommendations-for-woocommerce'); ?></label>
					</div>
					<div>
						<input type="checkbox" id="prwfr_products_desc_long" name="prwfr_products_desc_long" value="on" <?php echo checked('on', get_option('prwfr_products_desc_long'), false); ?> disabled />
						<label for="prwfr_products_desc_long"><?php echo esc_html__('Product Description( Long Description )', 'sft-product-recommendations-for-woocommerce'); ?></label>
					</div>
				</div>
			</div>
		</div>

		<div class="prwfr-store-desc-section">
			<div class="prwfr-ai-section-heading">
				<?php echo esc_html__('Recommendation Configuration & Store Details', 'sft-product-recommendations-for-woocommerce'); ?><span class="prwfr-required">*</span>

				<div class="prwfr-popup-btn-tooltip-container">
					<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
					<div class="prwfr-ai-popup-btn-tooltip prwfr-tooltip-top-right"><?php echo esc_html__('Provide a short description of your store so AI can offer more accurate product recommendations. The AI may consider your input, but it might not follow all instructions exactly.', 'sft-product-recommendations-for-woocommerce'); ?></div>
				</div>

			</div>

			<div class="prwfr-ai-sub-section-row prwfr-ai-checkbox-container">
				<div>
					<?php echo esc_html__('Set Number of Product Suggestions per Product', 'sft-product-recommendations-for-woocommerce'); ?>
					<span class="prwfr-required">* </span>
					<div class="prwfr-popup-btn-tooltip-container">
						<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
						<div class="prwfr-ai-popup-btn-tooltip prwfr-tooltip-top-right"><?php echo esc_html__('Choose the number of suggestions you want to have for each Product.', 'sft-product-recommendations-for-woocommerce'); ?></div>
					</div>
					<div class="prwfr-pro-lock-tooltip-container">
						<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/pro-crown-logo.svg'); ?>" width="15px" height="15px" title="Available in Pro Version" class="prwfr-pro-version-lock alt">
						<div class="prwfr-pro-lock-btn-tooltip">
							<?php echo esc_html__('Complete Feature Available in ', 'sft-product-recommendations-for-woocommerce'); ?>
							<a href="https://www.saffiretech.com/woocommerce-product-recommendations-pro/" target="_blank">
								<?php echo esc_html__('Pro Version', 'sft-product-recommendations-for-woocommerce'); ?>
							</a>
						</div>
					</div>
				</div>
				<div class="prwfr-ai-checkbox-container">
					<div>
						<?php
						$recommendation_limit = 5;
						?>
						<input disabled type="number" id="prprow_ai_recommendations_limit" name="prprow_ai_recommendations_limit" min="1" max="10" value="<?php echo (int) $recommendation_limit; ?>">
					</div>
					<p id="prwfr-limit-message" style="color: red; display: none;"><?php echo esc_html__('Please enter a number between 1 and 10.', 'sft-product-recommendations-for-woocommerce'); ?></p>
				</div>
			</div>

			<div class="prwfr-ai-sub-section prwfr-ai-save-recommendation-sourse ">

				<div style="font-weight: 500;">
					<?php echo esc_html__('Set Recommendations For', 'sft-product-recommendations-for-woocommerce'); ?>
					<span class="prwfr-required">*</span>
					<div class="prwfr-popup-btn-tooltip-container">
						<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
						<div class="prwfr-ai-popup-btn-tooltip">
							<?php echo esc_html__("Choose recommendation configuration: recently viewed products, past purchases, or both. 'Recently viewed' shows recommendations after browsing, 'Past purchases' after buying, and 'Both' saves recommendations for both scenarios.", 'sft-product-recommendations-for-woocommerce'); ?>
						</div>
					</div>
				</div>
				<div class="prwfr-ai-set-recommendations">
					<div class="prwfr-ai-checkbox-container">
						<div>
							<input type="radio" id="prwfr-save-both" name="prprow_source" value="prwfr-save-both" checked>
							<label for="prwfr-save-both">Both</label>
						</div>

						<div>
							<div>
								<input disabled type="radio" id="prwfr-save-rvp" name="prprow_source" value="prwfr-save-rvp" <?php echo checked('prwfr-save-rvp', get_option('prprow_source'), false); ?>>
								<label for="prwfr-save-rvp">Only Recently Viewed Products</label>
							</div>

							<div class="prwfr-pro-lock-tooltip-container">
								<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/pro-crown-logo.svg'); ?>" width="15px" height="15px" title="Available in Pro Version" class="prwfr-pro-version-lock alt">
								<div class="prwfr-pro-lock-btn-tooltip">
									<?php echo esc_html__('Complete Feature Available in ', 'sft-product-recommendations-for-woocommerce'); ?>
									<a href="https://www.saffiretech.com/woocommerce-product-recommendations-pro/" target="_blank">
										<?php echo esc_html__('Pro Version', 'sft-product-recommendations-for-woocommerce'); ?>
									</a>
								</div>
							</div>
						</div>

						<div>
							<div>
								<input disabled type="radio" id="prwfr-save-pp" name="prprow_source" value="prwfr-save-pp" <?php echo checked('prwfr-save-pp', get_option('prprow_source'), false); ?>>
								<label for="prprow-save-pp">Only Post-Purchase Product</label>
							</div>
							<div class="prwfr-pro-lock-tooltip-container">
								<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/pro-crown-logo.svg'); ?>" width="15px" height="15px" title="Available in Pro Version" class="prwfr-pro-version-lock alt">
								<div class="prwfr-pro-lock-btn-tooltip">
									<?php echo esc_html__('Complete Feature Available in ', 'sft-product-recommendations-for-woocommerce'); ?>
									<a href="https://www.saffiretech.com/woocommerce-product-recommendations-pro/" target="_blank">
										<?php echo esc_html__('Pro Version', 'sft-product-recommendations-for-woocommerce'); ?>
									</a>
								</div>
							</div>
						</div>
					</div>

					<span class="prwfr-ai-settings-placeholder" id="prwfr-save-products-placeholder" style="display:none;">

						<?php echo esc_html__('Use placeholder {all_product} to use all products in prompt.', 'sft-product-recommendations-for-woocommerce'); ?>
						<button class="prwfr-selected-recomm-sourse-clipboard clipboard">&#128203;</button>
						<span class="prwfr-selected-recomm-sourse-text-copied">

				</div>
			</div>

			<div class="prwfr-ai-sub-section prwfr-ai-checkbox-container" style="flex-direction: column;">
				<div class="prwfr-about-store">
					<?php echo esc_html__('About Store', 'sft-product-recommendations-for-woocommerce'); ?>
					<span class="prwfr-required">* </span>
					<div class="prwfr-popup-btn-tooltip-container">
						<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
						<div class="prwfr-ai-popup-btn-tooltip prwfr-tooltip-bottom-left"><?php echo esc_html__('Provide a description of your store to help the AI generate more tailored product recommendations based on your business needs', 'sft-product-recommendations-for-woocommerce'); ?></div>
					</div>
				</div>
				<textarea id="prwfr_about_store" name="prwfr_about_store" rows="3" placeholder="E.g. I have WooCommerce store that offers clothing and accessories for men and women, featuring a wide range of apparel and fashion items. The store is organized by categories, making it easy for customers to navigate and find what they need."><?php echo esc_html(get_option('prwfr_about_store')); ?></textarea>
			</div>
		</div>

		<div class="prwfr-ai-reset-save-container ">
			<button id="prwfr_save_ai_settings"><?php echo esc_html__('Save Settings', 'sft-product-recommendations-for-woocommerce'); ?> <span class="prwfr-ai-save-loader"></span></button>
			<button id="prwfr_reset_ai_settings"><?php echo esc_html__('Reset to Default', 'sft-product-recommendations-for-woocommerce'); ?></button>
			<button id="prwfr_undo_ai_changes"><?php echo esc_html__('Undo Changes', 'sft-product-recommendations-for-woocommerce'); ?></button>
			<span style="margin-left: auto; color: green;" class="prwfr-token-status"></span>
			<div class="prwfr-popup-btn-tooltip-container">
				<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
				<div class="prwfr-ai-popup-btn-tooltip">
					<?php
					echo wp_kses_post(
						sprintf(
							/* translators: %1$s: token message, %2$s: link to Switch Model page, %3$s: link to OpenAI Documentation */
							__('%1$s This token limit comes from ChatGPT, not our product. For longer inputs, you can switch to a higher-limit model or check the documentation. <a href="%2$s">Switch Model</a> | <a href="%3$s" target="_blank">OpenAI Documentation</a>', 'sft-product-recommendations-for-woocommerce'),
							$token_message,
							esc_url(admin_url('admin.php?page=prwfr_api_setting_page')),
							esc_url('https://platform.openai.com/docs/models')
						)
					);

					?>
				</div>
			</div>
		</div>

	</div>
<?php
}

/**
 * Display the second tab for AI Prompt.
 *
 * @param array  $all_products         All available products.
 * @param array  $product_categories   All product categories.
 * @param array  $selected_products    Products selected by the user.
 * @param array  $selected_categories  Categories selected by the user.
 * @param int    $time_interval        Time interval for the prompt.
 * @param array  $days_of_week         Selected days of the week.
 * @param string $value                Additional values for the prompt.
 * @param string $display_prompt       Prompt text to display.
 * @param int    $tokens_used          Number of tokens used.
 * @return void
 */
function prwfr_ai_prompt_tab2($all_products, $product_categories, $selected_products, $selected_categories, $time_interval, $days_of_week, $value, $display_prompt, $tokens_used)
{
	$token_message = prwfr_get_token('message');
?>

	<div class="prwfr-ai-popup">
		<div class=" prwfr-ai-general-section">
			<div class="prwfr-ai-section-heading">
				<?php echo esc_html__('Recommendations Schedule and Saving:', 'sft-product-recommendations-for-woocommerce'); ?>
				<div class="prwfr-popup-btn-tooltip-container">
					<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
					<div class="prwfr-ai-popup-btn-tooltip prwfr-tooltip-bottom-left"><?php echo esc_html__('Choose how frequently you want to receive AI product recommendations, whether as a one-time update or on a weekly basis. You can also set a specific date and time for generating and applying the suggestions.', 'sft-product-recommendations-for-woocommerce'); ?></div>
				</div>
			</div>
			<div class="prwfr-ai-sub-section">

			</div>
			<div class="prwfr-ai-sub-section">
				<div><?php echo esc_html__('How often should recommendations be generated?', 'sft-product-recommendations-for-woocommerce'); ?><span class="prwfr-required">* </span></div>
				<div class="prwfr-ai-radio-btn-container">
					<div>
						<input type="radio" id="one_time" name="prwfr_recurrence_period_ai" value="one_time" <?php echo checked('one_time', get_option('prwfr_recurrence_period_ai'), false); ?>>
						<label for="one_time"><?php echo esc_html__('One-Time', 'sft-product-recommendations-for-woocommerce'); ?></label>
					</div>
					<div>
						<input type="radio" id="weekly" name="prwfr_recurrence_period_ai" value="weekly" <?php echo checked('weekly', get_option('prwfr_recurrence_period_ai'), false); ?> disabled />
						<label for="weekly"><?php echo esc_html__('Weekly', 'sft-product-recommendations-for-woocommerce'); ?></label>
						<div class="prwfr-pro-lock-tooltip-container">
							<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/pro-crown-logo.svg'); ?>" width="15px" height="15px" title="Available in Pro Version" class="prwfr-pro-version-lock alt">
							<div class="prwfr-pro-lock-btn-tooltip">
								<?php echo esc_html__('Complete Feature Available in ', 'sft-product-recommendations-for-woocommerce'); ?>
								<a href="https://www.saffiretech.com/woocommerce-product-recommendations-pro/" target="_blank">
									<?php echo esc_html__('Pro Version', 'sft-product-recommendations-for-woocommerce'); ?>
								</a>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="prwfr-ai-recommendations-weekly prwfr-ai-sub-section">
				<div>
					<?php echo esc_html__('On which day and at what time should recommendations be generated?', 'sft-product-recommendations-for-woocommerce'); ?>
					<div class="prwfr-pro-lock-tooltip-container">
						<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/pro-crown-logo.svg'); ?>" width="15px" height="15px" title="Available in Pro Version" class="prwfr-pro-version-lock alt">
						<div class="prwfr-pro-lock-btn-tooltip">
							<?php echo esc_html__('Complete Feature Available in ', 'sft-product-recommendations-for-woocommerce'); ?>
							<a href="https://www.saffiretech.com/woocommerce-product-recommendations-pro/" target="_blank">
								<?php echo esc_html__('Pro Version', 'sft-product-recommendations-for-woocommerce'); ?>
							</a>
						</div>
					</div>
				</div>
				<div class="prwfr-ai-day-time-container">
					<div>
						<select disabled id="day-of-week" name="prwfr_ai_recommendations_everyweek">
							<?php
							foreach ($days_of_week as $day) {
								if (ucfirst($value) == $day) {
							?>
									<option selected="selected" value='<?php echo esc_html(ucfirst($value)); ?>'><?php echo esc_html($day); ?></option>
								<?php
								} else {
								?>
									<option value='<?php echo esc_html($day); ?>'><?php echo esc_html($day); ?></option>
							<?php
								}
							}
							?>
						</select>
					</div>

					<div>
						<input disabled type="time" name="prwfr_ai_recommendations_weekly_time" value="12:00" id="time-of-day">
					</div>
				</div>
			</div>

			<div class="prwfr-save-recommendations-weekly prwfr-ai-sub-section">
				<div><?php echo esc_html__('Do you want to directly save and display generated AI recommendations on your website ?', 'sft-product-recommendations-for-woocommerce'); ?></div>
				<div class="prwfr-ai-radio-btn-container" style="flex-direction: column; align-items: flex-start;">
					<div>
						<input type="radio" id="prwfr_weekly_automatic" name="prwfr_weekly_save_recommendations" value="automatic" checked="checked">
						<label for="prwfr_weekly_automatic"><?php echo esc_html__(' Yes, save and apply product recommendations directly on the website.', 'sft-product-recommendations-for-woocommerce'); ?></label>
					</div>
					<div>
						<input type="radio" id="prwfr_weekly_manual" name="prwfr_weekly_save_recommendations" value="manual" disabled />
						<label for="prwfr_weekly_manual"><?php echo esc_html__('No, I want to review the product recommendations manually before saving them.', 'sft-product-recommendations-for-woocommerce'); ?></label>
						<div class="prwfr-pro-lock-tooltip-container">
							<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/pro-crown-logo.svg'); ?>" width="15px" height="15px" title="Available in Pro Version" class="prwfr-pro-version-lock alt">
							<div class="prwfr-pro-lock-btn-tooltip">
								<?php echo esc_html__('Complete Feature Available in ', 'sft-product-recommendations-for-woocommerce'); ?>
								<a href="https://www.saffiretech.com/woocommerce-product-recommendations-pro/" target="_blank">
									<?php echo esc_html__('Pro Version', 'sft-product-recommendations-for-woocommerce'); ?>
								</a>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="prwfr-ai-recommendations-admin-email prwfr-ai-sub-section">
				<div>
					<label for="prwfr_ai_admin_email"><?php echo esc_html__('Add email address where you wish to be notified when recommendations are ready:', 'sft-product-recommendations-for-woocommerce'); ?></label>
					<div class="prwfr-pro-lock-tooltip-container">
						<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/pro-crown-logo.svg'); ?>" width="15px" height="15px" title="Available in Pro Version" class="prwfr-pro-version-lock alt">
						<div class="prwfr-popup-btn-tooltip-container">
							<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
							<div class="prwfr-ai-popup-btn-tooltip prwfr-tooltip-bottom-left"><?php echo esc_html__('Choose how frequently you want to receive AI product recommendations, whether as a one-time update or on a weekly basis. You can also set a specific date and time for generating and applying the suggestions.', 'sft-product-recommendations-for-woocommerce'); ?></div>
						</div>

						<div class="prwfr-pro-lock-btn-tooltip" style="width: 130px;">
							<?php echo esc_html__('Available in ', 'sft-product-recommendations-for-woocommerce'); ?>
							<a href="https://www.saffiretech.com/woocommerce-product-recommendations-pro/" target="_blank">
								<?php echo esc_html__('Pro Version', 'sft-product-recommendations-for-woocommerce'); ?>
							</a>
						</div>
					</div>
				</div>
				<input type="text" disabled id="prwfr_ai_admin_email" name="prwfr_ai_admin_email" style="max-width:312px; width:100%;" value="<?php echo esc_url(get_option('admin_email')); ?>" />
				<span style="font-size: 11px;">(For multiple email addresses, please use comma as a separator)</span>

			</div>

		</div>

		<div class="prwfr-ai-reset-save-container ">
			<button id="prwfr_save_ai_settings"><?php echo esc_html__('Save Settings', 'sft-product-recommendations-for-woocommerce'); ?> <span class="prwfr-ai-save-loader"></span></button>
			<button id="prwfr_reset_ai_settings"><?php echo esc_html__('Reset to Default', 'sft-product-recommendations-for-woocommerce'); ?></button>
			<button id="prwfr_undo_ai_changes"><?php echo esc_html__('Undo Changes', 'sft-product-recommendations-for-woocommerce'); ?></button>
			<span style="margin-left: auto; color: green;" class="prwfr-token-status"></span>
			<div class="prwfr-popup-btn-tooltip-container">
				<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
				<div class="prwfr-ai-popup-btn-tooltip">
					<?php
					echo wp_kses_post(
						sprintf(
							/* translators: %1$s: token message, %2$s: link to Switch Model page, %3$s: link to OpenAI Documentation */
							__('%1$s This token limit comes from ChatGPT, not our product. For longer inputs, you can switch to a higher-limit model or check the documentation. <a href="%2$s">Switch Model</a> | <a href="%3$s" target="_blank">OpenAI Documentation</a>', 'sft-product-recommendations-for-woocommerce'),
							$token_message,
							esc_url(admin_url('admin.php?page=prwfr_api_setting_page')),
							esc_url('https://platform.openai.com/docs/models')
						)
					);
					?>
				</div>
			</div>
		</div>
	</div>
<?php
}

/**
 * Display the third tab for AI Prompt.
 *
 * @param array  $all_products         All available products.
 * @param array  $product_categories   All product categories.
 * @param array  $selected_products    Products selected by the user.
 * @param array  $selected_categories  Categories selected by the user.
 * @param int    $time_interval        Time interval for the prompt.
 * @param int    $days_of_week         Selected days of the week.
 * @param string $value                Additional values for the prompt.
 * @param string $display_prompt       Prompt text to display.
 * @param int    $tokens_used          Number of tokens used.
 * @return void
 */
function prwfr_ai_prompt_tab3($all_products, $product_categories, $selected_products, $selected_categories, $time_interval, $days_of_week, $value, $display_prompt, $tokens_used)
{
	$token_message = prwfr_get_token('message');
?>
	<div class="prwfr-ai-popup">
		<div class=" prwfr-additional-data-section">
			<div class="prwfr-ai-section-heading">
				<?php echo esc_html__('Additional Information to add in Prompt', 'sft-product-recommendations-for-woocommerce'); ?>
				<div class="prwfr-popup-btn-tooltip-container">
					<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
					<div class="prwfr-ai-popup-btn-tooltip"><?php echo esc_html__('This setting lets you provide additional details to guide the AIs response.', 'sft-product-recommendations-for-woocommerce'); ?></div>
				</div>
				<div class="prwfr-pro-lock-tooltip-container">
					<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/pro-crown-logo.svg'); ?>" width="15px" height="15px" title="Available in Pro Version" class="prwfr-pro-version-lock alt">
					<div class="prwfr-pro-lock-btn-tooltip">
						<?php echo esc_html__('Complete Feature Available in ', 'sft-product-recommendations-for-woocommerce'); ?>
						<a href="https://www.saffiretech.com/woocommerce-product-recommendations-pro/" target="_blank">
							<?php echo esc_html__('Pro Version', 'sft-product-recommendations-for-woocommerce'); ?>
						</a>
					</div>
				</div>
			</div>

			<div class="prwfr-ai-sub-section prwfr-ai-checkbox-container">
				<div>
					<input type="checkbox" id="prwfr_fbt_data" name="prwfr_fbt_data" value="on" disabled />
					<?php echo esc_html__('Include Past Sales Data (Optional)', 'sft-product-recommendations-for-woocommerce'); ?>
					<div class="prwfr-popup-btn-tooltip-container">
						<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
						<div class="prwfr-ai-popup-btn-tooltip"><?php echo esc_html__('Include your store\'s  sales data in AI-generated suggestions to enhance the relevance of recommendations by suggesting products that are often purchased together.', 'sft-product-recommendations-for-woocommerce'); ?></div>
					</div>
				</div>
				<div class="prwfr-ai-settings-placeholder">
					<b>
						<?php echo esc_html__('Disclaimer: By selecting this option, you consent to sharing your store\'s sales data with OpenAI to enhance the accuracy of product recommendations. If you prefer not to share your sales data, please leave this option unchecked. Check our ', 'sft-product-recommendations-for-woocommerce'); ?><a href="https://saffiretech.com/terms-and-conditions/"><?php esc_html_e('Terms & Conditions', 'sft-product-recommendations-for-woocommerce'); ?></a><?php esc_html_e(' and ', 'sft-product-recommendations-for-woocommerce'); ?><a href="https://saffiretech.com/privacy-policy/"><?php esc_html_e('Privacy Policy', 'sft-product-recommendations-for-woocommerce'); ?></a><?php esc_html_e(' here for more details on how your data is handled.', 'sft-product-recommendations-for-woocommerce'); ?>
					</b>
				</div>
				<div class=" prwfr-ai-fbt-interval">
					<div style="font-weight:500;"><?php echo esc_html__('Sale Interval', 'sft-product-recommendations-for-woocommerce'); ?></div>
					<div>
						<div class="prwfr-ai-radio-btn-container-grid" style="margin-bottom: 8px;">
							<?php
							// Get the saved option from the database.
							$saved_option = get_option('prprow_ai_prompt_sale_days_limit') ? get_option('prprow_ai_prompt_sale_days_limit') : '';

							// Define time interval options.
							$time_intervals = array(
								'prwfr-interval-7-days'    => 'Last 7 Days',
								'prwfr-interval-30-days'   => 'Last 30 Days',
								'prwfr-interval-90-days'   => 'Last 90 Days',
								'prwfr-interval-6-months'  => 'Last 6 Months',
								'prwfr-interval-12-months' => 'Last 12 Months',
								'prwfr-interval-all-time'  => 'Custom Date Range',
							);
							?>
							<?php foreach ($time_intervals as $value => $label) { ?>
								<div>
									<input disabled type="radio" id="<?php echo esc_attr($value); ?>" name="prprow_sale_interval" value="<?php echo esc_attr($value); ?>" <?php echo checked($value, $saved_option, false); ?>>
									<label for="<?php echo esc_attr($value); ?>"><?php echo esc_html($label); ?></label>
								</div>
							<?php }; ?>
						</div>

					</div>
				</div>
			</div>

			<div class="prwfr-ai-sub-section">
				<div>
					<?php echo esc_html__('Extra Instruction', 'sft-product-recommendations-for-woocommerce'); ?>
					<div class="prwfr-popup-btn-tooltip-container">
						<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
						<div class="prwfr-ai-popup-btn-tooltip"><?php echo esc_html__('Use this field to provide extra context or specific instructions for the AI. Note: The AI may consider your input, but it may or may not follow all instructions.', 'sft-product-recommendations-for-woocommerce'); ?></div>
					</div>
					<div class="prwfr-pro-lock-tooltip-container">
						<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/pro-crown-logo.svg'); ?>" width="15px" height="15px" title="Available in Pro Version" class="prwfr-pro-version-lock alt">
						<div class="prwfr-pro-lock-btn-tooltip">
							<?php echo esc_html__('Complete Feature Available in ', 'sft-product-recommendations-for-woocommerce'); ?>
							<a href="https://www.saffiretech.com/woocommerce-product-recommendations-pro/" target="_blank">
								<?php echo esc_html__('Pro Version', 'sft-product-recommendations-for-woocommerce'); ?>
							</a>
						</div>
					</div>
				</div>
			</div>

			<div class="prwfr-ai-prompt-container" id="prwfr_textarea_container">
				<textarea id="prwfr_ai_request_prompt" name="prwfr_ai_request_prompt" rows="4" style="opacity: 0.5;width: 100%;" placeholder="Eg. Exclude products from the summer collection category in recommendations."></textarea>
			</div>
		</div>

		<div class="prwfr-ai-reset-save-container ">
			<button id="prwfr_save_ai_settings"><?php echo esc_html__('Save Settings', 'sft-product-recommendations-for-woocommerce'); ?> <span class="prwfr-ai-save-loader"></span></button>
			<button id="prwfr_reset_ai_settings"><?php echo esc_html__('Reset to Default', 'sft-product-recommendations-for-woocommerce'); ?></button>
			<button id="prwfr_undo_ai_changes"><?php echo esc_html__('Undo Changes', 'sft-product-recommendations-for-woocommerce'); ?></button>
			<span style="margin-left: auto; color: green;" class="prwfr-token-status"></span>
			<div class="prwfr-popup-btn-tooltip-container">
				<img src="<?php echo esc_attr(plugin_dir_url(dirname(__FILE__, 2)) . 'assets/images/information-icon.svg'); ?>" width="15px" height="15px" class="prwfr-popup-tooltip-icon">
				<div class="prwfr-ai-popup-btn-tooltip">
					<?php
					echo wp_kses_post(
						sprintf(
							/* translators: %1$s: token message, %2$s: link to Switch Model page, %3$s: link to OpenAI Documentation */
							__('%1$s This token limit comes from ChatGPT, not our product. For longer inputs, you can switch to a higher-limit model or check the documentation. <a href="%2$s">Switch Model</a> | <a href="%3$s" target="_blank">OpenAI Documentation</a>', 'sft-product-recommendations-for-woocommerce'),
							$token_message,
							esc_url(admin_url('admin.php?page=prwfr_api_setting_page')),
							esc_url('https://platform.openai.com/docs/models')
						)
					);
					?>
				</div>
			</div>
		</div>

		<div class="send_prompt prwfr-ai-outer-container ">
			<div class="prwfr-tokens-request-container prwfr-ai-sent-prompt-btn-container">
				<div class="prwfr-ai-request-warning"></div>
				<button id="prwfr-send-prompt-btn" class="prwfr-btn"><?php echo esc_html__('Generate AI Recommendations', 'sft-product-recommendations-for-woocommerce'); ?></button>
			</div>
		</div>
	</div>
<?php
}



/**
 * Return the information about model tokens.
 *
 * @param string $return_type return type.
 * @return array|int|string Array of all token info or specific value.
 */
function prwfr_get_token($return_type = 'all')
{

	// Make sure model is updated.
	prwfr_update_model_token_option();

	// Fetch the new option.
	$all_models_token_limit_max = get_option('prprow_models_token_limit_max');

	// Get selected model safely.
	$model_name = get_option('prwfr_openai_api_model', '');
	if (empty($model_name) || ! isset($all_models_token_limit_max[$model_name])) {
		return array(
			'error'               => true,
			'message'             => empty($model_name) ? 'No model selected.' : 'Selected model is invalid.',
			'input_limit'         => 0,
			'output_limit'        => 0,
			'usable_input_tokens' => 0,
			'buffer'              => 0,
		);
	}

	$model_max_token_limit = $all_models_token_limit_max[$model_name];
	$context_window        = intval($model_max_token_limit['context_window'] ?? 0);
	$output_limit          = intval($model_max_token_limit['output'] ?? 0);

	// calculating the input token by subtracting the output tokens from the context window of that model.
	$input_limit = $context_window - $output_limit;

	// 5% buffer
	if ($context_window < 128000) {
		$buffer = intval($context_window * 0.05);
	} else {
		$buffer = intval($context_window * 0.01);
	}

	$usable_input_tokens = max(0, $input_limit - $buffer);

	// Dynamic message using actual tokens.
	$message = sprintf(
		'The selected model "%s" has a maximum input token limit of %d tokens. We reserve %d tokens as a safety buffer, leaving approximately %d usable input tokens.',
		$model_name,
		$input_limit,
		$buffer,
		$usable_input_tokens
	);

	$data = array(
		'error'               => false,
		'message'             => $message,
		'input_limit'         => $input_limit,
		'output_limit'        => $output_limit,
		'usable_input_tokens' => $usable_input_tokens,
		'buffer'              => $buffer,
	);

	// Return only requested type if provided.
	if ('input_limit' === $return_type) {
		return $data['input_limit'];
	}
	if ('output_limit' === $return_type) {
		return $data['output_limit'];
	}
	if ('usable_input_tokens' === $return_type) {
		return $data['usable_input_tokens'];
	}
	if ('buffer' === $return_type) {
		return $data['buffer'];
	}
	if ('message' === $return_type) {
		return $data['message'];
	}

	// Default: return full array.
	return $data;
}

/**
 * Update Token with new values.
 *
 * @return void
 */
function prwfr_update_model_token_option()
{

	$update_option = 'prprow_models_token_limit_max_v2';
	$is_updated    = get_option($update_option);

	if (! $is_updated) {

		$all_models_token_limit_max = array(
			// GPT-3.5 family.
			'gpt-3.5-turbo'             => array(
				'context_window' => 16385,
				'output'         => 4096,
			),
			'gpt-3.5-turbo-1106'        => array(
				'context_window' => 16385,
				'output'         => 4096,
			),
			'gpt-3.5-turbo-0125'        => array(
				'context_window' => 16385,
				'output'         => 4096,
			),
			'gpt-3.5-turbo-16k'         => array(
				'context_window' => 16385,
				'output'         => 4096,
			),

			// GPT-4 base.
			'gpt-4'                     => array( // SAME IP / OP ? updated the limts as 2048 cause both limits were same.
				'context_window' => 8192,
				'output'         => 2048,
			),
			'gpt-4-0613'                => array( // SAME IP / OP ? updated the limts as 2048 cause both limits were same.
				'context_window' => 8192,
				'output'         => 2048,
			),

			// GPT-4 Turbo.
			'gpt-4-turbo'               => array(
				'context_window' => 128000,
				'output'         => 4096,
			),
			'gpt-4-turbo-preview'       => array(
				'context_window' => 128000,
				'output'         => 4096,
			),
			'gpt-4-0125-preview'        => array(
				'context_window' => 128000,
				'output'         => 4096,
			),
			'gpt-4-turbo-2024-04-09'    => array(
				'context_window' => 128000,
				'output'         => 4096,
			),

			// updated the name of model as the dropdown shows different name than documentation.
			'gpt-4-1106-preview'        => array(
				'context_window' => 128000,
				'output'         => 4096,
			),

			// GPT-4o family.
			'gpt-4o'                    => array(
				'context_window' => 128000,
				'output'         => 16384,
			),
			'gpt-4o-2024-05-13'         => array(
				'context_window' => 128000,
				'output'         => 4096,
			),
			'gpt-4o-2024-08-06'         => array(
				'context_window' => 128000,
				'output'         => 16384,
			),
			'gpt-4o-2024-11-20'         => array(
				'context_window' => 128000,
				'output'         => 16384,
			),
			'chatgpt-4o-latest'         => array(
				'context_window' => 128000,
				'output'         => 16384,
			),

			// GPT-4o Mini.
			'gpt-4o-mini'               => array(
				'context_window' => 128000,
				'output'         => 16384,
			),
			'gpt-4o-mini-2024-07-18'    => array(
				'context_window' => 128000,
				'output'         => 16384,
			),

			// GPT-4.1 family.
			'gpt-4.1'                   => array(
				'context_window' => 1048576,
				'output'         => 32768,
			),
			'gpt-4.1-mini'              => array(
				'context_window' => 1048576,
				'output'         => 32768,
			),
			'gpt-4.1-nano'              => array(
				'context_window' => 1048576,
				'output'         => 32768,
			),
			'gpt-4.1-2025-04-14'        => array(
				'context_window' => 1048576,
				'output'         => 32768,
			),
			'gpt-4.1-mini-2025-04-14'   => array(
				'context_window' => 1048576,
				'output'         => 32768,
			),
			'gpt-4.1-nano-2025-04-14'   => array(
				'context_window' => 1048576,
				'output'         => 32768,
			),

			// GPT-5 chat (latest).
			'gpt-5-chat-latest'         => array(
				'context_window' => 128000,
				'output'         => 16384,
			),

			// GPT-4o Transcribe Diarize.
			'gpt-4o-transcribe-diarize' => array(
				'context_window' => 16000,
				'output'         => 2000,
			),
		);

		// Store in new option to keep old version intact.
		update_option('prprow_models_token_limit_max', $all_models_token_limit_max);
	}

	update_option($update_option, true);
}
