<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

require_once WPAISAAS_PLUGIN_DIR_PATH . 'vendor/autoload.php';

use Orhanerday\OpenAi\OpenAi;

/**
 * Display the navigation items based on the user's role
 *
 * @return string
 */
function wpaisaas_display_navigation_based_on_role() {
	if ( ! is_user_logged_in() ) {
		redirect( wp_login_url() );
	}
	global $wp;
	$current_page_url = home_url( $wp->request );

	$current_user = wp_get_current_user();
	$user_role    = $current_user->roles[0]; // Get the first user role

	$option = wpaisaas_get_option( 'pricing_table' );

	$features = array();

	if ( ! empty( $option ) ) {
		// Define which features correspond to each role
		$features_by_role = array(
			'subscriber'                                                             => array(),
			'wpaisaas_' . strtolower( esc_html( $option['plan_title_free'] ) )       => esc_html( $option['plan_title_free'] ),
			'wpaisaas_' . strtolower( esc_html( $option['plan_title_pro'] ) )        => esc_html( $option['plan_title_pro'] ),
			'wpaisaas_' . strtolower( esc_html( $option['plan_title_enterprise'] ) ) => esc_html( $option['plan_title_enterprise'] ),
		);
		// Get the features for the user's role
		$features = $features_by_role[ $user_role ] ?? array();
	}

	// Define the navigation items and their associated features
	$navigation_items = array(
		'dashboard'    => 'Dashboard',
		'conversation' => 'Conversation',
		'custom'       => 'All Templates',
		'image'        => 'Image Generation',
	);


	// Display the navigation items

	foreach ( $navigation_items as $page_slug => $nav_text ) {
//        if (isset($features['enabled']) || $page_slug === 'dashboard') {
		if ( $page_slug === 'dashboard' || $user_role === 'super_admin' || $user_role === 'administrator' || $user_role === 'editor' || array_key_exists( $page_slug, $features['enabled'] ) ) {
			echo '<li class="nav-item ">';
			if ( rtrim( wpaisaas_get_page_link( $page_slug ), '/' ) !== $current_page_url ) {
				echo '<a class="nav-link border-top" href="' . esc_url( wpaisaas_get_page_link( $page_slug ) ) . '">';
			} else {
				echo '<a class="nav-link active border-top" href="' . esc_url( wpaisaas_get_page_link( $page_slug ) ) . '">';
			}
			echo '<div class="icon icon-shape icon-sm shadow border-radius-md bg-white text-center me-2 d-flex align-items-center justify-content-center">';

			echo match ( $page_slug ) {
				'dashboard' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/dashboard.svg" alt="Conversation Icon" width="20" height="20">',
				'conversation' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/conversation.svg" alt="Conversation Icon" width="20" height="20">',
				'image' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/image.svg" alt="Image Icon" width="20" height="20">',
				'music' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/music.svg" alt="Music Icon" width="20" height="20">',
				'hashtag' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/hashtag.svg" alt="Hashtag Icon" width="20" height="20">',
				'code' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/code.svg" alt="Code Icon" width="20" height="20">',
				default => '<i class="fas fa-tachometer-alt text-dark"></i>',
			};

			echo '</div>';

			echo '<span class="nav-link-text ms-1">' . esc_html( $nav_text ) . '</span>';
			echo '</a>';
			echo '</li>';
//            }
		}
	}


}

/**
 * Display the features based on the user's role
 *
 * @return string
 */
function wpaisaas_display_features_based_on_role() {
	$current_user = wp_get_current_user();
	$user_role    = $current_user->roles[0]; // Get the first user role

	if ( ! is_user_logged_in() ) {
		return;
	}

	$option = wpaisaas_get_option( 'pricing_table' );

	$features = array();
	if ( ! empty( $option ) ) {
		// Define which features correspond to each role
		$features_by_role = array(
			'subscriber'                                                             => array(),
			'wpaisaas_' . strtolower( esc_html( $option['plan_title_free'] ) )       => esc_html( $option['plan_title_free'] ),
			'wpaisaas_' . strtolower( esc_html( $option['plan_title_pro'] ) )        => esc_html( $option['plan_title_pro'] ),
			'wpaisaas_' . strtolower( esc_html( $option['plan_title_enterprise'] ) ) => esc_html( $option['plan_title_enterprise'] ),
		);
		$features         = $features_by_role[ $user_role ] ?? array();
	}
	// Define the navigation items and their associated features
	$navigation_items = array(
		'dashboard'    => 'Dashboard',
		'conversation' => 'Conversation',
		'custom'       => 'All Templates',
		'image'        => 'Image Generation',
	);
	echo '<div class="row">';
	// Display the navigation items
	foreach ( $navigation_items as $page_slug => $nav_text ) {
		// Check if the current user has access to this navigation item's feature
//        if (isset($features['enabled']) || $page_slug === 'dashboard') {
		if ( $page_slug === 'dashboard' || $user_role === 'super_admin' || $user_role === 'administrator' || $user_role === 'editor' || array_key_exists( $page_slug, $features['enabled'] ) ) {
			//print_r($feature);
			// print_r($value);
			echo '<div class="col-md-12 mb-4">';
			echo '<div class="card card-body border card-plain border-radius-lg d-flex align-items-center flex-row">';
			echo match ( $page_slug ) {
				'dashboard' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/dashboard.svg" alt="Conversation Icon" width="20" height="20">',
				'conversation' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/conversation.svg" alt="Conversation Icon" width="20" height="20">',
				'image' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/image.svg" alt="Image Icon" width="20" height="20">',
				'music' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/music.svg" alt="Music Icon" width="20" height="20">',
				'hashtag' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/hashtag.svg" alt="Hashtag Icon" width="20" height="20">',
				'code' => '<img src="' . esc_url( WPAISAAS_PLUGIN_DIR_URL ) . 'assets/img/logos/code.svg" alt="Code Icon" width="20" height="20">',
				default => '<i class="fas fa-tachometer-alt text-dark"></i>',
			};
			echo '<h6 class="mb-0 mx-2">' . esc_html( ucwords( $nav_text ) ) . '</h6>';
			echo '<a href="' . esc_url( wpaisaas_get_page_link( $page_slug ) ) . '" class="ms-auto text-dark cursor-pointer"><i class="fas fa-arrow-right text-sm ms-1" aria-hidden="true"></i></a>';
			echo '</div></div>';
//            }
		}
	}
	echo '</div>';
}

