<?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");}
if ($add2==1){$showcredits="";}else{$showcredits="display:none;";}
$id=-1;

if (isset($_GET["id"])){$id=intval($_GET["id"]);}


if ($id===-1){
	header("location:projects.php");
}

	
$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
    ]);


$blog_url="";

$fields = [];
for ($i = 1; $i <= 12; $i++) {
    $fields[] = "user_bloglink" . $i;
}
$sql = "SELECT " . implode(", ", $fields) . " FROM users WHERE user_id = :user_id";

$stmt = $db->prepare($sql);
$stmt->bindParam(':user_id', $userid, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);


$bloglinks = [];
$blog_urls = [];

if ($result) {
    for ($i = 1; $i <= 12; $i++) {
        $key = "user_bloglink" . $i;
        if (isset($result[$key])) {
            $bloglinks[$i] = base64_decode($result[$key]);
            $blog_urls[$i] = substr($bloglinks[$i], 16);
        }
    }
}



$blog_select = '<select name="blognumber" id="blognumber" class="form-control custom-select" style="width:200px; margin-right:5px; float:right;">';
$blog_select .= '<option selected="selected" disabled="true">Select Blog</option>';
foreach ($blog_urls as $index => $url) {
    if (!empty($url)) { 
        $blog_select .= "<option value='{$index}'>{$url}</option>";
    }
}
$blog_select .= '</select>';


$st = $db->prepare("SELECT cat_id,cat_name FROM categories WHERE cat_userid=:userid");
$st->bindParam(':userid', $userid);
$st->execute();
$user=[];
$results = $st->fetchAll();
$catout="";
if ($results){
	
	foreach ($results as $key => $value) {
		$catout.='<option value="'.$value["cat_id"].'">'.$value["cat_name"].'</option>';
	}
} else {
	$catout="";
}
$project_name="";
$audience="";
$tone=10;
$category=0;
$language=3;
$p1_input="";

$p1_content="";
$p2_content="";
$p3_content="";
$p4_content="";
$p5_content="";
$title="";
$imageprompt="";
$imagefile="";
$wordsperpost="";
$isposted=0;
$dateposted="";


if($id > 0){
	$query = $db->prepare("SELECT * FROM projects WHERE id = :id AND user_id = :user_id");
	$query->execute(['id' => $id, 'user_id' => $userid]);
	$result = $query->fetch(PDO::FETCH_ASSOC);
	if($result === false){
		header('Location: projects.php');
		exit();
	}
	extract($result);
}

$usercredits=1000000;
// Check for available credits if not editmode and credits system installed
if ($add2==1){
	$usercredits=0;
		try {
			$query = "SELECT user_credits FROM users WHERE user_id = :userid";
			$stmt = $db->prepare($query);
			$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
			$stmt->execute();
			$result = $stmt->fetch(PDO::FETCH_ASSOC);
			
			if ($result) {
				$usercredits = $result['user_credits'];
			} else {
				echo "No user found with the given user_id.";
			}

		} catch(PDOException $e) {
			echo "Error getting words left";
		}
		if ($usercredits<200) {
			header("location:projects.php?w=1");
		}
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
	<link rel="icon" type="image/x-icon" href="favicon.ico">
    <title><?php echo $sitename; ?></title>

    <!-- Custom fonts for this template -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" integrity="sha512-q3eWabyZPc1XTCmF+8/LuE1ozpg5xxn7iO89yfSOd5/oKvyqLngoNGsx8jq92Y8eXJ/IRxQbEC+FGSYxtk2oiw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
	
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
        rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="libs/sbadmin2/css/sb-admin-2.min.css" rel="stylesheet">

    <!-- Custom styles for this page -->
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.39.0/css/tempusdominus-bootstrap-4.min.css" integrity="sha512-3JRrEUwaCkFUBLK1N8HehwQgu8e23jTH4np5NHOmQOobuC4ROQxFwFgBLTnhcnQRMs84muMh0PnnwXlPq5MGjg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
	
	<style>
		.topgap {
			margin-top: 15px;
		}
		.topgap2 {
			margin-top: 20px;
		}
		#overlay {
			position: fixed;
			top: 0;
			left: 0;
			height: 100vh;
			width: 100vw;
			background-color: rgba(0, 0, 0, 0.6);
			display: none;
			align-items: center;
			justify-content: center;
			z-index: 9999;
		}

		#overlay.display-flex {
			display: flex;
		}

		#overlay-text {
			color: white;
			font-family:Nunito;
			font-size: 24px;
			pointer-events: none;
			user-select: none;
		}
		
		.nav-item .nav-link.active {
			background-color: #9f9f9f !important;
			color:#fff !important;
			font-weight:bold !important;
			border-bottom:0px !important;
			border-right:0px !important;
		}
		
		.link-text { color:#555 !important; }
		
		.tab-back { background-color:#f2f2f2; !important; border-right:1px solid #dfdfdf !important; }
		
		.card-flat-top { border-radius:0px 0px 5px 5px; !important; }
		
		#postButton .dropdown-menu .disabled {
			pointer-events: none;
			opacity: 0.65;  /* Optional: gives a visual indication of being disabled */
		}
		
		#postedmessage:hover, #postedmessage:focus {
			background-color: #717384 !important;
			border-color: #6b6d7d !important;
			color: #fff !important;
			box-shadow: none !important;
			opacity: 1 !important;
		}

		
	</style>	

