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

$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="";
$product_name="";
$summary="";
$editor_store="";
$persona=1;
$style=1;
$longtail="";
$longtail_out="";

for ($i = 1; $i <= 9; $i++) {
    $variableName = 's' . $i;
    $$variableName = "";
}

$p1_wordcount=0;
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);
	

	$longtailArray = explode("|", $longtail);
	$longtail_out = "";
	foreach ($longtailArray as $option) {
		$longtail_out .= "<option value='" . htmlspecialchars($option, ENT_QUOTES) . "'>" . htmlspecialchars($option) . "</option>\n";
	}
	
	$p1_wordcount=str_word_count($p1_input);
}

$usercredits=10000000;
// 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;
		}
		
		option.generated {
		  background-color: #FFFFBB;
		}
		.fast-spin {
			-webkit-animation: fa-spin 1s infinite linear;
			animation: fa-spin 1s infinite linear;
		}		

		
	</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">

							</span>
							<input id="add2" style="display:none;" value="<?php echo($add2); ?>">
							<input id="project_id" style="display:none;" value="<?php echo($id); ?>">
							<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); ?>">
							<input id="persona_store" style="display:none;" value="<?php echo($persona); ?>">
							<input id="longtail_store" style="display:none;" value="<?php echo($longtail); ?>">
							<input id="nomatch" style="display:none;" value="0">
							<textarea style="display:none;" name="p1_input" id="p1_input" ><?php echo $p1_input; ?></textarea>
							<textarea style="display:none;" name="summary" id="summary" ><?php echo $summary; ?></textarea>
							<textarea style="display:none;" name="editor_store" id="editor_store" ><?php echo $editor_store; ?></textarea>
							<?php
							for ($i = 1; $i <= 9; $i++) {
								$variableName = 's' . $i;
								$value = isset($$variableName) ? $$variableName : '';  // Dynamically get the variable's value
								echo "<textarea style='display:none!important;' id='$variableName'>$value</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; ?>">
							<span id="step-1" style="<?php if($id!=0){echo 'display:none;';} ?>">
							<div class="row">
								<div class="col-12">
									<div class="alert alert-primary">Paste in your source text or scrape the URL of the product or service. Please edit until the content is less than 5500 words (anything after 5500 words will be discarded). You must have a minimum of 500 words to continue. Press next when ready to continue.</div>
								</div>
							</div>
							
							<div class="row topgap">
								<div class="col-12">
									<textarea id="scrapeContent" class="form-control" style="height:400px; border-width:3px;"></textarea>
								</div>
							</div>
							<div class="row topgap">
								<div class="col-3">
									<label for="">Product Name</label>
									<input type="text" class="form-control" placeholder="Optional but recommended" maxlength="500" name="product_name" id="product_name" value="<?php echo $product_name; ?>">
								</div>
								<div class="col-3">
									<label for="">URL to Scrape</label>
									<div class="input-group">
										<input type="text" class="form-control" placeholder="https://urltoscrape.com" maxlength="300" name="urlToScrape" id="urlToScrape" value="">
										<div class="input-group-append">
											<button class="btn btn-outline-secondary" type="button" id="btnScrapeUrl"><i class="far fa-file-code"></i> Scrape URL</button>
										</div>
									</div>
								</div>
								<div class="col-1">
									<label for="">Word #</label>
									<input type="text" readonly class="form-control" placeholder="" maxlength="300" name="" id="wordCount" value="<?php echo $p1_wordcount; ?>">
								</div>

								
								<div class="col-5" style="">
									<label for="">&nbsp;</label><br>
									<button id="btnCut" class="btn btn-info btn-icon-split " style="margin-right:5px; display:none;"><span class="icon text-white-50"><i class="fas fa-cut"></i></span><span class="text">Auto Cut</span></button>
									<button id="btnNext" class="btn btn-success btn-icon-split float-right" style="margin-right:5px;"><span class="icon text-white-50"><i class="fas fa-forward"></i></span><span class="text">Next</span></button>
									<button id="btnClear" class="btn btn-danger btn-icon-split " style="margin-right:5px;"><span class="icon text-white-50"><i class="fas fa-trash-alt"></i></span><span class="text">Clear</span></button>
								</div>
							</div>
							</span>	


							<span id="step-2" style="<?php if($id==0){echo 'display:none;';} ?>">
							<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-1">
									<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-1">
									<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>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-3">
									<label for="category">Long Tail</label>
									<div class="input-group">
										<select name="longtaillist" id="longtaillist" class="form-control custom-select" style="">
										<?php echo $longtail_out; ?>
										</select>
										<div class="input-group-append">
											<button class="btn btn-outline-secondary addltbutton" type="button" id=""><i class="fas fa-plus-circle"></i></button>
										</div>
									</div>
								</div>

								<div class="col-2">
									<label>Type</label><br>
									<select name="type" id="type" class="form-control custom-select" style="">
										<option value="3" selected="selected">Blog Post</option>
										<option value="4">Article</option>
										<option value="5">LTK Based Video Script</option>
										<option value="6">Content Based Video Script</option>
										<option value="7">LTK Based SEO Keywords</option>
										<option value="8">Content Based SEO Keywords</option>
										<option value="9">Press Release</option>
										<option value="10">Domain Names</option>
									</select>
								</div>
					
								
								<div class="col-1">
									<label>&nbsp;</label><br>
									<button id="p1-generate" class="btn btn-success btn-icon-split float-right generate" style="margin-right:5px;"><span class="icon text-white-50"><i class="fas fa-sync-alt"></i></span><span class="text">Generate</span></button>										
								</div>

							</div>
							

							<div id="outputarea" class="topgap">  <!-- Start Output Area -->
				
								<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 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> <!-- End Output Area -->
						</span>
                        </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>


	<!-- 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>	

	<!-- Add Long Tail Keyword Modal -->
    <div class="modal fade" id="addltModal" tabindex="-1" role="dialog" aria-labelledby="addltLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addcatLabel">Add New Long Tail Keyword</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 Long Tail Keyword</label>
							<input type="text" class="form-control" placeholder="Long Tail Keyword" maxlength="350" name="addlt" id="addlt" 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="addNewLt();" data-dismiss="modal"><span class="icon text-white-50"><i class="fas fa-plus-circle"></i></span><span class="text">Add Keyword</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>
$('#type').change(function(){
    var stype = $(this).val();
	stype=stype-2;
    var txtext = $('#s' + stype).val();
    var editor = tinymce.get('p1_editorarea');
    if(editor) {
        editor.setContent(txtext);
    }
});

function isValidUrl(string) {
    try {
        new URL(string);
        return true;
    } catch (_) {
        return false;  
    }
}






$('#btnNext').click(async function(){
	var scrapeContent=$('#scrapeContent').val();
	scrapeContent=scrapeContent.trim();
    var words = scrapeContent.split(/\s+/);
	if (words.length<500){
		generalToast('Not Enough Words!','You must enter a minimum of 500 words.');
	} else {
		if (words.length > 5000) {

			var trimmedContent = words.slice(0, 5000).join(' ');
			scrapeContent=trimmedContent;
		}
		$('#saveProject').prop('disabled',false);
		if (words.length>5){
			$('#p1_input').val(scrapeContent);
			//await callAi(1);
			  $('#nomatch').val("0");
			  while ($('#nomatch').val() !== "1") {
				await callAi(2);
			  }			
			
			
		}
		$('#step-1').hide();
		$('#step-2').show();
	}
});

$('#btnCut').click(function(){
    var content = $("#scrapeContent").val();
    var words = content.split(/\s+/);

    if (words.length > 6000) {
        var trimmedContent = words.slice(0, 6000).join(' ');
        $("#scrapeContent").val(trimmedContent);
		$("#scrapeContent").trigger('input');
    }
});

$('#scrapeContent').on('input', function() {
	var textContent = $(this).val();
	var charCount = textContent.length;
	var wordCount = textContent.split(/\s+/).filter(function(word) {
		return word.length > 0;
	}).length;
	$('#wordCount').val(wordCount);

});

$('#btnClear').click(function(){
	$('#scrapeContent').val('');
	$('#wordCount').val('0');
	
});

$("#btnScrapeUrl").click(function() {
	var url = $("#urlToScrape").val();
	if (isValidUrl(url)) {
		$('#overlay-message').text('Scraping content - Please wait...');
		showOverlay(true);
		$.ajax({
			url: 'AJAX_scrape.php',
			type: 'POST',
			data: { url: url },
			success: function(response) {
				$("#scrapeContent").val(response).trigger('input');
				showOverlay(false);
			},
			error: function() {
				alert("An error occurred while processing the request.");
				showOverlay(false);
			}
		});
	} else {
		alert("Please enter a valid URL.");
	}
});

$('#stype').change(function(){
    var stype = $(this).val();
    var txtext = $('#s' + stype).val();
    var editor = tinymce.get('p1_editorarea');
    if(editor) {
        editor.setContent(txtext);
    }
});


$('.generate').click(async function(){
	if(enoughCredits()==false){
		generalToast('Cannot Proceed','Sorry you do not have enough credits left.');
	} else {
		$('#saveProject').prop('disabled',false);
		await callAi(parseInt($('#type').val(), 10));
	}
});



$('.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(stype){
	return new Promise((resolve, reject) => {	
		
		var panel_input=$('#p1_input').val();
				
		var summary=$('#summary').val();
		var language=$('#language').val();
		var audience=$('#audience').val();
		var product_name=$('#product_name').val();
		var persona=$('#persona').val();
		panel_input=panel_input.trim();
		var spamemail="";
		var spamsubject="";
		var newText="";
		var rewritesubject="";
		var rewriteemail="";
		var longtail=$('#longtaillist').val();
		
		if (panel_input!==""){
			var data = {
			  language: language,
			  audience: audience,
			  panel_input: panel_input,
			  stype: stype,
			  product_name: product_name,
			  persona: persona,
			  spamemail: spamemail,
			  spamsubject: spamsubject,
			  rewriteemail: rewriteemail,
			  rewritesubject: rewritesubject,
			  longtail: longtail
			};
			showOverlay(true);
			if (stype==1){
				$('#overlay-message').text('Asking AI to analyze content - Please wait...');
			} else {
				$('#overlay-message').text('Asking AI to generate content - Please wait...');
			}
			$.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 {
						var airesp = JSON.parse(response);
						var content = airesp.choices[0].message.content;
						if (stype<11){
							var content = content.replace(/\n/g, '<br>');
							let parts = content.split('<br><br>');
							for(let i = 0; i < parts.length; i++) {
								parts[i] = '<p>' + parts[i] + '</p>';
							}
							newText = parts.join('');
						}
						if (stype==1){
							$('#summary').val(newText);
							showOverlay(false);
						} else if (stype>2) {
							var editor = tinymce.get('p1_editorarea');
							editor.setContent(newText);
							$('#s'+(stype-2)).val(newText);
							$('#type option[value="' + stype + '"]').addClass('generated');
							showOverlay(false);
							var wordCount=getCount();
							wordCount=wordCount+parseInt($('#wordCount').val());
							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);
									}
								});
							}						
							showOverlay(false);
						} else if (stype==2) {

							var cleanedContent = content.replace(/<br>\s*/g, '');
							var jsonPart = cleanedContent.match(/\[\s*".+?\s*\]/s);
							var keywordsArray = [];

							if (jsonPart) {
								try {
									keywordsArray = JSON.parse(jsonPart[0]);
								} catch (e) {
									console.log("Error parsing JSON:", e);
								}
							}


							var longtail_store = '';
							$('#longtaillist').empty();

							if (keywordsArray.length > 0) {
								$('#nomatch').val("1");
								console.log("Matches found");
								$.each(keywordsArray, function(index, value) {
									var newOption = $('<option></option>').val(value).text(value);
									$('#longtaillist').append(newOption);
									longtail_store += value + '|';
								});
								longtail_store = longtail_store.slice(0, -1); 
								$('#longtail_store').val(longtail_store);
							} else {
								$('#nomatch').val("0");
								console.log("No matches found or invalid JSON");
							}

							showOverlay(false);
						} else if (stype==222) {
							var editor = tinymce.get('p1_editorarea');
							editor.setContent(newText);
							$('#editor_store').val(newText).trigger('change');
							showOverlay(false);
							var wordCount=getCount();
							wordCount=wordCount+parseInt($('#wordCount').val());
							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);
									}
								});
							}
						}
				}
				resolve();
			  },
			  error: function(xhr, status, error) {
					showOverlay(false);
					$('#s2errorModal').modal('show');
					resolve();
			  }
			});		
			

		} else {
			generalToast('ERROR: Field is empty!','The Subject field must NOT be empty!');
		}
		
	});
}


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

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

