<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once("config.php");
require_once("user/protect.php");
require_once("user/user-lib.php");

@set_time_limit(3000);
@ini_set('max_execution_time', 900);

$db = new PDO(
      "mysql:host=".USER_DB_HOST.";dbname=".USER_DB_NAME.";charset=".USER_DB_CHARSET,
      USER_DB_USER, USER_DB_PASSWORD, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);

if ($masterkeymode==false) {
	$query = "SELECT user_apikey FROM users WHERE user_id = :userid";
	$statement = $db->prepare($query);
	$statement->bindParam(':userid', $userid);
	$statement->execute();
	$result = $statement->fetch(PDO::FETCH_ASSOC);
	if ($result && !empty($result['user_apikey'])) {
		$api_key = $result['user_apikey'];
	} else {
		echo "NOUSERKEY";
		exit();
	}
} else {
	$api_key = $masterapikey;
}

$postfields = array();
foreach ($_POST as $key => $value) {
    $postfields[$key] = $value;
	$postfields[$key]=str_replace("'","",$postfields[$key]);
	$postfields[$key]=addslashes($postfields[$key]);			
}

$toneoptions = array(
	"1" => "Authoritative",
	"2" => "Casual",
	"3" => "Confident",
	"4" => "Conversational",
	"5" => "Educational",
	"6" => "Empathetic",
	"7" => "Encouraging",
	"8" => "Enthusiastic",
	"9" => "Friendly",
	"10" => "Informative",
	"11" => "Lighthearted",
	"12" => "Optimistic",
	"13" => "Persuasive",
	"14" => "Professional",
	"15" => "Straightforward",
	"16" => "Technical"
);
$tone="";
$tonenumber=$postfields["tone"];
if (isset($toneoptions[$tonenumber])) {
	$tone = $toneoptions[$tonenumber];
} 
$langoptions = [
    "1" => "Chinese",
    "2" => "Dutch",
    "3" => "English",
    "4" => "French",
    "5" => "German",
    "6" => "Italian",
    "7" => "Japanese",
    "8" => "Korean",
    "9" => "Portuguese",
    "10" => "Russian",
    "11" => "Spanish",
    "12" => "Vietnamese"
];
$language="";
$langnumber=$postfields["language"];
if (isset($langoptions[$langnumber])) {
	$language = $langoptions[$langnumber];
}

$panel_input=$postfields["panel_input"];

$target_audience=trim($postfields["audience"]);

$audience_insert="Throughout this task, infuse your writing with the chosen tone: [".$tone."]. Maintain a professional demeanor, eliminating any self-references, apologies, reminders about the instructions, or expressions of gratitude. Refrain from any self-referential remarks. Do not repeat back any of this prompt in your output.";
if($target_audience!==""){
	$audience_insert="Throughout this task, infuse your writing with the chosen tone: [".$tone."] to establish a connection with the target audience of: [".$target_audience."]. Maintain a professional demeanor, eliminating any self-references, apologies, reminders about the instructions, or expressions of gratitude. Refrain from any self-referential remarks. Do not repeat back any of this prompt in your output.";
}