</head>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

       <?php require_once("menu_sidenav.php"); ?>
        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Begin Page Content -->
                <div class="container-fluid" style="margin-top:50px;"	>

                    <!-- Page Heading -->
                    <h1 class="h3 mb-2 text-gray-800">Project Creation / Editing</h1>
                    <p class="mb-4">You can create and edit your projects here.</p>

                    <div class="card shadow mb-4" id="outerWrapper" style="display:none;">
                        <div class="card-header py-3">
							<span id="outerHeader">
							<?php 
								if ($isposted==1) {
									echo "<span id='postedmessage' class='btn btn-secondary' style='float:left; cursor:default; background-color: #717384; border-color: #6b6d7d; color:#fff;'>Posted to blog at $whichblog on $dateposted - You can't save or repost.</span>";
								}								
									
							?>
							</span>
							<input id="add2" style="display:none;" value="<?php echo($add2); ?>">
							<input id="project_id" style="display:none;" value="<?php echo($id); ?>">
							<input id="isposted" style="display:none;" value="<?php echo($isposted); ?>">
							<input id="tone_store" style="display:none;" value="<?php echo($tone); ?>">
							<input id="language_store" style="display:none;" value="<?php echo($language); ?>">
							<input id="category_store" style="display:none;" value="<?php echo($category); ?>">

							
							<textarea id="p1_content" style="display:none;" ><?php echo($p1_content); ?></textarea>
							<textarea id="p2_content" style="display:none;" ><?php echo($p2_content); ?></textarea>
							<textarea id="p3_content" style="display:none;" ><?php echo($p3_content); ?></textarea>
							<textarea id="p4_content" style="display:none;" ><?php echo($p4_content); ?></textarea>
							<textarea id="p5_content" style="display:none;" ><?php echo($p5_content); ?></textarea>
							
							<button id="saveProject" class="btn btn-primary btn-icon-split float-right" style="margin-right:5px;" <?php if ($id==0){echo 'disabled="disabled"';} ?>><span class="icon text-white-50"><i class="fas fa-save"></i></span><span class="text">Save All</span></button>

							<a href="projects.php" id="cancelButton" class="btn btn-danger btn-icon-split float-right" style="margin-right:5px;"><span class="icon text-white-50"><i class="fas fa-window-close"></i></span><span class="text">Cancel</span></a>
							<span class="float-left form-inline" style="<?php echo $showcredits; ?>">Credits Left:&nbsp;&nbsp;<div class="form-control fake-input" id="usercredits" readonly ><?php echo $usercredits; ?></div><input id="userid" type="text" style="display:none;" value="<?php echo $userid; ?>"></span>							
                        </div>
                        <div class="card-body">
							<input id="userid" style="display:none" value="<?php echo $userid; ?>">

							<div class="row">
								<div class="col-2">
									<label>Project Name</label>
									<input type="text" class="form-control validate" placeholder="Name (internal use - 50 chars)" maxlength="50" name="projectname" id="projectname" value="<?php echo $project_name; ?>">
									<label class="form-check-label text-danger" style="display:none;" for="projectname">You must provide a project name!</label>
								</div>
								<div class="col-2">
									<label>Target Audience</label>
									<input type="text" class="form-control validate" placeholder="(Optional)" maxlength="250" name="audience" id="audience" value="<?php echo $audience; ?>">
									<label class="form-check-label text-danger" style="display:none;" for="projectname">You must provide a target audience!</label>
								</div>
								<div class="col-2">
								<label>Max Words</label><br>
									<div class="input-group">
										<span class="input-group-prepend">
											<button type="button" class="btn btn-outline-secondary btn-number" data-type="minus" data-field="wordsperpost">
												<span class="fa fa-minus"></span>
											</button>
										</span>
										<input type="text" name="wordsperpost" id="wordsperpost" class="form-control input-number" value="<?php if ($wordsperpost==""){echo "500";}else{echo $wordsperpost;} ?>" min="300" max="2000">
										<span class="input-group-append">
											<button type="button" class="btn btn-outline-secondary btn-number" data-type="plus" data-field="wordsperpost">
												<span class="fa fa-plus"></span>
											</button>
										</span>
									</div>
								</div>								
								<div class="col-2">
									<label for="category">Category</label>
									<div class="input-group">
										<select name="category" id="category" class="form-control custom-select">
											<option value="0">No Category</option>
											<?php echo $catout; ?>
										</select>
										<div class="input-group-append">
											<button class="btn btn-outline-secondary addcatbutton" type="button" id=""><i class="fas fa-plus-circle"></i></button>
										</div>
									</div>
								</div>
								<div class="col-2">
									<label>Language</label><br>
									<select name="language" id="language" class="form-control custom-select" style="">
										<option value="1">Chinese</option>
										<option value="2">Dutch</option>
										<option value="3" selected="selected">English</option>
										<option value="4">French</option>
										<option value="5">German</option>
										<option value="6">Italian</option>
										<option value="7">Japanese</option>
										<option value="8">Korean</option>
										<option value="9">Portuguese</option>
										<option value="10">Russian</option>
										<option value="11">Spanish</option>
										<option value="12">Vietnamese</option>
									</select>
								</div>
								<div class="col-2">
									<label>Writing Tone</label>
									<select name="tone" id="tone" class="form-control custom-select" style="">
										<option value="1">Authoritative</option>
										<option value="2">Casual</option>
										<option value="3">Confident</option>
										<option value="4">Conversational</option>
										<option value="5">Educational</option>
										<option value="6">Empathetic</option>
										<option value="7">Encouraging</option>
										<option value="8">Enthusiastic</option>
										<option value="9">Friendly</option>
										<option value="10" selected="selected">Informative</option>
										<option value="11">Lighthearted</option>
										<option value="12">Optimistic</option>
										<option value="13">Persuasive</option>
										<option value="14">Professional</option>
										<option value="15">Straightforward</option>
										<option value="16">Technical</option>
									</select>
								</div>
							</div>
							
							<div class="row topgap">
								<div class="col-10">
									<label>Blog Post Subject</label>
									<div class="input-group mb-3">
										<input type="text" class="form-control validate" placeholder="Details of blog post" maxlength="" name="p1_input" id="p1_input" value="<?php echo $p1_input; ?>">
										<div class="input-group-append">
											<button class="btn btn-outline-secondary sendtoall" id="p1" type="button" style="display:none;"><i class="fas fa-share-alt"></i>&nbsp;&nbsp;Copy To All</button>
										</div>
									</div>
								</div>
								<div class="col-2">
									<label>&nbsp;</label><br>
									<button id="p1-generate" class="btn btn-success btn-icon-split float-right generate" style="margin-right:5px; <?php if($id>0){echo "display:none;";} ?>"><span class="icon text-white-50"><i class="fas fa-sync-alt"></i></span><span class="text">Generate</span></button>										
								</div>
								<input id="title_store" style="display:none;" value="<?php echo $title; ?>">
							</div>							

							<div id="titlearea" style="display:none;">  <!-- Start Title Area -->
							
								<div class="row topgap">
									<div class="col-12">
										<div class="alert alert-secondary">Please choose/edit a Blog Post Title and click the Next button of your choice</div>
									</div> 
								</div>
							
										<?php for ($i=0; $i<=9; $i++){
											echo '<div class="row topgap"><div class="col-6"><input type="text" class="form-control" style="background-color:white;" id="title'.$i.'" value=""></div><button data-id="title'.$i.'" class="btn  btn-success btn-icon-split chooseTitle" style=""><span class="icon text-white-50"><i class="fas fa-angle-double-right"></i></span><span class="text">Next</span></button></div>';
										} ?>
							
							</div>  <!-- End Title Area -->


							<div id="outputarea" style="<?php if($id==0){echo 'display:none;';} ?>">  <!-- Start Output Area -->
							
								<div class="row topgap">
									<div class="col-12">
										<ul class="nav nav-tabs">
										  <li class="nav-item tab-back" id="tab1">
											<a class="nav-link link-text active" href="#">Blog Post</a>
										  </li>
										  <li class="nav-item tab-back" id="tab2">
											<a class="nav-link link-text" href="#">FaceBook Post</a>
										  </li>
										  <li class="nav-item tab-back" id="tab3">
											<a class="nav-link link-text" href="#">TikTok Video</a>
										  </li>
										  <li class="nav-item tab-back" id="tab4">
											<a class="nav-link link-text" href="#">Tweet</a>
										  </li>
										  <li class="nav-item tab-back" id="tab5">
											<a class="nav-link link-text" href="#">Email</a>
										  </li>
										  <li class="nav-item tab-back" style="border-right:0px !important;" id="tab6">
											<a class="nav-link link-text" href="#">Image</a>
										  </li>										  
										</ul>
									</div>
								</div>

					
								
								<div id="panel_tab1" class="card card-flat-top" style="display:block;">
									<div class="card-body">

										<div class="row topgap">
											<div class="col-12">
												<div id="p1_editorarea"></div>
											</div>
										</div>
										<div class="row topgap">
											<div class="col-12">
												<div id="p1_docHtml" class="googoose-wrapper" style="display:none;"></div>
	
									
												<div id="postButton" class="btn-group float-right" style="margin-right:10px">
													<button type="button" class="btn btn-success btn-icon-split float-right"><span class="icon text-white-50"><i class="fab fa-wordpress"></i></span><span class="text">Post</span></button>
													<button type="button" class="btn btn-success dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button>
													<div class="dropdown-menu">
														<a class="dropdown-item publishbutton" data-id="draft" href="#">Draft</a>
														<a class="dropdown-item publishbutton" data-id="now" href="#">Publish Now</a>
														<a class="dropdown-item publishbutton" data-id="later" href="#">Publish Later</a>
													</div>
												</div>
												
												<select name="sendwithpost" id="sendwithpost" class="form-control custom-select" style="width:200px; margin-right:5px; float:right;">
													<option value="0" selected="selected">Don't Post Image</option>
													<option value="1" >Post Image</option>
												</select>												
												<?php echo $blog_select; ?>
												
												<div class="btn-group float-right" style="margin-right:10px">
													<button type="button" class="btn btn-primary btn-icon-split float-right"><span class="icon text-white-50"><i class="fas fa-file-export"></i></span><span class="text">Export</span></button>
													<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button>
													<div class="dropdown-menu">
														<a class="dropdown-item exportbutton" data-id="doc" data-section="p1" href="#">DOC File</a>
														<a class="dropdown-item exportbutton" data-id="txt" data-section="p1" href="#">Text File</a>
														<a class="dropdown-item exportbutton" data-id="pdf" data-section="p1" href="#">PDF File</a>
													</div>
												</div>
												<button id="p1" class="btn btn-info btn-icon-split float-right copybutton" style="margin-right:5px;"><span class="icon text-white-50"><i class="fas fa-copy"></i></span><span class="text">Copy</span></button>
											</div>
										</div>
			
									</div>
								</div>
								
								

								<div id="panel_tab2" class="card card-flat-top" style="display:none;">
									<div class="card-body">
										<div class="row topgap">
											<div class="col-12">
												<div id="p2_editorarea"></div>
											</div>
										</div>
										<div class="row topgap">
											<div class="col-12">
												<div id="p2_docHtml" class="googoose-wrapper" style="display:none;"></div>
											

												<div class="btn-group float-right" style="margin-right:10px">
													<button type="button" class="btn btn-primary btn-icon-split float-right"><span class="icon text-white-50"><i class="fas fa-file-export"></i></span><span class="text">Export</span></button>
													<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button>
													<div class="dropdown-menu">
														<a class="dropdown-item exportbutton" data-id="doc" data-section="p2" href="#">DOC File</a>
														<a class="dropdown-item exportbutton" data-id="txt" data-section="p2" href="#">Text File</a>
														<a class="dropdown-item exportbutton" data-id="pdf" data-section="p2" href="#">PDF File</a>
													</div>
												</div>
												<button id="p2" class="btn btn-info btn-icon-split float-right copybutton" style="margin-right:5px;"><span class="icon text-white-50"><i class="fas fa-copy"></i></span><span class="text">Copy</span></button>
											</div>
										</div>
									</div>
								</div>

								<div id="panel_tab3" class="card card-flat-top" style="display:none;">
									<div class="card-body">
									
										<div class="row topgap">
											<div class="col-12">
												<div id="p3_editorarea"></div>
											</div>
										</div>
										<div class="row topgap">
											<div class="col-12">
												<div id="p3_docHtml" class="googoose-wrapper" style="display:none;"></div>
											
												<div class="btn-group float-right" style="margin-right:10px">
													<button type="button" class="btn btn-primary btn-icon-split float-right"><span class="icon text-white-50"><i class="fas fa-file-export"></i></span><span class="text">Export</span></button>
													<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button>
													<div class="dropdown-menu">
														<a class="dropdown-item exportbutton" data-id="doc" data-section="p3" href="#">DOC File</a>
														<a class="dropdown-item exportbutton" data-id="txt" data-section="p3" href="#">Text File</a>
														<a class="dropdown-item exportbutton" data-id="pdf" data-section="p3" href="#">PDF File</a>
													</div>
												</div>
												<button id="p3" class="btn btn-info btn-icon-split float-right copybutton" style="margin-right:5px;"><span class="icon text-white-50"><i class="fas fa-copy"></i></span><span class="text">Copy</span></button>	
											</div>
										</div>
									</div>
								</div>

								<div id="panel_tab4" class="card card-flat-top" style="display:none;">
									<div class="card-body">
									
										<div class="row topgap">
											<div class="col-12">
												<div id="p4_editorarea"></div>
											</div>
										</div>
										<div class="row topgap">
											<div class="col-12">
												<div id="p4_docHtml" class="googoose-wrapper" style="display:none;"></div>
												<div class="btn-group float-right" style="margin-right:10px">
													<button type="button" class="btn btn-primary btn-icon-split float-right"><span class="icon text-white-50"><i class="fas fa-file-export"></i></span><span class="text">Export</span></button>
													<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button>
													<div class="dropdown-menu">
														<a class="dropdown-item exportbutton" data-id="doc" data-section="p4" href="#">DOC File</a>
														<a class="dropdown-item exportbutton" data-id="txt" data-section="p4" href="#">Text File</a>
														<a class="dropdown-item exportbutton" data-id="pdf" data-section="p4" href="#">PDF File</a>
													</div>
												</div>
												<button id="p4" class="btn btn-info btn-icon-split float-right copybutton" style="margin-right:5px;"><span class="icon text-white-50"><i class="fas fa-copy"></i></span><span class="text">Copy</span></button>																					
											</div>
										</div>
									</div>
								</div>
																													
								<div id="panel_tab5" class="card card-flat-top" style="display:none;">
									<div class="card-body">
									
										<div class="row topgap">
											<div class="col-12">
												<div id="p5_editorarea"></div>
											</div>
										</div>
										<div class="row topgap">
											<div class="col-12">
												<div id="p5_docHtml" class="googoose-wrapper" style="display:none;"></div>
												<div class="btn-group float-right" style="margin-right:10px">
													<button type="button" class="btn btn-primary btn-icon-split float-right"><span class="icon text-white-50"><i class="fas fa-file-export"></i></span><span class="text">Export</span></button>
													<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button>
													<div class="dropdown-menu">
														<a class="dropdown-item exportbutton" data-id="doc" data-section="p5" href="#">DOC File</a>
														<a class="dropdown-item exportbutton" data-id="txt" data-section="p5" href="#">Text File</a>
														<a class="dropdown-item exportbutton" data-id="pdf" data-section="p5" href="#">PDF File</a>
													</div>
												</div>
												<button id="p5" class="btn btn-info btn-icon-split float-right copybutton" style="margin-right:5px;"><span class="icon text-white-50"><i class="fas fa-copy"></i></span><span class="text">Copy</span></button>																					
											</div>
										</div>
									</div>
								</div>

								<div id="panel_tab6" class="card card-flat-top" style="display:none;">
									<div class="card-body">
										<div class="row topgap">
											<div class="col-6">
												<label>Suggested Image Description</label>
													<input type="text" class="form-control validate" placeholder="" maxlength="" name="imageprompt" id="imageprompt" value="<?php echo $imageprompt; ?>">
											</div>
											<div class="col-1">
												<label>Prompt Type</label><br>
												<select name="promptmode" id="promptmode" class="form-control custom-select" style="">
													<option value="0" selected="selected">Custom</option>
													<option value="1" >Photographic</option>
													<option value="2" >Cyberpunk Neon Illustration</option>
													<option value="3" >Cyberpunk Neon Photorealistic</option>
													<option value="4" >Cartoon</option>
													<option value="5" >Illustration</option>
													<option value="6" >Pencil Sketch</option>
													<option value="7" >Simple Watercolor</option>
													<option value="8" >Detailed Watercolor</option>
													<option value="9" >Tilt Shift</option>
													<option value="10" >Retail Photography</option>
													<option value="11" >Sci Fi</option>
													<option value="12" >Play Clay</option>
													<option value="13" >Graphic Novel</option>
													<option value="14" >Comic Book</option>
													<option value="15" >Ink Line Art</option>
													<option value="16" >Food Photography</option>
													<option value="17" >Impressionist Painting</option>
													<option value="18" >Street Photography</option>
													<option value="19" >Childrens Book Illustration</option>
													<option value="20" >Technical Illustration</option>
													
												</select>
											</div>											
											<div class="col-3">
												<label>&nbsp;</label><br>
												<button id="downloadimage" class="btn btn-info btn-icon-split float-left" style="margin-right:5px; <?php if($imagefile==""){echo 'display:none; ';} ?>"><span class="icon text-white-50"><i class="fas fa-file-download"></i></span><span class="text">Download</span></button>
												<button id="image-generate" class="btn btn-success btn-icon-split float-right" style="margin-right:5px;"><span class="icon text-white-50"><i class="fas fa-sync-alt"></i></span><span class="text">Generate Image</span></button>
											</div>
											<input id="filename_store" style="display:none;" value="<?php echo $imagefile; ?>">
										</div>	
										<div class="row topgap">
											<div class="col-12">
												<div id="imagearea" style="text-align:center; <?php if($id==0 || $imagefile==""){echo 'display:none;';} ?>"><img id="imagepreview" src='<?php echo ("image_store/".$userid."/".$imagefile); ?>'></div>
											</div>
										</div>
									</div>
								</div>									

							</div> <!-- End Output Area -->
							
                        </div>
                    </div>

                </div>
                <!-- /.container-fluid -->

            </div>
            <!-- End of Main Content -->

            <!-- Footer -->
            <footer class="sticky-footer bg-white">
                <div class="container my-auto">
                    <div class="copyright text-center my-auto">
                        <?php echo $footer; ?>
                    </div>
                </div>
            </footer>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- AI Error Modal -->
    <div class="modal fade" id="s2errorModal" tabindex="-1" role="dialog" aria-labelledby="s2ErrorLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="s2ErrorLabel">AI Error</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">There has been a problem connecting to the AI. This could be because the service is currently too busy.  Please try again.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">OK</button>
                </div>
            </div>
        </div>
    </div>

	<!-- Date Picker Modal -->
    <div class="modal fade" id="datepickerModal" tabindex="-1" role="dialog" aria-labelledby="datepickerLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userkeyLabel">Choose a date to publish</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
					<div class="container">
						<div class="row">
							<div class="col-12">
								<div class="form-group">
									<div class="input-group date" id="datetimepicker1" data-target-input="nearest">
										<input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1" />
										<div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
											<div class="input-group-text"><i class="fa fa-calendar"></i></div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>				
				</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-icon-split" data-dismiss="modal"><span class="icon text-white-50"><i class="fas fa-window-close"></i></span><span class="text">Cancel</span></button>
					<button type="button" class="btn btn-primary btn-icon-split" onclick="postBlog('later');" data-dismiss="modal"><span class="icon text-white-50"><i class="fab fa-wordpress"></i></span><span class="text">Post</span></button>
                </div>
            </div>
        </div>
    </div>	
	
	<!-- API Key Error Modal -->
    <div class="modal fade" id="userkeyModal" tabindex="-1" role="dialog" aria-labelledby="userkeyLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userkeyLabel">API Key Error</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">There has been a problem connecting to the AI. Your OpenAI API key is either missing or invalid - Please set it correctly in your Settings dashboard.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">OK</button>
                </div>
            </div>
        </div>
    </div>	

	<!-- Add Category Modal -->
    <div class="modal fade" id="addcatModal" tabindex="-1" role="dialog" aria-labelledby="addcatLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addcatLabel">Add New Category</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
					<div class="row">
						<div class="col-12">
							<label>New Category</label>
							<input type="text" class="form-control" placeholder="New Category" maxlength="50" name="addcat" id="addcat" value="">
						</div>
					</div>
				</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-icon-split" data-dismiss="modal"><span class="icon text-white-50"><i class="fas fa-window-close"></i></span><span class="text">Cancel</span></button>
					<button type="button" class="btn btn-primary btn-icon-split" onclick="addNewCat();" data-dismiss="modal"><span class="icon text-white-50"><i class="fas fa-plus-circle"></i></span><span class="text">Add Category</span></button>
                </div>
            </div>
        </div>
    </div>	


	<div class="toast bg-gray-400" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000" style="position: absolute; top: 1rem; right: 1rem;" id="generalToast">
	  <div class="toast-header bg-gray-700">
		<strong class="mr-auto"><span id="generalToastHeader" style="color:#FFF;"></span></strong>
		<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
		  <span aria-hidden="true" style="color:#FFF;">&times;</span>
		</button>
	  </div>
	  <div class="toast-body">
		<span id="generalToastBody" style="color:#000"></span>
	 </div>
	</div>

    <!-- Bootstrap core JavaScript-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.2/js/bootstrap.bundle.min.js" integrity="sha512-igl8WEUuas9k5dtnhKqyyld6TzzRjvMqLC79jkgT3z02FvJyHAuUtyemm/P/jYSne1xwFI06ezQxEwweaiV7VA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <!-- Core plugin JavaScript-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js" integrity="sha512-0QbL0ph8Tc8g5bLhfVzSqxe9GERORsKhIn1IrpxDAgUsbBGz/V7iSav2zzW325XGd1OMLdL4UiqRJj702IeqnQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <!-- Custom scripts for all pages-->
    <script src="libs/sbadmin2/js/sb-admin-2.min.js"></script>

	<!-- Page level plugins -->
	<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/aadel112/googoose@master/jquery.googoose.js"></script>

	<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.4.2/tinymce.min.js" integrity="sha512-sWydClczl0KPyMWlARx1JaxJo2upoMYb9oh5IHwudGfICJ/8qaCyqhNTP5aa9Xx0aCRBwh71eZchgz0a4unoyQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
	
	<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment-with-locales.min.js" integrity="sha512-42PE0rd+wZ2hNXftlM78BSehIGzezNeQuzihiBCvUEB3CVxHvsShF86wBWwQORNxNINlBPuq7rG4WWhNiTVHFg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
	
	<script src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.39.0/js/tempusdominus-bootstrap-4.min.js" integrity="sha512-k6/Bkb8Fxf/c1Tkyl39yJwcOZ1P4cRrJu77p83zJjN2Z55prbFHxPs9vN7q3l3+tSMGPDdoH51AEU8Vgo1cgAA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script>

