<?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="";
$category=0;
$canvas_width=300;
$canvas_height=300;
$palette_store="";
$canvas_store=0;


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

$usercredits=100000000000;
// 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 credits left";
		}
}

$fontlist=file_get_contents("fontlist.php");
$fontlist=trim($fontlist);
$fontlist = str_replace(array("\r", "\n"), '', $fontlist);

$fontlistarray=explode("&",$fontlist);
$loadfonts="";
$fontselect="";

// create font loader and selector list
$i=0;
foreach($fontlistarray as $font) {
	if ($i==0){
		$loadfonts.=$font;
	} else {
		$loadfonts.="&family=".$font;
	}
	$font=str_replace("+"," ",$font);
	$fontselect.="<a class=\"dropdown-item\" style=\"font-family:'".$font."';\" onclick=\"selectFont('".$font."');\">".$font."</a>";
	$i++;
}

$loadfontsfinal="https://fonts.googleapis.com/css2?family=".$loadfonts."&display=swap";

// create styles list

$styles="Abstract Art,Abstract Geometry,Art Deco,Art Nouveau,Bauhaus,Bokeh Art,Brutalism,Byzantine,Celtic,Cartoon,Charcoal,Childrens Book Illustration,Chinese Brush Painting,Chiptune Visuals,Comic Book (Simple),Comic Book (American),Comic Book (British SciFi),Comic Book (Manga),Concept Art,Constructivism,Cyber Folk,Cyber Art,Cyberpunk,Cyberpunk Neon Illustration,Cyberpunk Neon Photo,Dadaism,Data Art,Digital Collage,Digital Cubism,Digital Impressionism,Digital Painting,Double Exposure,Dreamy Fantasy,Dystopian Art,Etching,Expressionism,Fauvism,Flat Design,Food Photography,Fractal Art,Futurism,Glitch Art,Gothic Art,Gouache,Graphic Novel,Greco-Roman Art,Illustration,Impressionism,Impressionist Painting,Ink Line Art,Ink Wash,Isometric Art,Japanese Ukiyo-e,Kinetic Typography,Lithography,Low Poly,Macabre Art,Magic Realism,Minimalism,Modernism,Monogram,Mosaic,Neon Graffiti,Neon Noir,Origami,Papercut,Parallax Art,Pastel Drawing,Pencil Sketch,Photographic,Photorealism,Pixel Art,Play Clay,Pointillism,Polyart,Pop Art,Psychedelic Art,Rennaissance/Baroque,Retail Photography,Retro Wave,Romanticism,Sci-Fi,Sci-Fi Fantasy,Scratchboard,Steampunk,Stippling,Street Photography,Surrealism,Symbolism,Technical Illustration,Tilt-Shift,Trompe-l'oeil,Vaporwave,Vector Art,Voxel Art,Watercolor,Watercolor Detailed,Watercolor Simple,Woodblock Printing,Zen Doodle";

$stylearray=explode(",",$styles);
$stylesoptions="";
$i=1;
foreach ($stylearray as $style) {
	$stylesoptions.='<option value="'.$i.'">'.$stylearray[$i-1].'</option>';
	$i++;
}