/**
 * Redirect users to the profile page after login
 * if they have one of the specified roles
 * @return void
 */
function wpaisaas_redirect_to_profile_page() {
	// Check if user is logged in
	if ( is_user_logged_in() ) {
		// Get current user object
		$current_user = wp_get_current_user();
		$prefix       = "wpaisaas_";
		$option       = wpaisaas_get_option( 'pricing_table' );

		// Check if user has one of the specified roles
		if ( ! empty( $option ) ) {
			$allowed_roles = array(
				'subscriber',
				$prefix . strtolower( esc_html( $option['plan_title_free'] ) ),
				$prefix . strtolower( esc_html( $option['plan_title_pro'] ) ),
				$prefix . strtolower( esc_html( $option['plan_title_enterprise'] ) )
			);
			$user_roles    = $current_user->roles;

			$intersect_roles = array_intersect( $user_roles, $allowed_roles );

			// If user has one of the allowed roles, redirect to custom profile page
			if ( ! empty( $intersect_roles ) ) {
				wp_redirect( esc_url( wpaisaas_get_page_link( 'profile' ) ) ); // Redirect to profile page
				exit;
			}
		}
	}
}

add_action( 'load-profile.php', 'wpaisaas_redirect_to_profile_page' );

function wpaisaas_get_user_ip_address() {
	// Check if the IP address is set by the server
	if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
		return $_SERVER['REMOTE_ADDR'];
	}

	return '';
}

if ( ! function_exists( 'csf_add_my_custom_css' ) ) {
	function csf_add_my_custom_css() {
		wp_enqueue_style( 'csf-custom-css', get_template_directory_uri() . '/includes/framework/assets/css/custom.css', array(), '1.0.0', 'all' );

	}

	add_action( 'csf/enqueue', 'csf_add_my_custom_css' );
}

/**
 * @param $template_name
 *
 * @return false|string|void
 */
function wpaisaas_get_page_link( $template_name ) {
	// Check if user is logged in
	if ( is_user_logged_in() ) {
		$_template_name = $template_name . "-template.php";
		$page           = get_posts( array(
			'post_type'      => 'page',
			'meta_key'       => '_wp_page_template',
			'meta_value'     => $_template_name,
			'posts_per_page' => 1,
		) );

		// Check if any page is found using the template
		$page_url = "";
		if ( $page ) {
			// Get the URL of the page
			$page_url = get_permalink( $page[0]->ID );
		}

		return $page_url;
	} else {
		// User is not logged in, redirect to login page or home page
		wp_redirect( wp_login_url() ); // Redirect to login page
		// Or
		// wp_redirect(home_url()); // Redirect to home page
		exit;
	}
}

/**
 * Get the option value from the database
 *
 * @param string $option
 * @param null $default
 *
 * @return mixed|null
 */
if ( ! function_exists( 'wpaisaas_get_option' ) ) {
	function wpaisaas_get_option( $option = '', $default = null ) {
		$options = get_option( 'wpaisaas_' ); // Attention: Set your unique id of the framework

		return ( isset( $options[ $option ] ) ) ? $options[ $option ] : $default;
	}
}

/**
 * Maximum token calculation
 *
 * @param $command
 * @param string $selected_model
 *
 * @return int
 */
function wpaisaas_get_max_token( $command, $selected_model = '' ) {
	// Skip calculation for specific model
	if ( $selected_model === 'gpt-3.5-turbo-16k' ) {
		return wpaisaas_get_option( 'wpwand_max_token', 3600 );
	}

	$total_word  = str_word_count( $command );
	$total_token = $total_word * 1.2;
	$max_token   = wpaisaas_get_option( 'wpwand_max_token', 3600 );

	$sum_of_tokens = $total_token + $max_token;
	$excess        = $sum_of_tokens - 4000;

	if ( $excess > 0 ) {
		// Subtract the excess from max_token
		$max_token -= $excess;
	}

	// Return the adjusted max_token value
	return $max_token;
}

/**
 * @param $prompt
 * @param $number_of_result
 * @param $args
 *
 * @return bool|string
 * @throws Exception
 */