function getCount(editorId){
    let theEditor = tinymce.get(editorId);
    if (theEditor) {
        let wordCount = theEditor.plugins.wordcount.getCount();
		return wordCount;
    } else {
        alert('Editor not found.');
    }
}


function postBlog(postmode){
	var projectid=$('#project_id').val();
	if (projectid==0){
		generalToast('ERROR!','You must save your project before you can post.');
	} else {
		var postdate="";
		if (postmode=='later'){
			postdate = $('.datetimepicker-input').val();
		}
		var imagefilename=$('#filename_store').val();
		var title=$('#title_store').val();
		var sendwithpost=$('#sendwithpost').val();
		var grabdoc1 = tinymce.get("p1_editorarea").getContent();
		var whichblog = $('#blognumber').val();
		if (whichblog==null){
			generalToast('ERROR!','You must select which blog to post to!');
		} else {
			grabdoc1=encodeURIComponent(grabdoc1);
			$.ajax({
				url: 'AJAX_blogpost.php',
				data:{postmode:postmode, postdate:postdate, imagefilename:imagefilename, title:title, p1_content: btoa(unescape(encodeURIComponent(grabdoc1))), sendwithpost:sendwithpost, projectid:projectid, whichblog:whichblog},
				type: 'POST',
				success: function (response) {
					if (response.substring(0, 5) !== "ERROR") {
						var whichblog=$('#blognumber option:selected').text();
						generalToast('Success!', 'Posted to blog at '+whichblog);
						$('#image-generate').hide();
						$('#filename_store').val('');
						$('#imageprompt').val('');
						$('#imagearea').hide();
						var $group = $('#postButton');
						$group.find('button').prop('disabled', true);
						$group.find('a').addClass('disabled').on('click', function(e) {
							e.preventDefault();
						});
						$('#blognumber').prop('disabled',true);
						$('#sendwithpost').prop('disabled',true);
						$('#tab6').hide();
						$('#saveProject').prop('disabled',true);
						$('#outerHeader').html("<span id='postedmessage' class='btn btn-secondary' style='float:left; cursor:default; background-color: #717384; border-color: #6b6d7d; color:#fff;'>Posted to blog at "+whichblog+" recently - You can't save or repost.</span>");
						for (var i = 1; i <= 5; i++) {
							var editorId = 'p' + i + '_editorarea';
							var editor = tinymce.get(editorId);
							if (editor) { 
								editor.mode.set('readonly'); 
							}
						}

					} else {
						generalToast('ERROR!','Could not post to blog! '+response);
					}
				}
			});
		}
	}
}