?>
<!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>
	<link rel="preconnect" href="https://fonts.googleapis.com">
	<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

	<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet" />

	<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
    <!-- 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 rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="<?php echo $loadfontsfinal; ?>" 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" />
	
	<link href="https://cdn.jsdelivr.net/npm/spectrum-colorpicker2@2.0.10/dist/spectrum.min.css" rel="stylesheet">


	
	<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;
		}		
		.sp-replacer {
			margin:0;
			margin-top:6px;
			vertical-align:middle;
			display:inline-block;
			display: inline;
			border: none;
			background: transparent;
			border-radius:0px;
			
		}
		.sp-replacer:hover, .sp-replacer.sp-active {
			border-color: #F0C49B;
			background-color:#DDE2F1;
			color: #111;
		}

		.sp-dd {
			padding: 14px 2px;
			height: 9px;
			width: 15px;
			line-height: 10px;
			float:left;
			font-size:8px;
		}

		

		.btn-toolbar {
			display: flex;
			flex-wrap: wrap;
			justify-content: flex-start;
		}

		.btn-toolbar .btn-group {
			flex-shrink: 0;
		}

		
	</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="">
                        <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="category_store" style="display:none;" value="<?php echo($category); ?>">
							<input id="palette_store" style="display:none;" value="<?php echo ($palette_store);?>">
							<input id="image_upload_name_store" style="display:none;" value="">
							<input id="image_ai_name_store" style="display:none;" value="">
							
							<input id="font_store" style="display:none;" value="Verdana">
							
							<button id="saveProject" class="btn btn-primary btn-icon-split float-right" style="margin-right:5px;" ><span class="icon text-white-50"><i class="fas fa-save"></i></span><span class="text">Save</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">

							<div class="row">
								<div class="col-3">
									<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-3">
									<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>Width</label>
									<input type="number" class="form-control" id="canvasx" value="<?php echo $canvas_width; ?>">
								</div>
								
								<div class="col-2">
									<label>Height</label>
									<input type="number" class="form-control" id="canvasy" value="<?php echo $canvas_height; ?>">
								</div>
								
								<div class="col-2">
									<label>Preset Size</label>
									<select id="presetsize" class="form-control custom-select" >
										<option class="form-control" selected="selected" disabled="disabled">Please Select</option>
										<option class="form-control" value="1024x1024">AI Image 1024x1024</option>
										<option class="form-control" value="1792x1024">AI Image 1792x1024</option>
										<option class="form-control" value="1024x1792">AI Image 1024x1792</option>
										<option class="form-control" disabled="disabled"></option>
										<option class="form-control" value="1280x720">HD 1280x720</option>
										<option class="form-control" value="1920x1080">Full HD 1920x1080</option>
										<option class="form-control" value="3840x2160">UHD (4k) 3840x2160</option>
										<option class="form-control" disabled="disabled" onclick=""></option>
										<option class="form-control" value="1600x2560">Amazon KDP ebook cover 1600x2560</option>
										<option class="form-control" value="1400x2100">B&N Nook ebook cover 1400x2100</option>
										<option class="form-control" value="1600x2400">Kobo ebook cover 1600x2400</option>
										<option class="form-control" value="1600x2560">Google ebook cover 1600x2560</option>
										<option class="form-control" value="1400x2100">Apple iBooks ebook cover 1400x2100</option>
										<option class="form-control" value="1400x2100">Smashwords ebook cover 1400x2100</option>
										<option class="form-control" value="2800x3920">Illustrated ebook cover 1 2800x3920</option>
										<option class="form-control" value="3000x3600">Illustrated ebook cover 2 3000x3600</option>
										<option class="form-control" value="3200x3200">Audiobook cover 3200x3200</option>
										<option class="form-control" disabled="disabled" onclick=""></option>
										<option class="form-control" value="820x312">Facebook cover photos</option>
										<option class="form-control" value="170x170">Facebook profile photos</option>
										<option class="form-control" value="1200x628">Facebook event photos</option>
										<option class="form-control" value="1080x1080">Facebook image/video ads</option>
										<option class="form-control" disabled="disabled" onclick=""></option>
										<option class="form-control" value="320x320">Instagram Profile Photos</option>
										<option class="form-control" value="1080x566">Instagram Ads landscape</option>
										<option class="form-control" value="1080x1080">Instagram Ads/Posts square</option>
										<option class="form-control" value="600x750">Instagram Ads vertical</option>
										<option class="form-control" value="1080x566">Instagram posts landscape</option>
										<option class="form-control" value="1080x1350">Instagram posts vertical</option>
										<option class="form-control" value="1080x1920">Instagram stories</option>
										<option class="form-control" disabled="disabled" onclick=""></option>
										<option class="form-control" value="2560x1440">YouTube channel art</option>
										<option class="form-control" value="1280x720">YouTube thumbnail</option>
										<option class="form-control" disabled="disabled" onclick=""></option>
										<option class="form-control" value="400x400">Twitter/X profile photo</option>
										<option class="form-control" value="1500x500">Twitter/X header</option>
										<option class="form-control" value="1600x900">Twitter/X image post</option>
										<option class="form-control" disabled="disabled" onclick=""></option>
										<option class="form-control" value="2000x2000">Etsy listing image</option>
										<option class="form-control" value="2700x2075">Etsy product image</option>
										<option class="form-control" value="1600x400">Etsy shop banner</option>
										<option class="form-control" value="1200x300">Etsy carousel banner</option>
										<option class="form-control" disabled="disabled" onclick=""></option>
										<option class="form-control" value="1000x1500">Pinterest carousel/collection/static pin</option>
										<option class="form-control" value="1080x1920">Pinterest idea pin</option>
										<option class="form-control" value="1000x1000">Pinterest square pin</option>
									</select>		
								
							</div>
						</div>
                    </div>
						<div class="card-body" style="">
							<div class="row">
								<div class="col-12">
									<div class="btn-toolbar" role="toolbar" aria-label="">	
										<button data-toggle="tooltip" data-placement="top" title="Send to back (CTRL+ALT+PgDn)" type="button" class="btn btn-light" onclick="toback();" id=""><span class="material-symbols-outlined">flip_to_back</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Bring to front (CTRL+ALT+PgUp)" type="button" class="btn btn-light" onclick="tofront();" id=""><span class="material-symbols-outlined">flip_to_front</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Delete (DEL)" type="button" class="btn btn-light" onclick="delobject();" id=""><span class="material-symbols-outlined">delete_forever</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Cut (CTRL+X)" type="button" class="btn btn-light" onclick="cutObjects();" id=""><span class="material-symbols-outlined">content_cut</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Copy (CTRL+C)" type="button" class="btn btn-light" onclick="copyObjects();" id=""><span class="material-symbols-outlined">content_copy</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Paste (CTRL+V)" type="button" class="btn btn-light" onclick="pasteObjects();" id=""><span class="material-symbols-outlined">content_paste</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Deselect All (CTRL+ALT+D)" type="button" class="btn btn-light" onclick="deselectObjects();" id=""><span class="material-symbols-outlined">deselect</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Download PNG (CTRL+ALT+P)" type="button" class="btn btn-light" onclick="toImage();" id=""><span class="material-symbols-outlined">download</span></button>

										<div data-toggle="tooltip" data-placement="top" title="Choose Font" class="btn-group" role="group" style="margin-right:-10px!important;">
											<button id="btnGroupFont" type="button" class="btn btn-light dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span class="material-symbols-outlined">brand_family</span></button>
											<div class="dropdown-menu" style="cursor:pointer;">
												<?php echo $fontselect; ?>
												<a class="dropdown-item" style="font-family:'Verdana';" onclick="selectFont('Verdana');">Verdana</a>
											</div>
										</div>
										
										<button data-toggle="tooltip" data-placement="top" title="Add text (CTRL+ALT+T)" type="button" class="btn btn-light" onclick="addText();" id=""><span class="material-symbols-outlined">insert_text</span></button>

										<button data-toggle="tooltip" data-placement="top" title="Align text left" type="button" class="btn btn-light" onclick="textJustify(0);" id=""><span class="material-symbols-outlined">format_align_left</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Center text" type="button" class="btn btn-light" onclick="textJustify(1);" id=""><span class="material-symbols-outlined">format_align_center</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Align text right" type="button" class="btn btn-light" onclick="textJustify(2);" id=""><span class="material-symbols-outlined">format_align_right</span></button>
										
										<button data-toggle="tooltip" data-placement="top" title="Remove dropshadow" type="button" class="btn btn-light" onclick="removeShadow();" id=""><span class="material-symbols-outlined">shadow_minus</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Add dropshadow" type="button" class="btn btn-light" onclick="setShadow();" id=""><span class="material-symbols-outlined">shadow_add</span></button>
										
										<button data-toggle="tooltip" data-placement="top" title="Fill (CTRL+ALT+F)" type="button" class="btn btn-light" onclick="colorObject();" id=""><span class="material-symbols-outlined">format_color_fill</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Decrease object size (CTRL+ALT+MINUS)" type="button" class="btn btn-light" onclick="sizeObject(0);" id=""><span class="material-symbols-outlined">indeterminate_check_box</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Increase object size (CTRL+ALT+PLUS)" type="button" class="btn btn-light" onclick="sizeObject(1);" id=""><span class="material-symbols-outlined">add_box</span></button>
										<button data-toggle="tooltip" data-placement="top" title="Crop image" type="button" class="btn btn-light" id="cropButton"><span class="material-symbols-outlined">crop</span></button>
										
										<div data-toggle="tooltip" data-placement="top" title="Add image" class="btn-group" role="group" style="margin-right:-10px!important;">
											<button id="btnGroupImage" type="button" class="btn btn-light dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span class="material-symbols-outlined">add_photo_alternate</span></button>
											<div class="dropdown-menu" style="cursor:pointer;">
											  <a class="dropdown-item" onclick="document.getElementById('imageUpload').click();">Upload Image</a>
											  <a class="dropdown-item" onclick="addImage(1);">AI Image</a>
											</div>
										</div>
										
										<div data-toggle="tooltip" data-placement="top" title="Add shape" class="btn-group" role="group" style="margin-right:-10px!important;">
											<button id="btnGroupShape" type="button" class="btn btn-light dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span class="material-symbols-outlined">shapes</span></button>
											<div class="dropdown-menu" style="cursor:pointer;">
											  <a class="dropdown-item" onclick="addShape(0);">Circle</a>
											  <a class="dropdown-item" onclick="addShape(1);">Square</a>
											  <a class="dropdown-item" onclick="addShape(2);">Triangle</a>
											</div>
										</div>
										
										<div data-toggle="tooltip" data-placement="top" title="Add outline" class="btn-group" role="group" style="margin-right:-10px!important;">
											<button id="btnGroupOutline" type="button" class="btn btn-light dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span class="material-symbols-outlined">border_outer</span></button>
											<div class="dropdown-menu" style="cursor:pointer;">
												<?php for ($i=0; $i<26; $i++){echo '<a class="dropdown-item" onclick="setOutline('.$i.')">'.$i.'px</a>';} ?>
											</div>
										</div>
										
			  

										<div data-toggle="tooltip" data-placement="top" title="Snap to grid" class="btn-group" role="group" >
											<button id="btnGroupSnap" type="button" class="btn btn-light dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span class="material-symbols-outlined">grid_on</span></button>
											<div class="dropdown-menu" style="cursor:pointer;">
											  <a class="dropdown-item" onclick="setGrid(0);">Snap To Grid Off</a>
											  <a class="dropdown-item" onclick="setGrid(5);">5px</a>
											  <a class="dropdown-item" onclick="setGrid(10);">10px</a>
											  <a class="dropdown-item" onclick="setGrid(15);">15px</a>
											  <a class="dropdown-item" onclick="setGrid(20);">20px</a>
											  <a class="dropdown-item" onclick="setGrid(30);">30px</a>
											  <a class="dropdown-item" onclick="setGrid(50);">50px</a>
											  <a class="dropdown-item" onclick="setGrid(100);">100px</a>
											</div>
										</div>
										
										<input type="color" class="btn btn-light" id="colpick" name="colpick" value="#e66465" />
										
										<span style="margin-top:10px; margin-left:5px; font-size:12px;">X-</span><input id="objx" value="" style="font-size:12px; width:40px; height:25px; margin-top:6px; background-color: #f9f9f9; border:1px solid #ddd;" readonly>
										<span style="margin-top:10px; margin-left:5px; font-size:12px;">Y-</span><input id="objy" value="" style="font-size:12px; width:40px; height:25px; margin-top:6px; background-color: #f9f9f9; border:1px solid #ddd;" readonly>

									</div>
								</div>
							
							</div>
							<div class="row"><div class="col-12"><hr><input type="file" id="imageUpload" name="imageUpload" style="display: none;" /></div></div>
							<div class="row">
								<div class="col-12" style="overflow-x:auto; overflow-y:hidden; padding-bottom:20px;">
									<div id="canvasContainer" style="width: <?php echo $canvas_width; ?>px; height: <?php echo $canvas_height; ?>px; position: relative; margin:0 auto; ">
										<canvas id="canvas" width="<?php echo $canvas_width; ?>" height="<?php echo $canvas_height; ?>" style="border:2px solid #DDDDDD; box-sizing:content-box;"></canvas>
										<div id="resizeHandle" style="width: 11px; height: 11px; border:2px solid #AAAAAA; position: absolute; bottom: -9px; right: -9px; cursor: nwse-resize;"></div>
									</div>
								</div>
							</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 Image Modal -->
    <div class="modal fade" id="imageAiModal" tabindex="-1" role="dialog" >
        <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Generate AI Image</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>Prompt</label>
							<textarea type="text" class="form-control validate" placeholder="Enter your image prompt" maxlength="3999" name="imageprompt" id="imageprompt" ></textarea>
						</div>
					</div>
					<div class="row topgap">
						<div class="col-2">
							<label for="">Enhance</label>
							<select name="reviseprompt" id="reviseprompt" class="form-control custom-select">
								<option selected="selected" value="0">No - Exact Prompt</option>
								<option value="1">Yes - Enhance Prompt</option>
							</select>
						</div>
						<div class="col-2">
							<label for="">Image Type</label>
							<select name="imagetype" id="imagetype" class="form-control custom-select">
								<option selected="selected" value="0">Vivid</option>
								<option value="1">Natural</option>
							</select>
						</div>
						<div class="col-2">
							<label for="">Size</label>
							<select name="imagesize" id="imagesize" class="form-control custom-select">
								<option selected="selected" value="0">1024 x 1024</option>
								<option value="1">1792 x 1024</option>
								<option value="2">1024 x 1792</option>
							</select>
						</div>
						<div class="col-3">
							<label for="">Image Style</label>
							<select name="imagestyle" id="imagestyle" class="form-control custom-select">
								<option selected="selected" value="0">No Style (custom)</option>
								<?php echo $stylesoptions; ?>
							</select>
						</div>
						<div class="col-3">
							<label>&nbsp;</label><br>
							<button id="btnGenerate" class="btn btn-success btn-icon-split" style="margin-right:5px; float:right;" data-dismiss="modal"><span class="icon text-white-50"><i class="fas fa-sync-alt"></i></span><span class="text">Generate</span></button>
						</div>
					</div>
				</div>
                <div class="modal-footer">
					<button class="btn btn-danger btn-icon-split" style="margin-right:5px;" data-dismiss="modal"><span class="icon text-white-50"><i class="fas fa-window-close"></i></span><span class="text">Cancel</span></button>
                </div>
            </div>
        </div>
    </div>


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


	<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 src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js" integrity="sha512-CeIsOAsgJnmevfCi2C7Zsyy6bQKi43utIjdA87Q0ZY84oDqnI0uwfM9+bKiIkI75lUeI00WG/+uJzOmuHlesMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
	<script src=" https://cdn.jsdelivr.net/npm/spectrum-colorpicker2@2.0.10/dist/spectrum.min.js "></script>
	


