<?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="";




$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 or topic 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": // Instagram Carousel
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in generating Instagram Carousels that are geared for engagement and you only write in the language [".$language."] --- I am going to give you information about a product, service or topic and your task is to generate an Instagram Carousel series, including titles, contents, and descriptions of images, followed by a captivating caption. Each section of the carousel should offer valuable insights or ideas related to the topic, designed to engage and inform the audience. End with a call-to-action caption that encourages interaction and sharing. ".$product_name_insert."  --- All of the output you create based on this prompt MUST be in the language ".$language.". --- ".$audience_insert." --- Here is the information about the product, service or topic : ".$postfields["panel_input"];
			
			sendPrompt($prompt,$aiengine,$api_key);
			break;
			
		case "4": // Instagram Account Creation
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in creating brand new instagram accounts and you only write in the language [".$language."]  --- Given information about a product, service or topic that I will give you describing the theme, niche, or main focus of a brand new Instagram account, generate a set of creative suggestions for the following elements: 1. Account Name Suggestions: Provide a bullet list of 10 unique and catchy Instagram account name ideas that reflect the account's theme or niche. Consider incorporating relevant keywords that are likely to attract the target audience.  Please ensure to use the @ sign at the start of the names.  2. Bio: Draft a concise and engaging bio for the Instagram account that captures the essence of its theme or niche. Include a brief description of what followers can expect from the account (e.g., daily inspiration, tips, exclusive content). Ensure the bio is limited to 150 characters or less to fit Instagram's bio space.  3. Captions/Call to Actions: Create 7 example captions that could be used for initial posts. These captions should resonate with the account's theme and encourage engagement (likes, comments, or follows). Include a strong call to action in at least one of the captions, inviting viewers to interact with the content or visit a link in the bio.  4. Hashtags: Suggest 10 relevant hashtags that can be used to increase the visibility of the posts. Ensure the hashtags are closely related to the account's theme or niche and are popular enough to attract the right audience but not so broad that the posts will get lost.  Remember, the goal is to tailor these elements to fit the specific input provided about the account's theme or niche. This includes reflecting the tone, style, and interests of the target audience in the names, bio, captions, and hashtags. --- Example Input: The account focuses on sustainable living and eco-friendly lifestyle tips. --- Expected Output: 1. Account Name Suggestions: - @EcoLifeHacks\r\n - @GreenLivingTips\r\n - @TheSustainableWay\r\n - @EarthFriendlyDaily\r\n - @EcoWarriorPath\r\n  2. Bio: 🌿 Your daily dose of eco-friendly living tips & sustainable lifestyle hacks. Let's make a greener planet together! 🌍✨ 3. Captions/Call to Actions:   - 'Embracing a sustainable lifestyle is easier than you think. Start with these simple swaps! 💚 #GoGreenWithUs' - 'Every small change counts towards a healthier planet. What's your eco-friendly tip for today? 🌱 Drop it below! 👇'  - 'Join our journey to sustainability. Follow us for daily inspiration and practical tips to live more sustainably. 🌏 #EcoWarriors'  4. Hashtags: #SustainableLiving, #EcoFriendly, #GreenLife, #EcoTips, #SaveThePlanet, #Sustainability, #EcoWarrior, #GreenLiving, #EarthFriendly, #LiveSustainably --- ".$product_name_insert."  --- Make sure to make use of carriage returns to separate things like the account name suggestions and hashtags --- All of the output you create based on this prompt MUST be in the language ".$language.". --- ".$audience_insert." --- Here is the information about the product, service or topic : [".$postfields["panel_input"]."]";
			
			sendPrompt($prompt,$aiengine,$api_key);
			break;


		case "5": // Instagram Post Generator
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in generating Instagram Posts that are geared for engagement and you only write in the language [".$language."] --- I am going to give you information about a product, service or topic and your task is to generate 5 Instagram Posts, including titles, contents, and image suggestions. Each post should offer valuable insights or ideas related to the topic, designed to engage and inform the audience.  ".$product_name_insert."  --- All of the output you create based on this prompt MUST be in the language ".$language.". --- ".$audience_insert." --- Here is the information about the product, service or topic : ".$postfields["panel_input"];
			sendPrompt($prompt,$aiengine,$api_key);
			break;


		case "6": // Instagram Layouts
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in generating Instagram Layouts that are geared for engagement and you only write in the language [".$language."] --- I am going to give you information about a product, service or topic and your task is to generate 20 unique and visually appealing Instagram story layouts that highlight its features, benefits, and related content. Consider incorporating a blend of images, text, and creative design elements to make each layout engaging and informative. --- ".$product_name_insert."--- Here are some example outputs but do not copy them or the titles verbatim : 
1. **Introduction Layout**
- Start with a vibrant background featuring an adorable puppy and introduce the dog training for newbies service with playful, eye-catching text.