$('.publishbutton').click(function(){
	let whichbutton=$(this).data('id');
	if (whichbutton=='later') {
		$('#datepickerModal').modal('show');
	} else {
		postBlog(whichbutton);
	} 
});

$('#image-generate').click(function(){
	if($('#usercredits').text()<1000){
		generalToast('Cannot Proceed','Sorry you do not have enough credits left. Each image costs 1000 credits.');
	} else {	
		var imageprompt=$('#imageprompt').val();
		var imagefilename=$('#filename_store').val();
		var promptmode=$('#promptmode').val();
		var project_id=$('#project_id').val();
		
		$('#overlay-message').text('Asking AI to generate Image - Please wait...');
		showOverlay(true);
		$.ajax({
				url: "AJAX_getimage.php",
				data: {imageprompt:imageprompt,imagefilename:imagefilename,promptmode:promptmode,project_id:project_id},
				type: 'POST',
				success: function (response) {
					if (response!="ERROR"){
						if (response.substring(0, 5) === "image") {
							var data=response;
							$('#filename_store').val(data);
							$('#imagearea').show();
							var userid=$('#userid').val();
							var pathArray = window.location.pathname.split('/');
							pathArray.pop();
							var pathWithoutFilename = pathArray.join('/');
							var imageURL = pathWithoutFilename+'/image_store/'+userid+'/'+data;
							$('#imagepreview').attr('src',imageURL+'?t=' + new Date().getTime());
							$('#downloadimage').show();
							var add2=$('#add2').val();
							if (add2==1){
								$.ajax({
									url: "AJAX_creditchange.php",
									type: "POST",
									data: { wordCount: 1000 },
									success: function(response){
										$('#usercredits').text(response);
									},
									error: function(error){
										console.log("Error:", error);
									}
								});
							}								
						}
						showOverlay(false);
					} else {
						showOverlay(false);
						generalToast('ERROR!','Could Not Generate Image!');
					}
				}
			});			
	}
});
$('.btn-number').click(function(e) {
    e.preventDefault();
    fieldName = $(this).attr('data-field');
    type = $(this).attr('data-type');
    var input = $("input[name='" + fieldName + "']");
    var currentVal = parseInt(input.val());
    if (!isNaN(currentVal)) {
        if (type == 'minus') {
            if (currentVal > input.attr('min')) {
                input.val(currentVal - 1).change();
            }
            if (parseInt(input.val()) == input.attr('min')) {
                $(this).attr('disabled', true);
            }

        } else if (type == 'plus') {

            if (currentVal < input.attr('max')) {
                input.val(currentVal + 1).change();
            }
            if (parseInt(input.val()) == input.attr('max')) {
                $(this).attr('disabled', true); 
            }

        }
    } else {
        input.val(0);
    }
});