function wpaisaas_prompt( $prompt, $number_of_result = 1, $args = [] ) {
	$selected_model    = $args['model'] ?? esc_html( wpaisaas_get_option( 'chat_model', 'gpt-3.5-turbo-0125' ) );
	$biz_details       = ! empty( $args['biz_details'] ) ? "Write this based on our business details, which this: " . $args['biz_details'] : "Write this based on our business details, which this: " . esc_html( wpaisaas_get_option( 'biz_details', '' ) );
	$targeted_customer = ! empty( $args['targeted_customer'] ) ? "Write this focusing the benefits of our targeted customer, which this: " . $args['targeted_customer'] : "Write this focusing the benefits of our targeted customer, which this: " . esc_html( wpaisaas_get_option( 'target_audience', '' ) );
	// $ai_character = isset($args['ai_character']) && !empty($args['ai_character']) ?  $args['ai_character'] : '';
	$language        = ! empty( $args['language'] ) ? $args['language'] : esc_html( wpaisaas_get_option( 'language', 'English' ) );
	$davinci_command = ! empty( $args['custom_command'] ) ? $prompt . ". " . $args['custom_command'] . ". You must write in " . $language . '. ' . $biz_details . ". " . $targeted_customer : $prompt . '. You must write in ' . $language . ". " . $biz_details . ". " . $targeted_customer;

	$temperature       = $args['temperature'] ?? esc_html( wpaisaas_get_option( 'temperature', 1.0 ) );
	$max_tokens        = $args['max_tokens'] ?? esc_html( wpaisaas_get_max_token( $davinci_command, $selected_model ) );
	$frequency_penalty = $args['frequency_penalty'] ?? esc_html( wpaisaas_get_option( 'frequency_penalty', 0 ) );
	$presence_penalty  = $args['presence_penalty'] ?? esc_html( wpaisaas_get_option( 'presence_penalty', 0 ) );

	return $davinci_command;

	$api_key = wpaisaas_get_option( 'openai_api_key' );
	// Call OpenAI API to generate content
	$openAI = new OpenAi( esc_html( $api_key ) );


	if ( 'gpt-3.5-turbo' == $selected_model || 'gpt-3.5-turbo-16k' == $selected_model || 'gpt-4' == $selected_model ) {
		$complete = $openAI->chat( [
			'model'             => $selected_model,
			'messages'          => [
				[
					'role'    => 'system',
					'content' => $davinci_command,
				]
			],
			'n'                 => max( $number_of_result, 1 ),
			'temperature'       => (int) $temperature,
			'max_tokens'        => (int) $max_tokens,
			'frequency_penalty' => (int) $frequency_penalty,
			'presence_penalty'  => (int) $presence_penalty,
		] );
	} else {
		$complete = $openAI->completion( [
			'n'                 => max( $number_of_result, 1 ),
			'model'             => $selected_model, // $selected_model,
			'prompt'            => $davinci_command,
			'temperature'       => (int) $temperature,
			'max_tokens'        => (int) $max_tokens,
			'frequency_penalty' => (int) $frequency_penalty,
			'presence_penalty'  => (int) $presence_penalty,
		] );

	}

	return $complete;
}

/**
 * chat api request
 * @return void
 * @throws Exception
 */
function wpaisaas_chat_api_request() {
	if ( ! isset( $_POST['input_text'] ) ) {
		wp_send_json_error( 'Input text is required' );
	}

	$inputText = sanitize_text_field( $_POST['input_text'] );


	$nonce = sanitize_text_field( $_POST['nonce'] );
	if ( ! wp_verify_nonce( $nonce, 'conversation_nonce_action' ) ) {
		wp_send_json_error( 'Invalid nonce' );
	}

	$text = wpaisaas_prompt( $inputText, 1, array(
		'custom_command'    => " You must write for general Chat wih an user. ",
		'targeted_customer' => "General Persons",
	) );

	wp_send_json_success( $text );
}

add_action( 'wp_ajax_chat_api_request', 'wpaisaas_chat_api_request' );
add_action( 'wp_ajax_nopriv_chat_api_request', 'wpaisaas_chat_api_request' );

function wpaisaas_code_api_request() {
	if ( ! isset( $_POST['input_text'] ) ) {
		wp_send_json_error( 'Input text is required' );
	}

	$inputText = sanitize_text_field( $_POST['input_text'] );
	$language  = sanitize_text_field( $_POST['language'] );
	$nonce     = sanitize_text_field( $_POST['nonce'] );
	if ( ! wp_verify_nonce( $nonce, 'code_nonce_action' ) ) {
		wp_send_json_error( 'Invalid nonce' );
	}

	$text = wpaisaas_prompt( $inputText, 1, array(
		'custom_command'    => ' Your programming language will be ' . $language,
		'biz_details'       => "Software Company",
		'targeted_customer' => "Software Company, Developer, Student, Digital Agency, Programmer etc.",
		'language'          => $language,
	) );

	wp_send_json_success( $text );
}

add_action( 'wp_ajax_code_api_request', 'wpaisaas_code_api_request' );
add_action( 'wp_ajax_nopriv_code_api_request', 'wpaisaas_code_api_request' );

function wpaisaas_hashtag_api_request() {
	if ( ! isset( $_POST['input_text'] ) ) {
		wp_send_json_error( 'Input text is required' );
	}

	$inputText = sanitize_text_field( $_POST['input_text'] );
	$language  = sanitize_text_field( $_POST['language'] );
	$keywords  = sanitize_text_field( $_POST['keywords'] );
	$nonce     = sanitize_text_field( $_POST['nonce'] );
	if ( ! wp_verify_nonce( $nonce, 'hashtag_nonce_action' ) ) {
		wp_send_json_error( 'Invalid nonce' );
	}

	$text = wpaisaas_prompt( $inputText, 1, array(
		'custom_command'    => "You must generate upto 10 hashtag with latest and current tends. Where keywords are: $keywords",
		'biz_details'       => " Blogger, Content Creator and Ecommerce Products.",
		'targeted_customer' => " Followers of Instagram, Facebook, Youtube, Twitter and Tiktok.",
		'language'          => $language,
	) );

	wp_send_json_success( ( $text ) );
}

add_action( 'wp_ajax_hashtag_api_request', 'wpaisaas_hashtag_api_request' );
add_action( 'wp_ajax_nopriv_hashtag_api_request', 'wpaisaas_hashtag_api_request' );