2. Benefits Layout
- Create an engaging carousel that highlights the benefits of dog training for newbies, using a mix of images and descriptive text on a clean background.

3. Trainer Profile Layout
- Showcase a professional image of a dog trainer along with a brief bio, qualifications, and certifications, using a tasteful background.

4. Training Techniques Layout
- Create an infographic-style layout that explains various effective training techniques for newbies, using easy-to-understand visuals and step-by-step instructions.

5. Before & After Layout
- Share a carousel of before and after pictures of well-trained dogs to demonstrate the positive effects of the training program, using contrasting backgrounds.

6. FAQ Layout
- Answer common questions about dog training for newbies in a visually appealing Q&A format, using colorful backgrounds and clear, concise text.

7. Client Success Stories Layout
- Display testimonials from satisfied clients who have successfully trained their dogs using the service, featuring their pictures and quotes on an engaging background.

8. Puppy Training Tips Layout
- Provide new puppy owners with valuable tips for basic training, such as housebreaking and leash walking, using cute puppy images and brief text.

9. Socialization Layout
- Educate newbies on the importance of socializing their dogs and share tips on how to introduce their furry friends to new environments and other dogs, using inviting images and useful text.

10. Interactive Quiz Layout
- Engage followers with an interactive quiz about dog training basics, using captivating visuals and multiple-choice questions on a fun background.

11. Training Equipment Layout
- Showcase essential training equipment, such as clickers, treats, and training pads, using high-quality product images and informative descriptions on a clean background.

12. Training Challenges Layout
- Address common training challenges faced by newbies, such as excessive barking or chewing, providing practical solutions accompanied by relatable images.

13. Reward System Layout
- Explain the importance of a reward-based training system and showcase different types of rewards, such as treats and toys, using appealing visuals on a motivating background.

14. Demonstration Videos Layout
- Share short demonstration videos of basic training exercises, featuring a dog trainer and clear step-by-step instructions, using a professional layout.

15. Safety Tips Layout
- Educate newbies on important safety tips during training sessions, such as avoiding aggressive behavior or using proper training equipment, using attention-grabbing visuals and concise text.

16. Progress Tracking Layout
- Encourage followers to track their dog's training progress and share their achievements using a visually appealing progress tracker design with motivating quotes and milestones.

17. Interactive Stories Layout
- Create interactive stories where followers can vote on their preferred training techniques or share their dog training experiences, using captivating visuals and engaging text.

18. Breed-Specific Training Layout
- Provide tailored training tips for specific dog breeds, highlighting their unique characteristics and challenges, using breed-specific images and informative text.

19. Outdoor Training Layout
- Showcase the benefits of outdoor training and provide tips for training in different outdoor environments, using captivating images of dogs in action and informative text.