$('.input-number').focusin(function() {
    $(this).data('oldValue', $(this).val());
});
$('.input-number').change(function() {
	
    minValue = parseInt($(this).attr('min'));
    maxValue = parseInt($(this).attr('max'));
    valueCurrent = parseInt($(this).val());

    name = $(this).attr('name');
    if (valueCurrent >= minValue) {
        $(".btn-number[data-type='minus'][data-field='" + name + "']").removeAttr('disabled')
    } else {
        $(this).val($(this).data('oldValue'));
    }
    if (valueCurrent <= maxValue) {
        $(".btn-number[data-type='plus'][data-field='" + name + "']").removeAttr('disabled')
    } else {
        $(this).val($(this).data('oldValue'));
    }
});

$(".input-number").keydown(function(e) {
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
        (e.keyCode == 65 && e.ctrlKey === true) ||
        (e.keyCode >= 35 && e.keyCode <= 39)) {
        return;
    }
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
});

$('.sendtoall').click(function(){
	var id=this.id;
	var sendtext=$('#'+id+'_input').val();
	$('#p1_input,#p2_input,#p3_input,#p4_input').val(sendtext);
	generalToast('Success!','This has been copied to all relevant fields.');
});

$('.generate').click(async function(){
	if(enoughCredits()==false){
		generalToast('Cannot Proceed','Sorry you do not have enough credits left.');
	} else {	
		$('#p1-generate').hide();
		await callAi('p1','none');
	}
});

$('.chooseTitle').click(async function(){
	$('#saveProject').prop('disabled',false);
	var title=$('#'+$(this).data('id')).val();
	$('#title_store').val(title);
	$('#imageprompt').val(title);
	await callAi('p2',title); // Blog Post
	await callAi('p3',title); // FB Post
	await callAi('p4',title); // TikTok
	await callAi('p5',title); // Tweet
	await callAi('p6',title); // Email
	var wordCount=getCount('p1_editorarea');
	wordCount+=getCount('p2_editorarea');
	wordCount+=getCount('p3_editorarea');
	wordCount+=getCount('p4_editorarea');
	wordCount+=getCount('p5_editorarea');
		
	var add2=$('#add2').val();
	if (add2==1){
		$.ajax({
			url: "AJAX_creditchange.php",
			type: "POST",
			data: { wordCount: wordCount },
			success: function(response){
				$('#usercredits').text(response);
			},
			error: function(error){
				console.log("Error:", error);
			}
		});
	}	
});

$('.copybutton').click(function() {
	var id=this.id;
	var editor = tinymce.get(id+'_editorarea');
	editor.execCommand('selectAll', true, 'texteditor');
	editor.execCommand( "Copy" );
	editor.selection.collapse();
	generalToast('Success!','The content has been copied to your clipboard.');
});