function wpaisaas_general_ajax_request() {
	$nonce = sanitize_text_field( $_POST['nonce'] );
	if ( ! wp_verify_nonce( $nonce, 'general_nonce_action' ) ) {
		wp_send_json_error( 'Invalid nonce' );
	}
	$categoryID       = sanitize_text_field( $_POST['categoryID'] );
	$description      = sanitize_text_field( $_POST['description'] );
	$service          = sanitize_text_field( $_POST['service'] );
	$language         = sanitize_text_field( $_POST['language'] );
	$creativity_level = sanitize_text_field( $_POST['creativity_level'] );
	$tone             = sanitize_text_field( $_POST['tone'] );
	$target_audience  = sanitize_text_field( $_POST['target_audience'] );
	$output           = sanitize_text_field( $_POST['output'] );
	$character_limit  = sanitize_text_field( $_POST['character'] );


	$taskType = wpaisaas_get_option_with_value( $categoryID );

	$prompt = wpaisaas_generate_blog_prompt( $taskType, $description, $service, $target_audience, $tone, $language, $keyPoints = null );

	$model             = esc_html( wpaisaas_get_option( 'chat_model', 'gpt-3.5-turbo-0125' ) );
	$frequency_penalty = esc_html( wpaisaas_get_option( 'frequency_penalty', 0 ) );
	$presence_penalty  = esc_html( wpaisaas_get_option( 'presence_penalty', 0 ) );

	$api_key = wpaisaas_get_option( 'openai_api_key' );

	$openAI = new OpenAi( esc_html( $api_key ) );

	try {
		// Call OpenAI API to generate content
		if ( 'gpt-3.5-turbo' == $model || 'gpt-3.5-turbo-16k' == $model || 'gpt-3.5-turbo-0125' == $model || 'gpt-4' == $model ) {
			$text = $openAI->chat( [
				'messages'          => [
					[
						'role'    => 'system',
						'content' => $prompt,
					]
				],
				'n'                 => (integer) $output,
				'model'             => $model,
				'prompt'            => $prompt,
				'temperature'       => (float) $creativity_level,
				'max_tokens'        => (int) $character_limit,
				'frequency_penalty' => (float) $frequency_penalty,
				'presence_penalty'  => (float) $presence_penalty,
			] );
		} else {
			$text = $openAI->completion( [
				'n'                 => (integer) $output,
				'model'             => $model,
				'prompt'            => $prompt,
				'temperature'       => (float) $creativity_level,
				'max_tokens'        => (integer) $character_limit,
				'frequency_penalty' => (float) $frequency_penalty,
				'presence_penalty'  => (float) $presence_penalty,
			] );
		}
		wp_send_json_success( $text );
	} catch ( Exception $e ) {
		wp_send_json_error( [ 'message' => $e->getMessage() ] );
	}
}

add_action( 'wp_ajax_general_api_request', 'wpaisaas_general_ajax_request' );
add_action( 'wp_ajax_nopriv_general_api_request', 'wpaisaas_general_ajax_request' );

/**
 * Hide the admin bar based on the user's role
 *
 * @param bool $show
 *
 * @return bool
 */
function wpaisaas_hide_admin_bar_based_on_role( $show ) {
	$current_user = wp_get_current_user();

	$option = wpaisaas_get_option( 'pricing_table' );
	if ( ! empty( $option ) ) {
		if ( in_array( 'wpaisaas_' . strtolower( $option['plan_title_free'] ), $current_user->roles ) || in_array( 'wpaisaas_' . strtolower( $option['plan_title_pro'] ), $current_user->roles ) || in_array( 'wpaisaas_' . strtolower( $option['plan_title_enterprise'] ), $current_user->roles ) ) {
			return false;
		}
	}
	return $show;
}

add_filter( 'show_admin_bar', 'wpaisaas_hide_admin_bar_based_on_role' );

/**
 * For find role Display name by role slug
 *
 * @param $role
 *
 * @return string
 */

function wpaisaas_get_role_name( $role ) {
	$option = wpaisaas_get_option( 'pricing_table' );
	switch ( $role ) {
		case 'administrator':
			echo "Administrator";
			break;
		case 'editor':
			echo "Editor";
			break;
		case 'author':
			echo "Author";
			break;
		case 'contributor':
			echo "Contributor";
			break;
		case 'subscriber':
			echo "Subscriber";
			break;
		case 'wpaisaas_' . strtolower( $option['plan_title_free'] ):
			echo esc_html( ucwords( $option['plan_title_free'] ) );
			break;
		case 'wpaisaas_' . strtolower( $option['plan_title_pro'] ):
			echo esc_html( ucwords( $option['plan_title_pro'] ) );
			break;
		case 'wpaisaas_' . strtolower( $option['plan_title_enterprise'] ):
			echo esc_html( ucwords( $option['plan_title_enterprise'] ) );
			break;
		default:
			echo "Subscriber";
	}
}

/**
 * For getting the option value with the corresponding text
 *
 * @param $value
 *
 * @return string
 */
function wpaisaas_get_option_with_value( $value ) {
	// Define the mapping of values to text
	$options = [
		23 => 'Blog Intro',
		24 => 'Blog Body',
		25 => 'Text Summarizer',
		26 => 'Sports Report',
		27 => 'Short Story',
		28 => 'Blog Outline',
		29 => 'Blog Idea Generator',
		30 => 'Blog Conclusion',
		31 => 'Fictional Story Idea',
		32 => 'Blog Paragraph',
		33 => 'E-Mail Text',
		34 => 'Facebook Ad Title',
		35 => 'Facebook Ad Text',
		36 => 'Google Ad Text',
		37 => 'Bing Ad Text',
		38 => 'Pinterest Ad Title',
		39 => 'Yandex Ad Text',
		40 => 'Google Ad Title',
		41 => 'Snapchat Ad Title',
		42 => 'Taboola Ad Text',
		43 => 'Youtube Video Title',
		44 => 'Youtube Video Description',
		45 => 'Youtube Video Topic Idea',
		46 => 'Video Script Outline',
		47 => 'Webinar Title Ideas',
		48 => 'Amazon Product Description',
		49 => 'Product Description',
		50 => 'Shopify Product Description',
		51 => 'Product Review',
		52 => 'Photo Post Caption',
		53 => 'Pinterest Pin Title',
		54 => 'Pinterest Description',
		55 => 'Personal Bio',
		56 => 'Facebook Caption',
		57 => 'LinkedIn Post',
		58 => 'Slack Text Message',
		59 => 'LinkedIn Bio',
		60 => 'Reddit Post Caption',
		61 => 'TikTok Bio',
		62 => 'Business Or Product Name',
		63 => 'Slogan Generator',
		64 => 'Pro\'s and Con\'s',
		65 => 'PAS (Problem Agitate Solution) Framework',
		66 => 'AIDA Framework',
		67 => 'SEO Meta Description',
		68 => 'Travel Copy',
		69 => 'Reply to Review',
		70 => 'Hashtag Generator',
	];

	// Check if the value exists in the array
	if ( array_key_exists( $value, $options ) ) {
		// Return the corresponding text
		return $options[ $value ];
	} else {
		// Return a default value or an error message if the value is not found
		return 'Invalid value';
	}
}