<script>

const canvas = new fabric.Canvas('canvas',{preserveObjectStacking: true});
var selectedObject=null;

function uploadFile() {
	let fileInput = document.getElementById('imageUpload');
	let file = fileInput.files[0];
	let formData = new FormData();
	formData.append('file', file);
	fetch('AJAX_imgup.php', {
		method: 'POST',
		body: formData
	})
	.then(response => response.json())
	.then(data => {
		if (data.status === 'success') {
			fabric.Image.fromURL(data.message, function(imgInstance) {
			  imgInstance.set({
				left: 1,
				top: 1,
				angle: 0,
				opacity: 1
			  });
			  canvas.add(imgInstance);
			});
		} else {
			alert('Upload failed: ' + data.message);
		}
	})
	.catch(error => {
		alert('An error occurred: ' + error);
	});
}

function addImage(imageType){
	if (imageType==1) {
		$('#imageAiModal').modal('show');
	}
}

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

$('.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();
	}
});

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;
}


function isCanvasEmpty() {
    return canvas.getObjects().length === 0;
}

$('#saveProject').click(function(){
	var projectname=$('#projectname').val();
	projectname=projectname.trim();
	if (projectname===''){
		generalToast("ERROR!","You MUST enter a Project Name");
	} else if (isCanvasEmpty()){
		generalToast("ERROR!","Your canvas is empty!");
	} else {
		var category=$('#category').val();
		var project_id=$('#project_id').val();
		var canvas_width=$('#canvasx').val();
		var canvas_height=$('#canvasy').val();
		var palette_store=localStorage.getItem("imagecrafter.selectionPalette");
		canvas.forEachObject(function(obj) {
			obj.fill = colorToHex(obj.fill);
			obj.stroke = colorToHex(obj.stroke);
		});
		
		var canvas_store = JSON.stringify(canvas.toJSON());
		var data = {
		  projectname: projectname,
		  category: category,
		  id: project_id,
		  canvas_width: canvas_width,
		  canvas_height: canvas_height,
		  palette_store: palette_store,
		  canvas_store: canvas_store
		};	
		$('#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</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");
		  }
		});	
	}
});



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