$('.addltbutton').click(function(){
	$('#addltModal').modal('show');
});

function addNewLt(){
	var newlt=$('#addlt').val().trim();
	if (newlt!=""){
		$('#longtail_store').val($('#longtail_store').val()+"|"+newlt);
		var newOption = $('<option>', {
			value: newlt,
			text: newlt
		});
		$('#longtaillist').append(newOption);
		generalToast('Keyword Added','This Long Tail Keyword has been added');
	}
}

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 p1_input = $('#p1_input').val();
		var summary = $('#summary').val();
		var audience = $('#audience').val();
		var language = $('#language').val();
		var category=$('#category').val();
		var project_id=$('#project_id').val();
		var projectname=$('#projectname').val();
		var product_name=$('#product_name').val();
		var style=$('#style').val();
		var editor_store=$('#editor_store').val();
		var longtail_store=$('#longtail_store').val();
		let sdata = {};
		for (let i = 1; i <= 9; i++) {
			let id = 's' + i;
			sdata[id] = btoa(unescape(encodeURIComponent($(`#${id}`).val())));
		}	
		var data = {
		  projectname: projectname,
		  category: category,
		  id: project_id,
		  summary: summary,
		  p1_input: p1_input,
		  audience: audience,
		  language: language,
		  product_name: product_name,
		  style: style,
		  editor_store: editor_store,
		  longtail: longtail_store,
		  ...sdata
		};	
		
		$('#saveProject').html('<span class="icon text-white-50"><i class="fas fa-sync-alt fa-spin fast-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.');
			if (Number.isInteger(+response)) {
				$('#project_id').val(response);
			} else {
				$('#project_id').val(0);
			}
		  },
		  error: function(xhr, status, error) {
				console.log("ERROR WITH SAVE");
		  }
		});	
	}
});