20. Continued Learning Layout
- Encourage followers to continue their dog training journey by offering recommendations for books, podcasts, and online resources, presented in an elegant layout with insightful reviews.  --- All of the output you create based on this prompt MUST be in the language ".$language.". --- ".$audience_insert." --- Here is the information about the product, service or topic : ".$postfields["panel_input"];
			sendPrompt($prompt,$aiengine,$api_key);
			break;

			
		case "7": // Boost Instagram Followers
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- you're an expert in Instagram marketing with deep knowledge of leveraging the platform to boost brands' online presence. and you only write in the language [".$language."] --- I am going to give you information about a brand, product, service or topic and your mission is to craft a comprehensive guide tailored to the provided brand, service, product, or topic. This guide should encapsulate everything from optimizing profiles and enhancing content to boosting engagement, utilizing hashtags, identifying collaboration opportunities, analyzing performance, leveraging user-generated content, strategizing Instagram advertising, and maximizing the use of Stories Highlights. Your advice should be actionable, specific, and designed to help brands skyrocket their follower count and engagement levels. Consider the unique identity and goals of the brand in question, providing strategies that they can immediately implement to command attention and dominate the Instagram scene.. --- ".$product_name_insert." --- ".$language.". --- ".$audience_insert." --- Here is the information about the brand, product, service or topic : ".$postfields["panel_input"];
			sendPrompt($prompt,$aiengine,$api_key);
			break;

		case "8": // Instagram Hashtags
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- you're an expert in Instagram hashtag creation and seo with deep knowledge of leveraging the platform to boost brands' online presence. and you only write in the language [".$language."] --- I am going to give you information about a brand, product, service or topic and your mission is to craft at least 20 optimized hashtags that are highly to the provided brand, service, product, or topic. The hashtags should be optimized to maximize SEO, Engagement and encourage sharing --- ".$product_name_insert." --- ".$language.". --- ".$audience_insert." --- Here is the information about the brand, product, service or topic : ".$postfields["panel_input"];
		
			
			sendPrompt($prompt,$aiengine,$api_key);
			break;
			

		case "9": // Content Calendar
		
			$prompt="All of the output you create based on this prompt MUST be in the language ".$language." --- You are an expert in generating Instagram Calendars and you only write in the language [".$language."] --- I am going to give you information about a brand, product, service or topic and your task is to Create a detailed content calendar for an Instagram account focusing on the information about the brand, product, service or topic that I provide. The calendar should cover a one-month period and include a mix of educational, promotional, and engaging content tailored to the theme. Each entry in the calendar should specify the date, the type of content (e.g., photo, video, infographic), the main hashtags to be used, and a captivating caption to accompany the post. Ensure the content is varied to maintain audience interest, avoid repetition, and align with the brand or topic's goals. Highlight any special dates or events relevant to the theme that should be considered. Guidelines:    Ensure each week offers a variety of content types (e.g., infographics on nutrition, video workout guides, progress pictures) to keep the audience engaged.    Incorporate hashtags that are popular within the theme's community but also include specific ones created for the brand or topic. Captions should be motivational, informative, or question-based to encourage engagement. Make sure to insert a few line breaks between each date--- ".$product_name_insert."--- Here are some example inputs and outputs but do not copy them or the titles verbatim : 

Example Input:

I have a school that trains mountain rescue dogs

Example Output:
Here's a one-month calendar for Instagram posts on mountain rescue dog training:

Week 1

Date: 1st January | Content: Introducing our mountain rescue dogs and their handlers. | Hashtags: #MountainRescueDogs #SearchAndRescue #K9Heroes #DogTraining | Caption: 'Meet our incredible mountain rescue dogs and their dedicated handlers who work tirelessly to save lives. 🐾 #K9Heroes'
Date: 4th January | Content: Behind the scenes of a mountain rescue dog training session. | Hashtags: #TrainingSessions #K9Training #RescueDogLife #Teamwork | Caption: 'Get an exclusive look at the intense training sessions our mountain rescue dogs undergo to become the heroes they are. 🚁 #TeamworkMakesTheDreamWork'
Date: 6th January | Content: Training tip on obedience and command recognition. | Hashtags: #TrainingTips #ObedienceTraining #RescueDogs #MountainSafety | Caption: 'Proper obedience training, like mastering commands, helps our mountain rescue dogs excel in their life-saving missions. 🐾 #MountainSafetyFirst'