function callAi(panel_id,title){
	return new Promise((resolve, reject) => {	
		var wordsperpost=$('#wordsperpost').val();
		var panel_input=$('#p1_input').val();
		var language=$('#language').val();
		var tone=$('#tone').val();
		var audience=$('#audience').val();
		var mode=panel_id;
		panel_input=panel_input.trim();
		if (panel_input!==""){
			var data = {
			  language: language,
			  tone: tone,
			  audience: audience,
			  panel_input: panel_input,
			  mode: mode,
			  wordsperpost: wordsperpost,
			  title: title
			};
			showOverlay(true);
			switch(panel_id){
				case 'p1':
					$('#overlay-message').text('Asking AI to generate Post Titles - Please wait...');	
					break;
				case 'p2':
					$('#overlay-message').text('Asking AI to generate Blog Post - Please wait...');		
					break;
				case 'p3':
					$('#overlay-message').text('Asking AI to generate Facebook Post - Please wait...');		
					break;
				case 'p4':
					$('#overlay-message').text('Asking AI to generate TikTok Script - Please wait...');		
					break;
				case 'p5':
					$('#overlay-message').text('Asking AI to generate a Tweet - Please wait...');		
					break;
				case 'p6':
					$('#overlay-message').text('Asking AI to generate an Email - Please wait...');		
					break;
			}
			
			$.ajax({
			  url: 'AJAX_aiengine.php',
			  type: 'POST',
			  data: data,
			  success: function(response) {

				let errortest;

				try {
				  errortest = JSON.parse(response);
				} catch (error) {
				  console.error("The response is not valid JSON");
					console.log("ERROR WITH AJAX CALL 1!!");
					showOverlay(false);
					$('#s2errorModal').modal('show');				  
				  errortest=response;
				}
				if (errortest=="NOUSERKEY") {
					console.log("ERROR WITH AJAX CALL 2!!");
					showOverlay(false);
					$('#userkeyModal').modal('show');	
				} else {
					
					if (panel_id=='p1'){
						showOverlay(false);
						$('#titlearea').show();
						var airesp = JSON.parse(response);
						var content = airesp.choices[0].message.content;
						var content = content.replace(/\n/g, '');
						content=content.replaceAll("<\/","<");
						content = content.replaceAll('<\\', '<');
						content = content.replaceAll('</', '<');
						//content = content.replaceAll(/["']/g, "");
						const contentarray = content.split("|").map(item => item.trim());
						for (let i = 0; i < 10; i++) {
							$('#title'+i).val(contentarray[i]);
						}
					}
					
					if (panel_id=='p2'){
						
						var airesp = JSON.parse(response);
						var content = airesp.choices[0].message.content;
						var content = content.replace(/\n/g, '<br>');
						//content = content.replaceAll(/["']/g, "");
									
						let parts = content.split('<br><br>');
						for(let i = 0; i < parts.length; i++) {
							parts[i] = '<p>' + parts[i] + '</p>';
						}
						let newText = parts.join('');	
						var editor = tinymce.get('p1_editorarea');
						editor.setContent(newText);
						
					}
					
					if (panel_id=='p3'){
						
						var airesp = JSON.parse(response);
						var content = airesp.choices[0].message.content;
						var content = content.replace(/\n/g, '<br>');
						//content = content.replaceAll(/["']/g, "");
									
						let parts = content.split('<br><br>');
						for(let i = 0; i < parts.length; i++) {
							parts[i] = '<p>' + parts[i] + '</p>';
						}
						let newText = parts.join('');	
						var editor = tinymce.get('p2_editorarea');
						editor.setContent(newText);						

					}
					
					if (panel_id=='p4'){
						
						var airesp = JSON.parse(response);
						var content = airesp.choices[0].message.content;
						var content = content.replace(/\n/g, '<br>');
						//content = content.replaceAll(/["']/g, "");
									
						let parts = content.split('<br><br>');
						for(let i = 0; i < parts.length; i++) {
							parts[i] = '<p>' + parts[i] + '</p>';
						}
						let newText = parts.join('');	
						var editor = tinymce.get('p3_editorarea');
						editor.setContent(newText);						
						
					}
					
					if (panel_id=='p5'){
						
						var airesp = JSON.parse(response);
						var content = airesp.choices[0].message.content;
						var content = content.replace(/\n/g, '<br>');
						//content = content.replaceAll(/["']/g, "");
									
						let parts = content.split('<br><br>');
						for(let i = 0; i < parts.length; i++) {
							parts[i] = '<p>' + parts[i] + '</p>';
						}
						let newText = parts.join('');	
						var editor = tinymce.get('p4_editorarea');
						editor.setContent(newText);						

					}

					if (panel_id=='p6'){
						
						var airesp = JSON.parse(response);
						var content = airesp.choices[0].message.content;
						var content = content.replace(/\n/g, '<br>');
						//content = content.replaceAll(/["']/g, "");
									
						let parts = content.split('<br><br>');
						for(let i = 0; i < parts.length; i++) {
							parts[i] = '<p>' + parts[i] + '</p>';
						}
						let newText = parts.join('');	
						var editor = tinymce.get('p5_editorarea');
						editor.setContent(newText);						
						
						
						$('#titlearea').hide();
						$('#outputarea').show();
						showOverlay(false);
					}				
			
				}
				resolve();
			  },
			  error: function(xhr, status, error) {
					showOverlay(false);
					$('#s2errorModal').modal('show');
					resolve();
			  }
			});		
			

		} else {
			var input_field='No Field';
			switch(panel_id){
				case 'p1':
					input_field='Campaign Details';
					break;
				case 'p2':
					input_field='Topic';
					break;
				case 'p3':
					input_field='Tiktok Script';
					break;
				case 'p4':
					input_field='Product Details';
					break;
			}
			generalToast('ERROR: Field is empty!','The '+input_field+' field must NOT be empty!');
		}
		
	});
}


function generalToast(header,body){
			$('#generalToastHeader').text(header);
			$('#generalToastBody').text(body);
			$('#generalToast').toast('show');
}

$('.addcatbutton').click(function(){
	$('#addcatModal').modal('show');
});

function addNewCat(whichsection){
	var newcat=$('#addcat').val().trim();
	if (newcat!=""){
		$('#addcat').val('');
		$.ajax({
			url: "AJAX_addnewcat.php",
			data: {newcatname:newcat},
			type: 'POST',
			success: function (response) {
				if (response!="ERROR"){
					$('#tablediv').show();
					var data = JSON.parse(response);
					var catId = data.cat_id;
					var catName = data.cat_name;
					var option = new Option(catName, catId);
					$('#category,#categoryEdit').append(option);
					$('#category,#categoryEdit').val(catId);
					$('#category,#categoryEdit').change();
					generalToast('Category Added','This Category has been added');
					
					$('#categoryEdit').change();					
				} else {
					generalToast('ERROR!','This Category has NOT been added');
				}
			}
		});
	}
	
}

function b64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    var byteCharacters = atob(b64Data);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }

    var blob = new Blob(byteArrays, {type: contentType});
    return blob;
}