function wpaisaas_generate_blog_prompt( $taskType, $blogTopic, $service, $targetAudience, $tone, $language, $keyPoints = null ) {
	// Define default key points for each task type
	$defaultKeyPoints = [
		'Blog Intro'                               => [
			"Brief overview of the blog topic",
			"Importance of the topic for the target audience",
			"What the readers can expect to learn",
			"Encouragement to read further"
		],
		'Blog Body'                                => [
			"In-depth discussion on the blog topic",
			"Examples and supporting evidence",
			"Detailed explanations of key points",
			"Relevant statistics and data",
			"Real-life applications or case studies"
		],
		'Text Summarizer'                          => [
			"Condensed version of the main content",
			"Highlight the key points",
			"Summarize important details",
			"Convey the essence of the content in a brief manner"
		],
		'Sports Report'                            => [
			"Overview of the event/game",
			"Key moments and highlights",
			"Player performances",
			"Final scores and statistics",
			"Implications for teams/players"
		],
		'Short Story'                              => [
			"Introduction of characters and setting",
			"Development of the plot",
			"Conflict and resolution",
			"Key themes and messages",
			"Engaging and creative narrative"
		],
		'Blog Outline'                             => [
			"Main sections and subsections",
			"Key points for each section",
			"Logical flow of content",
			"Brief descriptions of each point",
			"Structure for the blog post"
		],
		'Blog Idea Generator'                      => [
			"Brainstorming techniques",
			"Trending topics in the niche",
			"Unique angles on common topics",
			"Potential titles and headlines",
			"Audience interests and needs"
		],
		'Blog Conclusion'                          => [
			"Summary of key points",
			"Restatement of the blog’s main message",
			"Final thoughts and insights",
			"Call-to-action",
			"Encouragement for reader engagement"
		],
		'Fictional Story Idea'                     => [
			"Creative story concepts",
			"Interesting characters",
			"Unique settings",
			"Potential plot twists",
			"Key themes and messages"
		],
		'Blog Paragraph'                           => [
			"Detailed explanation of a specific point",
			"Supporting evidence and examples",
			"Clear and concise language",
			"Logical connection to other paragraphs",
			"Engaging and informative content"
		],
		'E-Mail Text'                              => [
			"Engaging subject line",
			"Clear and concise message body",
			"Call-to-action (if applicable)",
			"Personalization (if applicable)"
		],
		'Facebook Ad Title'                        => [
			"Attention-grabbing headline",
			"Relevant to the target audience",
			"Clear and concise",
			"Includes a benefit or value proposition"
		],
		'Facebook Ad Text'                         => [
			"Compelling ad copy",
			"Highlighting key features or benefits",
			"Call-to-action",
			"Engaging language"
		],
		'Google Ad Text'                           => [
			"Relevant to the target audience",
			"Clear and concise",
			"Includes keywords",
			"Call-to-action",
			"Engaging language"
		],
		'Bing Ad Text'                             => [
			"Relevant to the target audience",
			"Clear and concise",
			"Includes keywords",
			"Call-to-action",
			"Engaging language"
		],
		'Pinterest Ad Title'                       => [
			"Attention-grabbing headline",
			"Relevant to the target audience",
			"Clear and concise",
			"Includes a benefit or value proposition"
		],
		'Yandex Ad Text'                           => [
			"Relevant to the target audience",
			"Clear and concise",
			"Includes keywords",
			"Call-to-action",
			"Engaging language"
		],
		'Google Ad Title'                          => [
			"Attention-grabbing headline",
			"Relevant to the target audience",
			"Clear and concise",
			"Includes a benefit or value proposition"
		],
		'Snapchat Ad Title'                        => [
			"Attention-grabbing headline",
			"Relevant to the target audience",
			"Clear and concise",
			"Includes a benefit or value proposition"
		],
		'Taboola Ad Text'                          => [
			"Relevant to the target audience",
			"Clear and concise",
			"Includes keywords",
			"Call-to-action",
			"Engaging language"
		],
		'Youtube Video Title'                      => [
			"Attention-grabbing title",
			"Relevant to the video content",
			"Clear and concise",
			"Includes keywords",
			"Engaging language"
		],
		'Youtube Video Description'                => [
			"Detailed description of the video content",
			"Key points covered in the video",
			"Call-to-action",
			"Engaging language"
		],
		'Youtube Video Topic Idea'                 => [
			"Creative and engaging video topic",
			"Relevant to the target audience",
			"Clear and concise",
			"Includes keywords",
			"Engaging language"
		],
		'Video Script Outline'                     => [
			"Main sections and key points",
			"Logical flow of the video content",
			"Engaging introduction",
			"Clear and concise language",
			"Call-to-action"
		],
		'Webinar Title Ideas'                      => [
			"Attention-grabbing webinar title",
			"Relevant to the target audience",
			"Clear and concise",
			"Includes keywords",
			"Engaging language"
		],
		'Amazon Product Description'               => [
			"Detailed product description",
			"Key features and benefits",
			"Clear and concise language",
			"Engaging language",
			"Call-to-action"
		],
		'Product Description'                      => [
			"Detailed product description",
			"Key features and benefits",
			"Clear and concise language",
			"Engaging language",
			"Call-to-action"
		],
		'Shopify Product Description'              => [
			"Detailed product description",
			"Key features and benefits",
			"Clear and concise language",
			"Engaging language",
			"Call-to-action"
		],
		'Product Review'                           => [
			"Detailed product review",
			"Key features and benefits",
			"Honest and unbiased opinion",
			"Engaging language",
			"Call-to-action"
		],
		'Photo Post Caption'                       => [
			"Engaging caption for the photo",
			"Relevant to the image",
			"Clear and concise",
			"Includes hashtags",
			"Engaging language"
		],
		'Pinterest Pin Title'                      => [
			"Attention-grabbing title",
			"Relevant to the pin content",
			"Clear and concise",
			"Includes keywords",
			"Engaging language"
		],
		'Pinterest Description'                    => [
			"Detailed description of the pin content",
			"Key points covered in the pin",
			"Call-to-action",
			"Engaging language"
		],
		'Personal Bio'                             => [
			"Introduction of yourself",
			"Key achievements and experiences",
			"Interests and hobbies",
			"Engaging language",
			"Call-to-action (if applicable)"
		],
		'Facebook Caption'                         => [
			"Engaging caption for the post",
			"Relevant to the content",
			"Clear and concise",
			"Includes hashtags",
			"Engaging language"
		],
		'LinkedIn Post'                            => [
			"Professional post content",
			"Relevant to the target audience",
			"Clear and concise",
			"Includes hashtags",
			"Engaging language"
		],
		'Slack Text Message'                       => [
			"Clear and concise message",
			"Relevant to the conversation",
			"Engaging language",
			"Call-to-action (if applicable)"
		],
		'LinkedIn Bio'                             => [
			"Professional introduction",
			"Key achievements and experiences",
			"Interests and skills",
			"Engaging language",
			"Call-to-action (if applicable)"
		],
		'Reddit Post Caption'                      => [
			"Engaging caption for the post",
			"Relevant to the content",
			"Clear and concise",
			"Includes hashtags",
			"Engaging language"
		],
		'TikTok Bio'                               => [
			"Introduction of yourself",
			"Key interests and talents",
			"Engaging language",
			"Call-to-action (if applicable)"
		],
		'Business Or Product Name'                 => [
			"Creative and memorable name",
			"Relevant to the business or product",
			"Clear and concise",
			"Engaging language",
			"Call-to-action (if applicable)"
		],
		'Slogan Generator'                         => [
			"Catchy and memorable slogan",
			"Relevant to the business or product",
			"Clear and concise",
			"Engaging language",
			"Call-to-action (if applicable)"
		],
		'Pro\'s and Con\'s'                        => [
			"List of advantages and disadvantages",
			"Clear and concise",
			"Balanced perspective",
			"Engaging language",
			"Call-to-action (if applicable)"
		],
		'PAS (Problem Agitate Solution) Framework' => [
			"Identify the problem",
			"Agitate the problem",
			"Provide a solution",
			"Engaging language",
			"Call-to-action (if applicable)"
		],
		'AIDA Framework'                           => [
			"Attention-grabbing headline",
			"Generate interest",
			"Create desire",
			"Call-to-action",
			"Engaging language"
		],
		'SEO Meta Description'                     => [
			"Relevant to the content",
			"Includes keywords",
			"Clear and concise",
			"Engaging language",
			"Call-to-action (if applicable)"
		],
		'Travel Copy'                              => [
			"Engaging travel content",
			"Descriptive language",
			"Clear and concise",
			"Engaging language",
			"Call-to-action (if applicable)"
		],
		'Reply to Review'                          => [
			"Acknowledge the review",
			"Address any concerns",
			"Express gratitude",
			"Engaging language",
			"Call-to-action (if applicable)"
		],
		'Hashtag Generator'                        => [
			"Generate relevant hashtags",
			"Based on the content",
			"Clear and concise",
			"Engaging language",
			"Call-to-action (if applicable)"
		],

	];

	// Use provided key points or default to the general key points for the specific task
	if ( is_null( $keyPoints ) && isset( $defaultKeyPoints[ $taskType ] ) ) {
		$keyPoints = $defaultKeyPoints[ $taskType ];
	}

	// Generate the prompt based on the task type
	$prompt = "
    You are an AI assistant designed to help with blog writing. Your task is to write a compelling and engaging $taskType for a blog post in $language.

    Blog Title: $taskType
    Blog Topic: $blogTopic
    Product / Service / Industry: $service
    Target Audience: $targetAudience
    Desired Tone: $tone
    Key Points to Include:
    " . implode( "\n    - ", $keyPoints ) . "

    Instructions:
    ";

	// Add specific instructions based on the task type
	$instructions = [
		'Blog Intro'                               => [
			"Start with an attention-grabbing opening sentence.",
			"Introduce the blog topic and its relevance to the target audience.",
			"Highlight the key points that will be covered in the blog post.",
			"Ensure the tone is $tone.",
			"Make sure the introduction is engaging and encourages readers to continue reading.",
			"Write in $language."
		],
		'Blog Body'                                => [
			"Provide a comprehensive discussion of the blog topic.",
			"Use examples and supporting evidence to illustrate key points.",
			"Include relevant statistics and data where applicable.",
			"Maintain a logical flow and ensure clarity.",
			"Conclude with a summary of the key takeaways.",
			"Write in $language."
		],
		'Text Summarizer'                          => [
			"Provide a brief and concise summary of the main content.",
			"Highlight the most important points.",
			"Ensure the summary is clear and easy to understand.",
			"Maintain the original tone of the content.",
			"Write in $language."
		],
		'Sports Report'                            => [
			"Start with a summary of the event or game.",
			"Detail the key moments and highlights.",
			"Discuss standout player performances.",
			"Include final scores and relevant statistics.",
			"Comment on the implications for the teams or players.",
			"Write in $language."
		],
		'Short Story'                              => [
			"Introduce the main characters and setting.",
			"Develop the plot with interesting events.",
			"Include conflict and resolution.",
			"Convey key themes and messages.",
			"Use engaging and creative language.",
			"Write in $language."
		],
		'Blog Outline'                             => [
			"List the main sections and subsections of the blog.",
			"Provide key points for each section.",
			"Ensure a logical flow of content.",
			"Include brief descriptions of each point.",
			"Create a structured plan for the blog post.",
			"Write in $language."
		],
		'Blog Idea Generator'                      => [
			"Use brainstorming techniques to generate ideas.",
			"Identify trending topics in the niche.",
			"Suggest unique angles on common topics.",
			"Provide potential titles and headlines.",
			"Consider audience interests and needs.",
			"Write in $language."
		],
		'Blog Conclusion'                          => [
			"Summarize the key points discussed in the blog.",
			"Restate the blog’s main message.",
			"Provide final thoughts and insights.",
			"Include a call-to-action.",
			"Encourage reader engagement.",
			"Write in $language."
		],
		'Fictional Story Idea'                     => [
			"Generate creative and unique story concepts.",
			"Suggest interesting characters.",
			"Propose unique settings.",
			"Include potential plot twists.",
			"Identify key themes and messages.",
			"Write in $language."
		],
		'Blog Paragraph'                           => [
			"Provide a detailed explanation of a specific point.",
			"Include supporting evidence and examples.",
			"Use clear and concise language.",
			"Ensure a logical connection to other paragraphs.",
			"Make the content engaging and informative.",
			"Write in $language."
		],
		'E-Mail Text'                              => [
			"Craft an engaging subject line.",
			"Write a clear and concise message body.",
			"Include a call-to-action (if applicable).",
			"Personalize the message (if applicable).",
			"Write in $language."
		],
		'Facebook Ad Title'                        => [
			"Create an attention-grabbing headline.",
			"Ensure the title is relevant to the target audience.",
			"Keep the title clear and concise.",
			"Include a benefit or value proposition.",
			"Write in $language."
		],
		'Facebook Ad Text'                         => [
			"Write compelling ad copy.",
			"Highlight key features or benefits.",
			"Include a call-to-action.",
			"Use engaging language.",
			"Write in $language."
		],
		'Google Ad Text'                           => [
			"Ensure the ad is relevant to the target audience.",
			"Keep the text clear and concise.",
			"Include keywords.",
			"Include a call-to-action.",
			"Use engaging language.",
			"Write in $language."
		],
		'Bing Ad Text'                             => [
			"Ensure the ad is relevant to the target audience.",
			"Keep the text clear and concise.",
			"Include keywords.",
			"Include a call-to-action.",
			"Use engaging language.",
			"Write in $language."
		],
		'Pinterest Ad Title'                       => [
			"Create an attention-grabbing headline.",
			"Ensure the title is relevant to the target audience.",
			"Keep the title clear and concise.",
			"Include a benefit or value proposition.",
			"Write in $language."
		],
		'Yandex Ad Text'                           => [
			"Ensure the ad is relevant to the target audience.",
			"Keep the text clear and concise.",
			"Include keywords.",
			"Include a call-to-action.",
			"Use engaging language.",
			"Write in $language."
		],
		'Google Ad Title'                          => [
			"Create an attention-grabbing headline.",
			"Ensure the title is relevant to the target audience.",
			"Keep the title clear and concise.",
			"Include a benefit or value proposition.",
			"Write in $language."
		],
		'Snapchat Ad Title'                        => [
			"Create an attention-grabbing headline.",
			"Ensure the title is relevant to the target audience.",
			"Keep the title clear and concise.",
			"Include a benefit or value proposition.",
			"Write in $language."
		],
		'Taboola Ad Text'                          => [
			"Ensure the ad is relevant to the target audience.",
			"Keep the text clear and concise.",
			"Include keywords.",
			"Include a call-to-action.",
			"Use engaging language.",
			"Write in $language."
		],
		'Youtube Video Title'                      => [
			"Create an attention-grabbing title.",
			"Ensure the title is relevant to the video content.",
			"Keep the title clear and concise.",
			"Include keywords.",
			"Use engaging language.",
			"Write in $language."
		],
		'Youtube Video Description'                => [
			"Provide a detailed description of the video content.",
			"Include key points covered in the video.",
			"Include a call-to-action.",
			"Use engaging language.",
			"Write in $language."
		],
		'Youtube Video Topic Idea'                 => [
			"Generate a creative and engaging video topic.",
			"Ensure the topic is relevant to the target audience.",
			"Keep the topic clear and concise.",
			"Include keywords.",
			"Use engaging language.",
			"Write in $language."
		],
		'Video Script Outline'                     => [
			"List the main sections and key points of the video.",
			"Ensure a logical flow of the video content.",
			"Create an engaging introduction.",
			"Use clear and concise language.",
			"Include a call-to-action.",
			"Write in $language."
		],
		'Webinar Title Ideas'                      => [
			"Create an attention-grabbing webinar title.",
			"Ensure the title is relevant to the target audience.",
			"Keep the title clear and concise.",
			"Include keywords.",
			"Use engaging language.",
			"Write in $language."
		],
		'Amazon Product Description'               => [
			"Provide a detailed product description.",
			"Highlight key features and benefits.",
			"Use clear and concise language.",
			"Use engaging language.",
			"Include a call-to-action.",
			"Write in $language."
		],
		'Product Description'                      => [
			"Provide a detailed product description.",
			"Highlight key features and benefits.",
			"Use clear and concise language.",
			"Use engaging language.",
			"Include a call-to-action.",
			"Write in $language."
		],
		'Shopify Product Description'              => [
			"Provide a detailed product description.",
			"Highlight key features and benefits.",
			"Use clear and concise language.",
			"Use engaging language.",
			"Include a call-to-action.",
			"Write in $language."
		],
		'Product Review'                           => [
			"Provide a detailed product review.",
			"Highlight key features and benefits.",
			"Offer an honest and unbiased opinion.",
			"Use engaging language.",
			"Include a call-to-action.",
			"Write in $language."
		],
		'Photo Post Caption'                       => [
			"Create an engaging caption for the photo.",
			"Ensure the caption is relevant to the image.",
			"Keep the caption clear and concise.",
			"Include hashtags.",
			"Use engaging language.",
			"Write in $language."
		],
		'Pinterest Pin Title'                      => [
			"Create an attention-grabbing title.",
			"Ensure the title is relevant to the pin content.",
			"Keep the title clear and concise.",
			"Include keywords.",
			"Use engaging language.",
			"Write in $language."
		],
		'Pinterest Description'                    => [
			"Provide a detailed description of the pin content.",
			"Include key points covered in the pin.",
			"Include a call-to-action.",
			"Use engaging language.",
			"Write in $language."
		],
		'Personal Bio'                             => [
			"Introduce yourself in a professional manner.",
			"Highlight key achievements and experiences.",
			"Share interests and hobbies.",
			"Use engaging language.",
			"Include a call-to-action (if applicable).",
			"Write in $language."
		],
		'Facebook Caption'                         => [
			"Create an engaging caption for the post.",
			"Ensure the caption is relevant to the content.",
			"Keep the caption clear and concise.",
			"Include hashtags.",
			"Use engaging language.",
			"Write in $language."
		],
		'LinkedIn Post'                            => [
			"Craft a professional post content.",
			"Ensure the content is relevant to the target audience.",
			"Keep the content clear and concise.",
			"Include hashtags.",
			"Use engaging language.",
			"Write in $language."
		],
		'Slack Text Message'                       => [
			"Write a clear and concise message.",
			"Ensure the message is relevant to the conversation.",
			"Use engaging language.",
			"Include a call-to-action (if applicable).",
			"Write in $language."
		],
		'LinkedIn Bio'                             => [
			"Create a professional introduction.",
			"Highlight key achievements and experiences.",
			"Share interests and skills.",
			"Use engaging language.",
			"Include a call-to-action (if applicable).",
			"Write in $language."
		],
		'Reddit Post Caption'                      => [
			"Create an engaging caption for the post.",
			"Ensure the caption is relevant to the content.",
			"Keep the caption clear and concise.",
			"Include hashtags.",
			"Use engaging language.",
			"Write in $language."
		],
		'TikTok Bio'                               => [
			"Introduce yourself in a creative manner.",
			"Highlight key interests and talents.",
			"Use engaging language.",
			"Include a call-to-action (if applicable).",
			"Write in $language."
		],
		'Business Or Product Name'                 => [
			"Create a creative and memorable name.",
			"Ensure the name is relevant to the business or product.",
			"Keep the name clear and concise.",
			"Use engaging language.",
			"Include a call-to-action (if applicable).",
			"Write in $language."
		],
		'Slogan Generator'                         => [
			"Generate a catchy and memorable slogan.",
			"Ensure the slogan is relevant to the business or product.",
			"Keep the slogan clear and concise.",
			"Use engaging language.",
			"Include a call-to-action (if applicable).",
			"Write in $language."
		],
		'Pro\'s and Con\'s'                        => [
			"List the advantages and disadvantages of a product or service.",
			"Provide a balanced perspective.",
			"Use clear and concise language.",
			"Use engaging language.",
			"Include a call-to-action (if applicable).",
			"Write in $language."
		],
		'PAS (Problem Agitate Solution) Framework' => [
			"Identify the problem faced by the target audience.",
			"Agitate the problem to create urgency.",
			"Provide a solution to the problem.",
			"Use engaging language.",
			"Include a call-to-action (if applicable).",
			"Write in $language."
		],
		'AIDA Framework'                           => [
			"Create an attention-grabbing headline.",
			"Generate interest in the content.",
			"Create desire for the product or service.",
			"Include a call-to-action.",
			"Use engaging language.",
			"Write in $language."
		],
		'SEO Meta Description'                     => [
			"Write a meta description that is relevant to the content.",
			"Include keywords for SEO purposes.",
			"Keep the description clear and concise.",
			"Use engaging language.",
			"Include a call-to-action (if applicable).",
			"Write in $language."
		],
		'Travel Copy'                              => [
			"Write engaging travel content.",
			"Use descriptive language to paint a picture.",
			"Keep the content clear and concise.",
			"Use engaging language.",
			"Include a call-to-action (if applicable).",
			"Write in $language."
		],
		'Reply to Review'                          => [
			"Acknowledge the review and express gratitude.",
			"Address any concerns raised in the review.",
			"Use engaging language to maintain a positive tone.",
			"Include a call-to-action (if applicable).",
			"Write in $language."
		],
		'Hashtag Generator'                        => [
			"Identify key themes and topics.",
			"Research popular hashtags.",
			"Use location-specific hashtags.",
			"Include activity and interest hashtags.",
			"Combine general and niche hashtags.",
			"Keep hashtags relevant and specific.",
			"Limit the number of hashtags.",
			"Utilize GPT-4 for suggestions.",
			"Test and adjust.",
			"Write in $language."
		],

	];

	if ( isset( $instructions[ $taskType ] ) ) {
		$prompt .= implode( "\n        ", $instructions[ $taskType ] );
	}

	$prompt .= "
    Use clear and concise language, and maintain a logical flow. Aim for a length appropriate to the task type.
    ";

	return $prompt;
}






