<?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");
$add2=0;
if (file_exists("add2.php")){
	require_once("add2.php");
}
@set_time_limit(300);
@ini_set('max_execution_time', 300);

$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 && $add2==0) {
	$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;
}


// Check for credits system and set key accordingly

if ($add2==1){
	$api_key = $masterapikey;
}


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

$persona="";


$longtail=$postfields["longtail"];
file_put_contents("TEMPlongtail.text",$longtail);

$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"];
$product_name=$postfields["product_name"];
if (isset($langoptions[$langnumber])) {
	$language = $langoptions[$langnumber];
}

$panel_input=$postfields["panel_input"];

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

$stype=$postfields["stype"];

$spamemail=$postfields["spamemail"];

$spamsubject=$postfields["spamsubject"];

$rewritesubject=$postfields["rewritesubject"];

$rewriteemail=$postfields["rewriteemail"];

$audience_insert="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, 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.";
}
$product_name_insert="";
if (trim($product_name)!=""){$product_name_insert="The product or service is called [".$product_name."]";}

if (isset($postfields["stype"])){
	
	switch ($postfields["stype"]) {
		
		case "1": // Summary
				
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert sales copy summarizer.  I want you to write a detailed summary of sales page text that I will provide for you.  I am going to be promoting a product ".$product_name_insert." to my audience as an affiliate so your summary should be focused on the actual product being sold. Pick up on any testimonials or reviews and mention them.  Find any credible proof that the product works as advertised and mention it.  Find any USPs in the copy and highlight them.  Find any pain points and solutions in the copy and highlight them.  Find any calls to action in the copy and highlight them. Make sure your summary is at least 3000 words and covers everything - after the summary also write a bullet list of the benefits of the product and the unique features that set it apart from any competitors - all of this should be from an angle of selling it to my audience - All of your output MUST be in the language [".$language."] --- ".$audience_insert." --- Here is the sales page text : [".$postfields["panel_input"]."]  --- All of the output you create based on this prompt MUST be in the language ".$language.".";
		
			sendPrompt($prompt,$aiengine,$api_key);

			break;
			
		case "2": // Long Tails
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in SEO who writes ONLY in the language [".$language."] --- Output without description the top 20 long tail seo keywords for the text of a salespage I will provide. You MUST only output TWENTY (20) keywords. You must NOT produce more than TWENTY (20). Your output MUST be in JSON format. Here is the sales page text of the product you are writing the emails for : [".$postfields["panel_input"]."]  --- All of the output you create based on this prompt MUST be in the language ".$language.". REMEMBER: You must not output more than 20 keywords.";
			sendPrompt($prompt,$aiengine,$api_key);
			break;
			
		case "3": // Blog Post
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in writing blog posts that are geared for SEO around a long tail keyword and you only write in the language [".$language."] --- Your task is to write a blog post with great SEO in a personal, conversational and informal style, centered around the following Long Tail Keyword [".$longtail."]  --- All of the output you create based on this prompt MUST be in the language ".$language.". --- ".$audience_insert;
			
			sendPrompt($prompt,$aiengine,$api_key);
			break;

		case "4": // Article
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in writing articles that are geared for SEO around a long tail keyword and you only write in the language [".$language."] --- Your task is to write an article with great SEO centered around the following Long Tail Keyword [".$longtail."]  --- All of the output you create based on this prompt MUST be in the language ".$language.". --- ".$audience_insert;
			
			sendPrompt($prompt,$aiengine,$api_key);
			break;

		case "5": // Keyword Video Script
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in writing YouTube video scripts that are geared for SEO around a long tail keyword and you only write in the language [".$language."] --- Your task is to write an SEO centric YouTube Video script centered around the following Long Tail Keyword [".$longtail."] --- After the script include a selection of SEO centric youtube tags related to the script --- All of the output you create based on this prompt MUST be in the language ".$language.". --- ".$audience_insert;
			
			sendPrompt($prompt,$aiengine,$api_key);
			break;


		case "6": // Specific Video Script
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in writing YouTube video scripts that are geared for SEO around a long tail keyword and you only write in the language [".$language."] --- Your task is to write an SEO centric YouTube Video script centered around the following Long Tail Keyword [".$longtail."] for the product or service that I will give you details about and at the end --- After the script include a selection of SEO centric youtube tags related to the script ---  You MUST include the long tail keyword [".$longtail."] throughout the script for SEO. ".$product_name_insert.". --- Here is the product or service text [".$postfields["panel_input"]."] --- All of the output you create based on this prompt MUST be in the language ".$language.". --- ".$audience_insert;
			
			sendPrompt($prompt,$aiengine,$api_key);
			break;

			
		case "7": // More Keywords LTK
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in SEO who writes ONLY in the language [".$language."] --- Output without description the top 30 Latent Semantic Index (LSI)  seo keywords based around a long tail keyword of [".$longtail."]  Then you must output the top 30 Commercial Intent keywords based on the longtail keyword of [".$longtail."]. --- All of the output you create based on this prompt MUST be in the language ".$language.". REMEMBER: You must not output more than 20 keywords.";			
			sendPrompt($prompt,$aiengine,$api_key);
			break;

			case "8": // More Keywords Content
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in SEO who writes ONLY in the language [".$language."] --- Output without description the top 30 Latent Semantic Index (LSI)  seo keywords for the text of a salespage I will provide.  Then you must output the top 30 Commercial Intent keywords based on the salespage text. Here is the sales page text of the product you are writing the emails for : [".$postfields["panel_input"]."]  --- All of the output you create based on this prompt MUST be in the language ".$language.". REMEMBER: You must not output more than 20 keywords.";			
			sendPrompt($prompt,$aiengine,$api_key);
			break;
			

		case "9": // Press Release
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in writing Press Releases that are geared for SEO around a long tail keyword and you only write in the language [".$language."] --- Your task is to write an SEO centric Press Release centered around the following Long Tail Keyword [".$longtail."] for the product or service that I will give you details about and at the end ---   You MUST include the long tail keyword [".$longtail."] throughout the Press Release for SEO. ".$product_name_insert.". --- Here is the product or service text [".$postfields["panel_input"]."] --- All of the output you create based on this prompt MUST be in the language ".$language.". --- ".$audience_insert;
			
			sendPrompt($prompt,$aiengine,$api_key);
			break;

		case "10": // Domain Names
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in brainstorming domain names that are geared for SEO around a long tail keyword and you only write in the language [".$language."] --- Your task is to come up with 20 domain name ideas with great SEO centered around the following Long Tail Keyword [".$longtail."]  --- All of the output you create based on this prompt MUST 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) {
    $modelname = "gpt-3.5-turbo-16k"; // Default model name
    //$modelname = "gpt-3.5-turbo-1106"; 
    $endpoint = "chat/completions";
	
    if ($aiengine == 1) {
        $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_HTTPHEADER => array(
            'Authorization: Bearer ' . $api_key,
            'Content-Type: application/json'
        ),
    ));

    $postFields = json_encode(array(
        "model" => $modelname,
        "messages" => array(
            array(
                "role" => "user", 
                "content" => $prompt
            )
        ),
        "temperature" => 1,
        "max_tokens" => 8500
    ));


    curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);

    $response = curl_exec($curl);
	//file_put_contents("TEMPcurlresponse.txt",$response);

    if ($response === false) {
        echo "API Error: " . curl_error($curl);
    } else {

        print_r($response);
    }


    curl_close($curl);
}



?>