$(document).ready(function() {

	document.getElementById('imageUpload').addEventListener('change', uploadFile);
	$('#objx,#objy').on('focus', function() {
		$(this).blur();
	});
	localStorage.removeItem("imagecrafter.selectionPalette");
	var palette_store=$('#palette_store').val();
	$('#colpick').spectrum({
	  type: "component",
	  togglePaletteOnly: true,
	  showInput: true,
	  showInitial: true,
	  showAlpha: false,
	  showSelectionPalette: true,
	  selectionPalette: [[palette_store]],
	  localStorageKey: "imagecrafter.selectionPalette"
	});
	
	$('#category').val($('#category_store').val());
	
	$('#outerWrapper').show();
		
	$('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);
	});

	WebFont.load({ // Wait for fonts to load
		google: {
			families: ['Lobster']
		},
		active: function() {
			$('#loading').hide();
			
		}
	});	
	$(function () {
	  $('[data-toggle="tooltip"]').tooltip()
	});
	$('.btn-group[data-toggle="tooltip"] .dropdown-toggle').click(function(){
		$(this).closest('[data-toggle="tooltip"]').tooltip('hide');
	});
	
	var project_id=$('#project_id').val();
	if (project_id>0){
		var canvasData = <?php echo $canvas_store; ?>;
		canvas.loadFromJSON(canvasData, function() {
			canvas.renderAll();
		});
	}
});



	function updatePositionInputs(obj) {
		$('#objx').val(obj.left.toFixed(0)); // Update X position
		$('#objy').val(obj.top.toFixed(0));  // Update Y position
	}
	canvas.on('object:moving', function() {
		var activeObject = canvas.getActiveObject();
		if (activeObject) {
			updatePositionInputs(activeObject);
		}
	});

	function updateInputFields() {
		var activeObject = canvas.getActiveObject();

		if (activeObject) {
			if (activeObject.type === 'activeSelection') {
				var boundingRect = activeObject.getBoundingRect();
				$('#objx').val(boundingRect.left.toFixed(0));
				$('#objy').val(boundingRect.top.toFixed(0));
			} else {
				$('#objx').val(activeObject.left.toFixed(0));
				$('#objy').val(activeObject.top.toFixed(0));
			}
		} else {
			$('#objx').val('');
			$('#objy').val('');
		}
	}


	canvas.on('selection:created', updateInputFields);
	canvas.on('selection:updated', updateInputFields);
	canvas.on('object:modified', updateInputFields);

	
	canvas.on('object:rotating', function (options) {
		var objectRotating = options.target;
		
		objectRotating.on('rotating', function(options) {
		  if(options.e.shiftKey) {
			this.snapAngle = 15;
		  } else {
			this.snapAngle = 0;
		  }
		});
	});


	fabric.Object.prototype.toObject = (function (toObject) {
		return function (propertiesToInclude) {
			return fabric.util.object.extend(toObject.call(this, propertiesToInclude), {
				fill: this.fill,
				stroke: this.stroke
			});
		};
	})(fabric.Object.prototype.toObject);

	var lastClickedTime = 0;
	var lastClickedObject = null;
	var doubleClickThreshold = 300; // milliseconds

	function setGrid(gridPx){
		if (gridPx>0){
			canvas.on('object:moving', function (options) {
				var gridSize = gridPx;
				var object = options.target;
				object.set({
					left: Math.round(object.left / gridSize) * gridSize,
					top: Math.round(object.top / gridSize) * gridSize
				});
			});
		} else {
			canvas.off('object:moving');
		}
	}
	
	function addShape(shape){
		var colorchange=$('#colpick').spectrum('get');
		switch(shape){
			case 0:
				canvas.add(new fabric.Circle({ top: 1, left: 1, radius: 25, fill: colorchange }));
				break;
			case 1:
				canvas.add(new fabric.Rect({ top: 1, left: 1, width: 50, height: 50, fill: colorchange }));
			break;
			case 2:
				canvas.add(new fabric.Triangle({ top: 1, left: 1, width: 50, height: 50, fill: colorchange }));
			break;
		}
		
	}

	// Cropping start

	var cropRect, isCropping = false, imageToCrop;
	var cancelIcon, confirmIcon;

	function addCropIcons() {
	  fabric.Image.fromURL('img/icon_cancel.png', function(img) {
		cancelIcon = img.set({
		  left: cropRect.left + cropRect.width - 38,
		  top: cropRect.top + cropRect.height + 2,
		  scaleX: .5,
		  scaleY: .5,
		  hasControls: false,
		  hasBorders: false,
		  hoverCursor: 'pointer'
		});
		cancelIcon.on('mousedown', function() {
		  removeCrop();
		});
		canvas.add(cancelIcon);
	  });

	  fabric.Image.fromURL('img/icon_tick.png', function(img) {
		confirmIcon = img.set({
		  left: cropRect.left + cropRect.width - 15,
		  top: cropRect.top + cropRect.height + 2,
		  scaleX: .5,
		  scaleY: .5,
		  hasControls: false,
		  hasBorders: false,
		  hoverCursor: 'pointer'
		});
		confirmIcon.on('mousedown', function() {
		  performCrop();
		});
		canvas.add(confirmIcon);
	  });
	}



	function removeCrop() {
	  canvas.remove(cropRect, cancelIcon, confirmIcon);
	  canvas.renderAll();
	}


	document.getElementById('cropButton').addEventListener('click', function() {
	  if (isCropping) {
		//performCrop();
	  } else {
		var activeObject = canvas.getActiveObject();
		if (!activeObject || activeObject.type !== 'image') {
		  alert('Please select an image first');
		  return;
		}
		imageToCrop = activeObject;
		startCropping();
	  }
	});


	function startCropping() {
	  isCropping = true;

	  if (cropRect) {
		canvas.remove(cropRect);
	  }

	  cropRect = new fabric.Rect({
		left: imageToCrop.left,
		top: imageToCrop.top,
		width: 100,
		height: 100,
		fill: 'rgba(0,0,0,0.3)',
		cornerColor: 'blue',
		cornerSize: 10,
		transparentCorners: false,
		lockRotation: false,
		hasRotatingPoint: true
	  });
	  //cropRect.setControlsVisibility({ mtr: false })
	  canvas.add(cropRect);
	  canvas.bringToFront(cropRect);
	  canvas.setActiveObject(cropRect);
	  addCropIcons();
	  cropRect.on('moving', updateIconPositions);
	  cropRect.on('scaling', updateIconPositions);  
	  
	}

	function updateIconPositions() {
	  if (cropRect && cancelIcon && confirmIcon) {
		// Calculate scaled width and height
		var scaledWidth = cropRect.getScaledWidth();
		var scaledHeight = cropRect.getScaledHeight();

		// Update positions for both icons
		cancelIcon.set({
		  left: cropRect.left + scaledWidth - 38,
		  top: cropRect.top + scaledHeight + 2
		}).setCoords(); // Update coordinates after setting the position

		confirmIcon.set({
		  left: cropRect.left + scaledWidth - 15,
		  top: cropRect.top + scaledHeight + 2
		}).setCoords(); // Update coordinates after setting the position

		canvas.renderAll();
	  }
	}