if (isset($postfields["mode"])){
	
	switch ($postfields["mode"]) {
		
		case "p1" :
						
			$prompt="Adopt the persona of a seasoned marketing copywriter and design a persuasive call to action tailored specifically for the campaign centered on [".$panel_input."]. The copy should be drenched in the specified tonality, [".$tone."], effectively reflecting the mood and spirit of the campaign. Moreover, ensure that the call to action is composed in the requested language, [".$language."], to directly engage the target demographic. ".$audience_insert;
			
			sendPrompt($prompt,$aiengine,$api_key);
			
			break;		
		
		case "p2" :
		
			$prompt="Immerse yourself in the digital tapestry of social media, crafting a series of four distinctive posts, each ingeniously tailored to the peculiarities of a specific platform, all circling around the central theme of [".$panel_input."].  The first post, a Facebook masterpiece, should reflect the platform's wide-ranging demographic and its emphasis on interactive, shareable content. Post number two takes us to the visually-striking realm of Instagram. Craft a post that revels in visual appeal, complemented by succinct, engaging text and a judicious sprinkle of relevant hashtags. Next, navigate the rapid currents of Twitter for the third post. Respect the platform's 280-character limit, condensing the essence of [".$panel_input."] into a concentrated burst of insight, wit, or provocation, supplemented with strategic hashtags for maximum reach. Finally, step into the professional arena of LinkedIn for the fourth post. Strike a balance between informative and engaging, as befits the professional nature of the platform. Throughout this task, adopt the specified [".$tone."] tone to effectively resonate with the audience, and compose in the requested language, [".$language."]. ".$audience_insert;
			
			sendPrompt($prompt,$aiengine,$api_key);
			
			break;
		
		case "p3" :
									
			$prompt="Take on the role of a viral content creator and devise a captivating, 60-second TikTok video script focused on [".$panel_input."]. This script should be a compelling fusion of brevity and engagement, delivering its core message with clarity and charm. To resonate with the chosen demographic, the script should adopt the tone : [".$tone."], and it must be penned in the requested language, [".$language."]. Integrate a trendy musical selection or catchy sound effect to heighten the video's allure and viral potential. Incorporate strategic elements to boost visibility and user interaction, such as cues for consistent content release and opportunities for audience participation. Remember to conceptualize visually striking elements that support the narrative and aim to make a lasting impact. Strive for a balance between professionalism and relatability. ".$audience_insert;
			
			sendPrompt($prompt,$aiengine,$api_key);
			
			break;
			
		case "p4" :
		
			$prompt="Embark on a comprehensive journey to construct an effective launch strategy for a fresh [".$panel_input."] Instagram account, whether it serves as a business or a theme page. The mission is to encapsulate the essence of the brand or topic, cultivating an irresistible allure for the target audience. Branding Brainstorm: Initiate this journey by sparking a brainstorming session for innovative name suggestions, steeped in the unique flavor of the brand or topic. Harness the power of industry-specific keywords to inject a touch of relevance and familiarity, striving to create a name that etches itself into the memory of the audience with its simplicity and charm. Leverage digital tools like the Instagram Name Generator to fuel your creativity. Ensure the selected name aligns with Instagram's naming conventions, using the @ prefix and avoiding spaces. Bio Blueprint: Architect a compelling brand bio that serves as a compact yet powerful window into your brand's unique narrative. The language should be crystal clear and succinct, but potent enough to convey your mission, the value you deliver, and the qualities that elevate you above the competition. Strategically weave relevant keywords into this tapestry of words to enhance discoverability. Crown your bio with a compelling call-to-action (CTA), a magnetic pull inviting visitors to immerse themselves in your brand story.  You should adopt the tone [".$tone."] when writing. The entire output should be in the language : [".$language."]. ".$audience_insert;
			
			sendPrompt($prompt,$aiengine,$api_key);
			
			break;

		default :
			echo "UNKNOWN MODE";
			break;	
	}
	exit();
} else {
	echo ("NOMODE");
	exit();
}


function sendPrompt($prompt,$aiengine,$api_key){
	$endpoint="chat/completions";
	$modelname="gpt-3.5-turbo-16k";
	$aiengine=0; 
	if ($aiengine==0) {
		$endpoint="chat/completions";
		$modelname="gpt-3.5-turbo-16k";
	} else if ($aiengine==1) {
		$endpoint="chat/completions";
		$modelname="gpt-4";		
	}
	$curl = curl_init();
	curl_setopt_array($curl, array(
	  CURLOPT_URL => 'https://api.openai.com/v1/'.$endpoint,
	  CURLOPT_RETURNTRANSFER => true,
	  CURLOPT_ENCODING => '',
	  CURLOPT_MAXREDIRS => 10,
	  CURLOPT_TIMEOUT => 0,
	  CURLOPT_FOLLOWLOCATION => true,
	  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	  CURLOPT_CUSTOMREQUEST => 'POST',
	  CURLOPT_POSTFIELDS =>'{"model":"'.$modelname.'","messages": [{"role": "user", "content": "'.$prompt.'"}],"temperature":1,"max_tokens":14000}',
	  CURLOPT_HTTPHEADER => array(
		'Authorization: Bearer '.$api_key,
		'Content-Type: application/json'
	  ),
	));
	$response = curl_exec($curl);
	if ($response===false){
		echo "APIERROR - ".curl_error($curl);
		curl_close($curl);
		exit();
	} else {
		if (isset($response['error']) && $response['status'] != 200) {
			//header("HTTP/1.1 500 Internal Server Error");
			print_r($response);
		} else {
			print_r($response);
		}		
		curl_close($curl);
		exit();
	}
	
}


?>