$('.exportbutton').click(function(){
	let whichbutton=$(this).data('id');
	let stype=$('#stype').val();
	var grabdoc = tinymce.get("p1_editorarea").getContent();
	$('#p1_docHtml').html('<style>p { color: black; font-size: 12pt; font-family: Verdana; }</style>'+grabdoc);
	var filename=$('#projectname').val();
	if(filename==''){filename='myfile';}
	
	filename = filename.replace(/\W+/g, " ");
	filename = filename.replace(/\s+/g, "-");
	
	
	switch(whichbutton){
		case "txt":
			var grabtext = tinymce.get("p1_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'
			};
			$('#p1_docHtml').show();
			$(document).googoose(o);
			$('#p1_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 showOverlay(show) {
    if(show) {
        $('#overlay').addClass('display-flex');
    } else {
        $('#overlay').removeClass('display-flex');
    }
}


$(document).ready(function() {
	$('#category').val($('#category_store').val());
	$('#language').val($('#language_store').val());
    $('#type option').each(function() {
        var optionValue = $(this).val();
		optionValue=parseInt(optionValue,10);
		optionValue=optionValue-2;
        var correspondingTextarea = $('#s' + optionValue);
        if (correspondingTextarea.length === 0) {
            return true;
        }
        if (correspondingTextarea.val().trim() !== '') {
            $(this).addClass('generated');
        }
    });	
	
	$('#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('change', function (e) {
			var content = editor1.getContent();
			$('#editor_store').val(content).trigger('change');
		});			
		  editor1.on('init', function (e) {
			var content=$('#s1').val();
			tinymce.get('p1_editorarea').setContent(content);
			
		  });
		}
	});	


		
	$('input:not(#step4 input,#urlToScrape), #projectnameEdit').on('input', function() {
	  var inputValue = $(this).val();
	  var sanitizedValue = inputValue.replace(/[^A-Za-z0-9\s\-!\[\]{}()*?#&+_\-=\,\.À-ÖØ-öø-ÿ]/g, '');
	  $(this).val(sanitizedValue);
	});


	
});

function getFirstContent() {
    for (let i = 1; i <= 9; i++) {
        let id = 's' + i;
        let value = $("#" + id).val().trim();
        if (value !== "") {
            return id.substring(1);
        }
    }
    return null; 
}

function getCount(){
	tinyeditor = tinymce.get('p1_editorarea');
	wordCount = tinyeditor.plugins.wordcount.getCount();
	return wordCount;
}


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

</body>

</html>