$('#saveProject').click(function(){
	var projectname=$('#projectname').val();
	projectname=projectname.trim();
	if (projectname===''){
		generalToast("ERROR!","You MUST enter a Project Name");
	} else {
		var grabdoc1 = '<style>p { color: black; font-size: 12pt; font-family: Verdana; }</style>'+tinymce.get("p1_editorarea").getContent();
		var grabdoc2 = '<style>p { color: black; font-size: 12pt; font-family: Verdana; }</style>'+tinymce.get("p2_editorarea").getContent();
		var grabdoc3 = '<style>p { color: black; font-size: 12pt; font-family: Verdana; }</style>'+tinymce.get("p3_editorarea").getContent();
		var grabdoc4 = '<style>p { color: black; font-size: 12pt; font-family: Verdana; }</style>'+tinymce.get("p4_editorarea").getContent();
		var grabdoc5 = '<style>p { color: black; font-size: 12pt; font-family: Verdana; }</style>'+tinymce.get("p5_editorarea").getContent();
		
		var p1_input = $('#p1_input').val();
				
		var audience = $('#audience').val();
		var language = $('#language').val();
		var tone=$('#tone').val();
		var category=$('#category').val();
		var project_id=$('#project_id').val();
		var projectname=$('#projectname').val();
		var imageprompt=$('#imageprompt').val();
		var imagefile=$('#filename_store').val();
		var title=$('#title_store').val();
		var wordsperpost=$('#wordsperpost').val();
		
		var promptmode=$('#promptmode').val();
		var promptstrict=7;
		
		grabdoc1=encodeURIComponent(grabdoc1);
		grabdoc2=encodeURIComponent(grabdoc2);
		grabdoc3=encodeURIComponent(grabdoc3);
		grabdoc4=encodeURIComponent(grabdoc4);
		grabdoc5=encodeURIComponent(grabdoc5);
		
		var data = {
		  projectname: projectname,
		  p1_content: btoa(unescape(encodeURIComponent(grabdoc1))),
		  p2_content: btoa(unescape(encodeURIComponent(grabdoc2))),
		  p3_content: btoa(unescape(encodeURIComponent(grabdoc3))),
		  p4_content: btoa(unescape(encodeURIComponent(grabdoc4))),
		  p5_content: btoa(unescape(encodeURIComponent(grabdoc5))),
		  category: category,
		  id: project_id,
		  p1_input: p1_input,
		  audience: audience,
		  language: language,
		  tone: tone,
		  imageprompt: imageprompt,
		  imagefile: imagefile,
		  title: title,
		  wordsperpost: wordsperpost,
		  promptmode: promptmode,
		  promptstrict: promptstrict
		};	
		
		$('#saveProject').html('<span class="icon text-white-50"><i class="fas fa-sync-alt fa-spin"></i></span><span class="text">Saving</span>').prop('disabled',true);
			
		$.ajax({
		  url: 'AJAX_save.php',
		  type: 'POST',
		  data: data,
		  success: function(response) {
			$('#saveProject').html('<span class="icon text-white-50"><i class="fas fa-save"></i></span><span class="text">Save All</span>').prop('disabled',false);
			generalToast('Project Saved!','Your project has been saved.');
			$('#project_id').val(response);
		  },
		  error: function(xhr, status, error) {
				console.log("ERROR WITH SAVE");
		  }
		});	
	}
});



$('.exportbutton').click(function(){
	let whichbutton=$(this).data('id');
	let panel=$(this).data('section');
	var grabdoc = tinymce.get(panel+"_editorarea").getContent();
	$('#'+panel+'_docHtml').html('<style>p { color: black; font-size: 12pt; font-family: Verdana; }</style>'+grabdoc);
	var filename=$('#projectname').val();
	if(filename==''){filename='myfile';}
	
	var filenameModifier='';
	var panelModifiers = {
		"p1": "-BLOGPOST",
		"p2": "-FACEBOOK",
		"p3": "-TIKTOK",
		"p4": "-TWEET",
		"p5": "-EMAIL"
	};



	var filenameModifier = panelModifiers[panel];
	
	filename = filename.replace(/\W+/g, " ");
	filename = filename.replace(/\s+/g, "-");
	filename = filename+filenameModifier;
	
	switch(whichbutton){
		case "txt":
			var grabtext = tinymce.get(panel+"_editorarea").getContent({ format: "text" });
			var blob = new Blob([grabtext], {type: "text/plain"});
			var url = URL.createObjectURL(blob);
			var a = document.createElement('a');
			a.href = url;
			a.download = filename+'.txt';
			document.body.appendChild(a);
			a.click();
			document.body.removeChild(a);
			generalToast('Text File Created','Text File Created : '+filename+'.txt');
		break;
		
		case "doc":
			var o = {
				filename: filename+'.doc'
			};
			$('#'+panel+'_docHtml').show();
			$(document).googoose(o);
			$('#'+panel+'_docHtml').hide();
			generalToast('Doc File Created','DOC File Created : '+filename+'.doc');
		break;
		
		case "pdf":
			grabdoc = grabdoc.replace(/[\u{1f300}-\u{1f5ff}\u{1f600}-\u{1f64f}\u{1f680}-\u{1f6ff}\u{1f900}-\u{1f9ff}]/gu, '');
			grabdoc='<style>p { color: black; font-size: 12pt; font-family: Verdana; } img { max-width:100%; height:auto; }</style>'+grabdoc;
			
			$.ajax({
				url: 'AJAX_dopdf.php',
				type: 'POST',
				data: { 
					content: encodeURIComponent(grabdoc)
				},
				 success: function(response) {
						var blob = b64toBlob(response, "application/pdf");
						var blobUrl = URL.createObjectURL(blob);

						var link = $('<a>');
						link.attr('href', blobUrl);
						link.attr('download', filename+'.pdf');

						$('body').append(link);
						link[0].click();
						link.remove();
					},
					error: function(xhr, status, error) {

						console.log("Error Creating PDF");
					}
			});	
			generalToast('PDF File Created','PDF File Created : '+filename+'.pdf');
		break;
		
	}
	
});

function getResponseAI(language, tone, panel_input, mode){
    return new Promise((resolve, reject) => {
        $('#overlay-message').html('Asking AI to generate content. Please wait...');
        showOverlay(true);
		var data = {
		  language: language,
		  tone: tone,
		  panel_input: panel_input,
		  mode: mode
		};
        $.ajax({
            url: 'AJAX_aiengine.php',
            type: 'POST',
            data: data,
			cache: false,
            success: function(response) {
				
				try {
				  errortest = JSON.parse(response);
				} catch (error) {
					console.error("The response is not valid JSON in getResponseAI"); 
					
					showOverlay(false);
					$('#s2errorModal').modal('show');					  
				    errortest=response;
				}
				if (errortest.error){
					console.log("ERROR WITH AJAX CALL CHAPTER - errortest!!");
					
					showOverlay(false);
					$('#s2errorModal').modal('show');				
				} else {
					showOverlay(false);
					var airesp = JSON.parse(response);
					
					var content = airesp.choices[0].message.content;
					
					var content = content.replace(/\n/g, '<br>');
					var content = content.replaceAll('(To be continued...)', '');
					var content = content.replaceAll('To be continued', '');
					var content = content.replaceAll('TO BE CONTINUED', '');
					
					var content = content.replace(/\[.*?\]/g, '');
						
					resolve (content);
				}
            },
            error: function(xhr, status, error) {
                //console.error(error);
                showOverlay(false);
                $('#s2errorModal').modal('show');
                reject(error); // Reject the Promise with the error
            }
        });
    });
}

function showOverlay(show) {
    if(show) {
        $('#overlay').addClass('display-flex');
    } else {
        $('#overlay').removeClass('display-flex');
    }
}