function performCrop() {
    isCropping = false;

    // Calculate the cropping coordinates, accounting for scaling
    var scaleX = imageToCrop.scaleX;
    var scaleY = imageToCrop.scaleY;
	
	var imageAngle=imageToCrop.angle;
	var imageSkewX=imageToCrop.skewX;
	var imageSkewY=imageToCrop.skewY;
	
    var rectScaleX = cropRect.scaleX;
    var rectScaleY = cropRect.scaleY;

    var cropX = (cropRect.left - imageToCrop.left) / scaleX;
    var cropY = (cropRect.top - imageToCrop.top) / scaleY;
    var cropWidth = cropRect.width * rectScaleX / scaleX;
    var cropHeight = cropRect.height * rectScaleY / scaleY;

    // Create an image element to hold the cropped data
    var croppedImg = new Image();
    croppedImg.src = cropImage(imageToCrop, cropX, cropY, cropWidth, cropHeight);

    // Once the image is loaded, update canvas and send it to the server
    croppedImg.onload = function() {
        // Convert Data URL to Blob and send to the server
        dataURLToBlob(croppedImg.src).then(function(blob) {
            var formData = new FormData();
            formData.append('croppedImage', blob);
            formData.append('imageName', imageToCrop.getSrc().split('/').pop());

            $.ajax({
                url: 'AJAX_savecrop.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    // Assuming response is JSON with a field 'imageUrl'
                    if (response.status && response.imageUrl) {
                        var newImageUrl = response.imageUrl;
                        var uniqueUrl = newImageUrl;
                        

                        fabric.Image.fromURL(uniqueUrl, function(newImage) {
                            newImage.set({
                                left: cropRect.left,
                                top: cropRect.top,
                                scaleX: scaleX,
                                scaleY: scaleY,
                                angle: imageAngle,
                                skewX: imageSkewX,
                                skewY: imageSkewY
                            });
                            canvas.remove(imageToCrop);
                            canvas.remove(cropRect, cancelIcon, confirmIcon);
                            canvas.add(newImage);
                            canvas.renderAll();
                        });
                    } else {
                        console.error('Error in image upload:', response.message);
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error('AJAX error:', textStatus);
                }
            });
        });
    };
}