Week 2

Date: 8th January | Content: Showcase of agility training exercises for mountain rescue dogs. | Hashtags: #AgilityTraining #CanineAthletes #MountainRescueSkills #SearchAndRescue | Caption: 'Watch our highly skilled mountain rescue dogs in action as they conquer various agility training exercises. 🐕 #CanineAthletes'
Date: 10th January | Content: Important equipment used by mountain rescue dogs during operations. | Hashtags: #RescueDogGear #SearchAndRescueTools #K9Essentials #MountainSafetyEquipment | Caption: 'From harnesses to safety ropes, these are the essential tools that ensure our brave mountain rescue dogs are always prepared. 🛠️ #MountainSafety'
Date: 12th January | Content: Photo compilation of successful mountain rescue missions. | Hashtags: #RescueSuccess #LifeSavers #MountainHeroes #SearchAndRescueOperations | Caption: 'We take great pride in sharing some heartwarming moments from our successful mountain rescue missions. 🏔️❤️ #MountainHeroes'

Week 3

Date: 15th January | Content: Introduction to the intensive scent training our mountain rescue dogs undergo. | Hashtags: #ScentTraining #K9NoseWork #SearchAndRescueSkills #TrainHardWorkHarder | Caption: 'Discover the remarkable scent detection skills that our mountain rescue dogs acquire through rigorous training. 🐾 #NoseKnowsBest'
Date: 18th January | Content: Inspirational story of a mountain rescue dog's heroic act. | Hashtags: #HeroicDogs #InspiringTales #RescueStories #K9Heroes | Caption: 'Prepare to be amazed by the awe-inspiring story of a mountain rescue dog who went above and beyond to save a life. 🐕❤️ #TrueHeroes'
Date: 20th January | Content: Q&A session with a mountain rescue dog handler. | Hashtags: #AskTheHandler #MountainRescueExperts #K9Insights #DogTrainingTips | Caption: 'Have burning questions about mountain rescue dogs? Our experienced handler is here to answer them all. 🗣️ #AskTheExpert'

Week 4

Date: 22nd January | Content: Highlighting the close bond between mountain rescue dogs and their handlers. | Hashtags: #HumanAndCanineBond #K9Partners #UnbreakableConnection #MountainRescueFamily | Caption: 'The relationship between our mountain rescue dogs and handlers goes beyond words, forging an unbreakable connection. 🐾❤️ #K9Partnership'
Date: 25th January | Content: Training video demonstrating avalanche rescue techniques. | Hashtags: #AvalancheTraining #SnowRescueSkills #K9AvalancheRescue #MountainSafetySkills | Caption: 'Witness the precision and expertise of our mountain rescue dogs as they showcase their avalanche rescue skills in action. 🏔️❄️ #SnowHeroes'
Date: 27th January | Content: Heartfelt testimonials from individuals rescued by mountain rescue dogs. | Hashtags: #RescueTestimonials #SavedByADog #ForeverGrateful #MountainRescueSuccess | Caption: 'Listen to the touching stories of gratitude from those whose lives have been saved by our incredible mountain rescue dogs. 🙏💙 #ForeverGrateful'

Keep engaging, informing, and inspiring your Instagram audience with captivating content that showcases the admirable work of mountain rescue dogs. Remember to utilize a mix of photos, videos, and infographics to cater to different preferences and maintain audience interest.
 --- All of the output you create based on this prompt MUST be in the language ".$language.". --- ".$audience_insert." --- Here is the information about the product, service or topic : ".$postfields["panel_input"];
			
			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);
}



?>