$(document).ready(function() {
	

	
	$.fn.datetimepicker.Constructor.Default = $.extend({}, $.fn.datetimepicker.Constructor.Default, { icons: { time: 'fas fa-clock', date: 'fas fa-calendar', up: 'fas fa-arrow-up', down: 'fas fa-arrow-down', previous: 'fas fa-chevron-left', next: 'fas fa-chevron-right', today: 'fas fa-calendar-check', clear: 'fas fa-trash', close: 'fas fa-times' },		format: 'Y-MM-DD HH:mm:ss' });
	
	$('#datetimepicker1').datetimepicker();

	
	$("#downloadimage").click(function() {
		var imagefilename=$('#filename_store').val();
		if (imagefilename!=""){
			var imageUrl = $("#imagepreview").attr("src");
			var downloadLink = $('<a></a>')
				.attr('href', imageUrl)
				.attr('download', imagefilename) // The file name for the downloaded image
				.appendTo('body');
			downloadLink[0].click();
			downloadLink.remove();
		}
    });
	
	$(".nav-item").click(function() {
	    $('.nav-item .nav-link').removeClass('active');
    	$(this).find('.nav-link').addClass('active');
		var tab=this.id;

		$('#panel_tab1,#panel_tab2,#panel_tab3,#panel_tab4,#panel_tab5,#panel_tab6').hide();
		
		$('#panel_'+tab).show();
	});	
	
	var p1_content=$('#p1_content').val();
	var p2_content=$('#p2_content').val();
	var p3_content=$('#p3_content').val();
	var p4_content=$('#p4_content').val();
	var p5_content=$('#p5_content').val();
	
	
	$('#category').val($('#category_store').val());
	$('#tone').val($('#tone_store').val());
	$('#language').val($('#language_store').val());
	
	$('#outerWrapper').show();
	
	tinymce.init({
		selector: '#p1_editorarea',
		promotion: false,
		branding: false,
		inline_styles : true,
		content_style: "p { color: black; font-size: 12pt; font-family: Verdana; margin: 1rem auto; max-width: 1400px; }",	
		toolbar: "aligncenter alignjustify alignleft alignnone alignright| blockquote styles | image | link | bold italic underline strikethrough | copy | cut | fontfamily fontsize backcolor forecolor hr indent | language | lineheight | newdocument | outdent | paste pastetext | redo | selectall | searchreplace | subscript superscript | undo | fullscreen | code",
		plugins: "link, image, wordcount, fullscreen, code, searchreplace, emoticons",	 
		setup: function (editor1) {
		  editor1.on('init', function (e) {
			editor1.setContent(p1_content);
		  });
		}
	});	
		
	tinymce.init({
		selector: '#p2_editorarea',
		promotion: false,
		branding: false,
		inline_styles : true,
		content_style: "p { color: black; font-size: 12pt; font-family: Verdana; margin: 1rem auto; max-width: 1400px; }",	
		toolbar: "aligncenter alignjustify alignleft alignnone alignright| anchor | blockquote styles | bold italic underline strikethrough | emoticons | copy | cut | fontfamily fontsize backcolor forecolor hr indent | language | lineheight | newdocument | outdent | paste pastetext | redo | selectall | searchreplace | subscript superscript | undo | fullscreen",
		plugins: "wordcount, fullscreen, searchreplace, emoticons",	  
		setup: function (editor2) {
		  editor2.on('init', function (e) {
			editor2.setContent(p2_content);
		  });
		}
	});

	tinymce.init({
		selector: '#p3_editorarea',
		promotion: false,
		branding: false,
		inline_styles : true,
		content_style: "p { color: black; font-size: 12pt; font-family: Verdana; margin: 1rem auto; max-width: 1400px; }",	
		toolbar: "aligncenter alignjustify alignleft alignnone alignright| anchor | blockquote styles | bold italic underline strikethrough | emoticons | copy | cut | fontfamily fontsize backcolor forecolor hr indent | language | lineheight | newdocument | outdent | paste pastetext | redo | selectall | searchreplace | subscript superscript | undo | fullscreen",
		plugins: "wordcount, fullscreen, searchreplace, emoticons",	  
		setup: function (editor3) {
		  editor3.on('init', function (e) {
			editor3.setContent(p3_content);
		  });
		}
	});
		
	tinymce.init({
		selector: '#p4_editorarea',
		promotion: false,
		branding: false,
		inline_styles : true,
		content_style: "p { color: black; font-size: 12pt; font-family: Verdana; margin: 1rem auto; max-width: 1400px; }",	
		toolbar: "aligncenter alignjustify alignleft alignnone alignright| anchor | blockquote styles | bold italic underline strikethrough | emoticons | copy | cut | fontfamily fontsize backcolor forecolor hr indent | language | lineheight | newdocument | outdent | paste pastetext | redo | selectall | searchreplace | subscript superscript | undo | fullscreen",
		plugins: "wordcount, fullscreen, searchreplace, emoticons",	  
		setup: function (editor4) {
		  editor4.on('init', function (e) {
			editor4.setContent(p4_content);
		  });
		}
	});

	tinymce.init({
		selector: '#p5_editorarea',
		promotion: false,
		branding: false,
		inline_styles : true,
		content_style: "p { color: black; font-size: 12pt; font-family: Verdana; margin: 1rem auto; max-width: 1400px; }",	
		toolbar: "aligncenter alignjustify alignleft alignnone alignright| anchor | blockquote styles | bold italic underline strikethrough | emoticons | copy | cut | fontfamily fontsize backcolor forecolor hr indent | language | lineheight | newdocument | outdent | paste pastetext | redo | selectall | searchreplace | subscript superscript | undo | fullscreen",
		plugins: "wordcount, fullscreen, searchreplace, emoticons",	  
		setup: function (editor5) {
		  editor5.on('init', function (e) {
			editor5.setContent(p5_content);
		  });
		}
	});	
	
	$('input:not(#step4 input):not(.datetimepicker-input), #projectnameEdit').on('input', function() {
	  var inputValue = $(this).val();
	  var sanitizedValue = inputValue.replace(/[^A-Za-z0-9\s\-!\[\]{}()*?#&+_\-=\,\.]/g, '');
	  $(this).val(sanitizedValue);
	});  
	
	if ($('#isposted').val()==1){
		var $group = $('#postButton');
		$group.find('button').prop('disabled', true);
		$group.find('a').addClass('disabled').on('click', function(e) {
			e.preventDefault();
		});
		$('#blognumber').prop('disabled',true);
		$('#sendwithpost').prop('disabled',true);
		$('#tab6').hide();
		$('#saveProject').prop('disabled',true);
		for (var i = 1; i <= 5; i++) {
			var editorId = 'p' + i + '_editorarea';
			var editor = tinymce.get(editorId);
			if (editor) { 
				editor.mode.set('readonly'); 
			}
		}		
	}
	
});

function enoughCredits(){
	if ($('#add2').val()==1){
		var wordCount=parseInt($('#usercredits').text());
		var reqWords=parseInt($('#wordsperpost').val());
		var neededSize=reqWords+700;
		if (neededSize<wordCount){
			return true;
		} else {
			return false;
		}
	} else {
		return true;
	}
}
</script>
<div id="overlay">
    <div id="overlay-text"><i class="fas fa-sync-alt fa-spin" style="margin-right:15px"></i><span id="overlay-message">Communicating with AI - Please Wait...</span></div>
</div>

</body>

</html>