function cropImage(image, left, top, width, height) {
    var tempCanvas = document.createElement('canvas');
    tempCanvas.width = width;
    tempCanvas.height = height;
    var ctx = tempCanvas.getContext('2d');

    ctx.drawImage(image.getElement(), left, top, width, height, 0, 0, width, height);
    return tempCanvas.toDataURL();
}

function dataURLToBlob(dataURL) {
    return fetch(dataURL)
        .then(function(response) {
            return response.blob();
        });
}

function uniqid(prefix = "", random = false) {
    const sec = Date.now() * 1000 + Math.random() * 1000;
    const id = sec.toString(16).replace(/\./g, "").padEnd(14, "0");
    return `${prefix}${id}${random ? `.${Math.trunc(Math.random() * 100000000)}`:""}`;
};

	// Handle change color picker on object select
	canvas.on('selection:created', function(event) {
		changeColorPicker();
	});
	canvas.on('selection:updated', function(event) {
		changeColorPicker();
	});

	function changeColorPicker(){
		var currentobj=canvas.getActiveObject();
		$('#colpick').spectrum('set',currentobj.fill);
	}
	
	function textJustify(justifyMode){
		var currentobj=canvas.getActiveObject();
		switch (justifyMode){
			case 0:
				currentobj.set('textAlign', 'left');
				canvas.renderAll();
			break;
			case 1:
				currentobj.set('textAlign', 'center');
				canvas.renderAll();
			break;
			case 2:
				currentobj.set('textAlign', 'right');
				canvas.renderAll();
			break;
		}
		
	}

	function toback(){
		var currentobj=canvas.getActiveObject();
		canvas.sendToBack(currentobj);
	}

	function tofront(){
		var currentobj=canvas.getActiveObject();
		canvas.bringToFront(currentobj);
	}

	function delobject() {
		var activeObject = canvas.getActiveObject();

		if (activeObject) {
			// Check if it's a group of objects
			if (activeObject.type === 'activeSelection') {
				var objectsInGroup = activeObject.getObjects();

				objectsInGroup.forEach(function(obj) {
					deleteObjectIfImage(obj);
					canvas.remove(obj); // Remove object from canvas
				});
				canvas.discardActiveObject(); // Discard the group selection
			} else {
				// Handle a single object
				deleteObjectIfImage(activeObject);
				canvas.remove(activeObject);
			}
			canvas.requestRenderAll();
		}
	}

	function deleteObjectIfImage(obj) {
		if (obj.type === 'image') {
			var imageUrl = obj._element.src;
			var parts = imageUrl.split('/');
			var finalImage = parts.pop();
			$.ajax({
				url: 'AJAX_delimage.php',
				type: 'POST',
				data: { imageUrl: finalImage },
				success: function(response) {
					
				},
				error: function(xhr, status, error) {
					console.error(error);
				}
			});
		}
	}


	function colorObject(){
		var colorchange=$('#colpick').spectrum('get');
		if (colorchange=='rgba(0, 0, 0, 0)'){colorchange='transparent';}
		
		var currentobj=canvas.getActiveObject();
		
		if (currentobj!==null && currentobj!==undefined){
			currentobj.set('fill',colorchange);
		} else {
			canvas.backgroundColor = colorchange;
		}
		canvas.requestRenderAll();
	}

	function setOutline(outlineSize){
		var currentobj=canvas.getActiveObject();
		var colorchange=$('#colpick').spectrum('get');
		if (currentobj.type==='i-text'){
			currentobj.set({stroke:colorchange, strokeWidth:outlineSize, strokeUniform:true});
		} else {
			currentobj.set({stroke:colorchange, strokeWidth:outlineSize, strokeUniform:true});
		}
		canvas.requestRenderAll();
	}



	function setShadow(){
		var currentobj=canvas.getActiveObject();
		if (currentobj){
			var colorchange=$('#colpick').spectrum('get');
			
			if (currentobj.type==='i-text'){
				currentobj.set('shadow', new fabric.Shadow('-2 2 2 rgba(0,0,0,0.6)'))
			} else {
				currentobj.set('shadow', new fabric.Shadow('-5 5 5 rgba(0,0,0,0.6)'))
			}
			canvas.requestRenderAll();
		}
	}

	function removeShadow(){
		var currentobj=canvas.getActiveObject();
		if (currentobj){
			currentobj.set('shadow', new fabric.Shadow(null))
			canvas.requestRenderAll();
		}
	}

	function toImage(){
		var imageDataUrl = canvas.toDataURL({
		  format: 'png',
		  quality: 1
		});
		var filename=$('#projectname').val();
		filename=filename.trim();
		if (filename==""){
			filename="canvas-image.png";
		} else {
			filename = filename.replace(/[^a-zA-Z0-9_-]/g, "");
			filename+='.png';
		}
		var link = document.createElement('a');
		link.href = imageDataUrl;
		link.download = filename;
		link.click();	
	}

	function colorToHex(color) {
		function rgbToHex(r, g, b) {
			return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
		}

		if (typeof color === 'string') {
			// If it's already a string (hex, rgb, rgba), use it as is
			return color;
		} else if (color && color._originalInput) {
			// Extract RGB values and convert to hex
			var r = Math.round(color._r);
			var g = Math.round(color._g);
			var b = Math.round(color._b);
			return rgbToHex(r, g, b);
		}
		return color; // Return the color as is if it doesn't match the above cases
	}

	function addText(){
		var textfont='Verdana';
		var font_store=$('#font_store').val();
		if (font_store!=""){
			textfont=font_store;
		}
		var colorchange=$('#colpick').spectrum('get');
		if (colorchange=='rgba(0, 0, 0, 0)'){colorchange='transparent';}
		var text = new fabric.IText('Editable Text', { left: 100, top: 100, fontFamily:textfont, fill:colorchange });
		canvas.add(text);
		canvas.renderAll;				
	}

	function cutObjects() {
		copiedObjects = [];
		var activeObject = canvas.getActiveObject();
		if (activeObject.type === 'activeSelection') {
			activeObject.forEachObject(function(obj) {
				var clonedObj = fabric.util.object.clone(obj);
				clonedObj.fill = colorToHex(clonedObj.fill);
				clonedObj.stroke = colorToHex(clonedObj.stroke);
				copiedObjects.push(clonedObj);
				canvas.remove(obj);
			});
			canvas.discardActiveObject();
		} else if (activeObject) {
			var cloned = fabric.util.object.clone(activeObject);
			cloned.fill = colorToHex(cloned.fill);
			cloned.stroke = colorToHex(cloned.stroke);
			copiedObjects.push(cloned);
			canvas.remove(activeObject);
		}
		
		canvas.requestRenderAll();
	}


	function copyObjects() {
		copiedObjects = [];

		var activeObject = canvas.getActiveObject();
		if (activeObject.type === 'activeSelection') {
			activeObject.forEachObject(function(obj) {
				var clonedObj = fabric.util.object.clone(obj);
				clonedObj.fill = colorToHex(clonedObj.fill);
				clonedObj.stroke = colorToHex(clonedObj.stroke);
				copiedObjects.push(clonedObj);
			});
		} else if (activeObject) {
			var cloned = fabric.util.object.clone(activeObject);
			cloned.fill = colorToHex(cloned.fill);
			cloned.stroke = colorToHex(cloned.stroke);
			copiedObjects.push(cloned);
		}
	
	}


	function pasteObjects() {
		var group = [];

		copiedObjects.forEach(function(obj) {
			obj.clone(function(clonedObj) {
				canvas.discardActiveObject();
				clonedObj.set({
					left: clonedObj.left + 10,
					top: clonedObj.top + 10,
					evented: true,
				});

				if (clonedObj.type === 'activeSelection') {
					clonedObj.forEachObject(function(obj) {
						canvas.add(obj);
						group.push(obj);
					});
				} else {
					canvas.add(clonedObj);
					group.push(clonedObj);
				}
			});
		});

		if (group.length > 1) {
			var newGroup = new fabric.ActiveSelection(group, { canvas: canvas });
			canvas.setActiveObject(newGroup);
		} else if (group.length === 1) {
			canvas.setActiveObject(group[0]);
		}

		canvas.requestRenderAll();
	}



	// Handle Canvas Resize :

	var canvasContainer = document.getElementById('canvasContainer');
	var resizeHandle = document.getElementById('resizeHandle');


	var startWidth, startHeight, startX, startY;

	resizeHandle.addEventListener('mousedown', function(e) {
		startWidth = canvas.getWidth();
		startHeight = canvas.getHeight();
		startX = e.clientX;
		startY = e.clientY;
		document.documentElement.style.cursor = 'nwse-resize';
		document.addEventListener('mousemove', resizeCanvas, false);
		document.addEventListener('mouseup', stopResize, false);
	});

	$('#canvasx, #canvasy').on('change', function() {
		var newWidth = parseInt($('#canvasx').val());
		var newHeight = parseInt($('#canvasy').val());

		// Check for valid numbers
		if (!isNaN(newWidth) && !isNaN(newHeight) && newWidth > 0 && newHeight > 0) {
			newWidth=parseInt(newWidth);
			newHeight=parseInt(newHeight);
			canvasContainer.style.width = newWidth + 'px';
			canvasContainer.style.height = newHeight + 'px';

			canvas.setWidth(newWidth);
			canvas.setHeight(newHeight);
			canvas.renderAll();
		}
	});


	function resizeCanvas(e) {
		var newWidth, newHeight;

		if (e.shiftKey || e.ctrlKey || e.metaKey) {
			// Calculate the new size while maintaining aspect ratio
			var aspectRatio = startWidth / startHeight;
			var delta = Math.min(e.clientX - startX, e.clientY - startY);
			newWidth = startWidth + delta;
			newHeight = startHeight + delta / aspectRatio;
		} else {
			// Regular resizing
			newWidth = startWidth + e.clientX - startX;
			newHeight = startHeight + e.clientY - startY;
		}
		updateCanvasSize(newWidth, newHeight);
	}

	function updateCanvasSize(newWidth, newHeight) {
		canvasContainer.style.width = newWidth + 'px';
		canvasContainer.style.height = newHeight + 'px';

		canvas.setWidth(newWidth);
		canvas.setHeight(newHeight);
		canvas.renderAll();
		if (newWidth<10){newWidth=10};
		if (newHeight<10){newHeight=10};
		var newWidth=parseInt(newWidth);
		var newHeight=parseInt(newHeight);
		$('#canvasx').val(newWidth);
		$('#canvasy').val(newHeight);
	}

	function stopResize() {
		document.documentElement.style.cursor = '';
		document.removeEventListener('mousemove', resizeCanvas, false);
		document.removeEventListener('mouseup', stopResize, false);
	}


$('#presetsize').change(function(){
	var size_preset=$(this).val();
	var parts = size_preset.split('x');
	var presetX = parseInt(parts[0], 10);
	var presetY = parseInt(parts[1], 10);
	$('#canvasx').val(presetX).trigger('change');
	$('#canvasy').val(presetY).trigger('change');
	

});

function sizeObject(sizetype) {
	var currentobj=canvas.getActiveObject();
	if (currentobj){
		if (sizetype==0 && (currentobj.scaleX > 0.10 && currentobj.scaleY > 0.10)) {
			currentobj.set({
				scaleX: currentobj.scaleX * 0.8,
				scaleY: currentobj.scaleY * 0.8
			});
		} else if (sizetype==1) {
			currentobj.set({
				scaleX: currentobj.scaleX * 1.2,
				scaleY: currentobj.scaleY * 1.2
			});			
		}
		canvas.renderAll();
		
	}
}

function selectFont(fontselect) {
	$('#font_store').val(fontselect);
	var currentobj=canvas.getActiveObject();
	if (currentobj && currentobj.type==="i-text"){
		currentobj.set('fontFamily',fontselect);
		canvas.renderAll();
	}
}

function deselectObjects() {
    canvas.discardActiveObject();
    canvas.requestRenderAll();	
}

$(window).keydown(function(e) {
    if (["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement.tagName)) {
        return;
    }
    var activeObject = canvas.getActiveObject();
    if (activeObject) {
        if ([37, 38, 39, 40].includes(e.which)) {
            e.preventDefault(); // Prevent scrolling
            nudgeObject(e, activeObject);
        } else if (e.which === 46) {
            e.preventDefault();
            delobject();
        } else if (e.which === 67 && e.ctrlKey) {
			e.preventDefault();
			copyObjects();
		} else if (e.which === 86 && e.ctrlKey) {
			e.preventDefault();
			pasteObjects();
		} else if (e.which === 88 && e.ctrlKey) {
			e.preventDefault();
			cutObjects();
		} else if (e.which === 68 && e.ctrlKey && e.altKey) {
			e.preventDefault();
			deselectObjects();
		} else if (e.which === 33 && e.ctrlKey && e.altKey) {
			e.preventDefault();
			tofront();
		} else if (e.which === 34 && e.ctrlKey && e.altKey) {
			e.preventDefault();
			toback();
		} else if (e.which === 84 && e.ctrlKey && e.altKey) {
			e.preventDefault();
			addText();
		} else if (e.which === 70 && e.ctrlKey && e.altKey) {
			e.preventDefault();
			colorObject();
		}  else if (e.which === 109 && e.ctrlKey && e.altKey) {
			e.preventDefault();
			sizeObject(0);
		}  else if (e.which === 107 && e.ctrlKey && e.altKey) {
			e.preventDefault();
			sizeObject(1);
		}  else if (e.which === 80 && e.ctrlKey && e.altKey) {
			e.preventDefault();
			toImage();
		}
		
    }
    
    
});

function nudgeObject(e, activeObject) {
    var isShiftPressed = e.shiftKey;
    var nudgeAmount = isShiftPressed ? 10 : 1;

    switch (e.which) {
        case 37:
            activeObject.set('left', activeObject.left - nudgeAmount);
            break;
        case 38:
            activeObject.set('top', activeObject.top - nudgeAmount);
            break;
        case 39:
            activeObject.set('left', activeObject.left + nudgeAmount);
            break;
        case 40:
            activeObject.set('top', activeObject.top + nudgeAmount);
            break;
    }

    activeObject.setCoords();
    canvas.requestRenderAll();
	updatePositionInputs(activeObject);
}



$('#btnGenerate').click(function(){
		showOverlay(true);
		var imageprompt=$('#imageprompt').val();
		var reviseprompt=$('#reviseprompt').val();
		var imagesize=$('#imagesize').val();
		var imagetype=$('#imagetype').val();
		var imagestyle=$('#imagestyle').val();
		
		var data = {
		  imageprompt: imageprompt,
		  reviseprompt: reviseprompt,
		  imagesize: imagesize,
		  imagetype: imagetype,
		  imagestyle: imagestyle
		};
		$('#overlay-message').text('Asking AI to generate image - Please wait...');	
		$.ajax({
		  url: 'AJAX_aiengine.php',
		  type: 'POST',
		  data: data,
		  success: function(response) {
			if (response=="NOUSERKEY") {
				console.log("ERROR WITH AJAX CALL 2!!");
				showOverlay(false);
				$('#userkeyModal').modal('show');	
			} else {
				showOverlay(false);
				
				var userid=$('#userid').val();
				var imagefile='u_img/'+userid+'/'+response;
				
				fabric.Image.fromURL(imagefile, function(imgInstance) {
				  imgInstance.set({
					left: 0,
					top: 0,
					angle: 0,
					opacity: 1
				  });
				  canvas.add(imgInstance);
				});								
				
				var add2=$('#add2').val();
				if (add2==1){
					var wordCount=1;
					$.ajax({
						url: "AJAX_creditchange.php",
						type: "POST",
						data: { wordCount: wordCount },
						success: function(response){
							$('#usercredits').text(response);
						},
						error: function(error){
							console.log("Error:", error);
						}
					});
				}						
			}
			
		  },
		  error: function(xhr, status, error) {
			showOverlay(false);
			$('#s2errorModal').modal('show');
		  }
		});	
	
});


function getCount(){
	tinyeditor = tinymce.activeEditor;
	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>