<?php
function random_string($length) {
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));

    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }

    return $key;
}
function redirect($new_location) {
	header("Location: " . $new_location);
	exit;
}
function password_encrypt($password) {
	$hash_format = "$2y$10$";   
	$salt = generate_salt();
	$format_and_salt = $hash_format . $salt;
	$hash = crypt($password, $format_and_salt);
	return $hash;
}
function generate_salt() {
	$unique_random_string = md5(uniqid(mt_rand(), true));
	$base64_string = base64_encode($unique_random_string);
	$modified_base64_string = str_replace('+', '.', $base64_string);
	$salt = substr($modified_base64_string, 0, 22);
	return $salt;
}
function FetchWebsiteName($mysqli){ //Used to return the website name 
$results = $mysqli->query("SELECT StoreName FROM MiscInfo");


while($row = $results->fetch_array()) {

    return $row["StoreName"];


}   	
}
function FetchNumber($mysqli){ //Used to return the website name 
$results = $mysqli->query("SELECT ContactNumber FROM MiscInfo");

 
while($row = $results->fetch_array()) {

    return $row["ContactNumber"];


}   	
}
function FetchAddress($mysqli){ //Used to return the website name 
$results = $mysqli->query("SELECT Address FROM MiscInfo");

 
while($row = $results->fetch_array()) {

    return $row["Address"];


}   	
}
function FetchEmail($mysqli){ //Used to return the website name 
$results = $mysqli->query("SELECT ContactEmail FROM MiscInfo");


while($row = $results->fetch_array()) {

    return $row["ContactEmail"];


}   	
}
function FetchWebsiteURL($mysqli, $DBUser){ //Used to return the website name 
$results = $mysqli->query("SELECT Domain FROM Websites WHERE DBName = '$DBUser'");


while($row = $results->fetch_array()) {

    return $row['Domain'];


}   	
}
function DynamicNavBarSelector($Links,$FilterWord,$ActiveWord, $CurrentPage){
			 $NavBar = explode('.php',$Links);
			
			 foreach($NavBar as $Item){
				
			 	if(strpos($Item.'.php',$CurrentPage) !==false){
					  if(strpos($FilterWord,'/') !==false){
						  $ActWord = explode('/',$ActiveWord);
						   $Filtering = explode('/',$FilterWord);
						
							  if(strpos($Item,$Filtering[1]) !== false){
								 
							$Nav[] = str_replace($Filtering[1],$ActWord[1],$Item); 
							  }elseif(strpos($Item,$Filtering[0]) !== false){
							$Nav[] = str_replace($Filtering[0],$ActWord[0],$Item);
							  }else{
								 $Nav[] = $Item; 
							  }
						  
					}else{
						
						$Nav[] = str_replace($FilterWord,$ActiveWord,$Item);
					  }
						  
					  
				}else{
					$Nav[] = $Item;
				}
				  				 
			 }
			  
			   return implode('.php',$Nav);
			   
}
function UpdateNote($mysqli, $ID, $Title,$Description){ //Used to return the website name 
$datum = new DateTime();
$startTime = $datum->format('Y-m-d H:i:s');

$stmt = $mysqli->prepare("UPDATE Notes SET Note = '$Description', Title = '$Title', Date = '$startTime' WHERE ID = '$ID'");
$stmt->execute(); 

return;
}
function DeleteNote($mysqli, $ID){ //Used to return the website name 
$stmt = $mysqli->prepare("DELETE FROM Notes WHERE ID = '$ID'");
$stmt->execute(); 

return;
}

function AddNote($mysqli){ //Used to return the website name 
$datum = new DateTime();
$startTime = $datum->format('Y-m-d H:i:s');
mysqli_query($mysqli,"INSERT INTO Notes (Note,Title,Date) VALUES ('Blank Note','Untitled','$startTime')");

return;
}
function FetchNotes($mysqli){
	$results = $mysqli->query("SELECT * FROM Notes");


while($row = $results->fetch_array()) {
$Notes[] = '<div class="note-item media current fade in">
                    <button class="close">×</button>
                    <div class="SingleNote" id="'.$row['ID'].'">
                      <div>
                        <p class="note-name">'.$row['Title'].'</p>
                      </div>
                      <p class="note-desc hidden">'.$row['Note'].'</p>
                      <p><small>'.date('j M Y g:i A', strtotime($row['Date'])).'</small></p>
                    </div>
                  </div>';
    


}   	
return $Notes;
}
function CreatePages($mysqli, $ItemsPerPage, $TableDB, $Type){

$FFF = DisplayTable($mysqli, $TableDB);		
// Here we have the total row count
$rows = $FFF[2];
// This is the number of results we want displayed per page
$page_rows =  $ItemsPerPage;
// This tells us the page number of our last page
if($ItemsPerPage == 'All'){
	$page_rows = $FFF[2];
}
$last = ceil($rows/$page_rows);

// This makes sure $last cannot be less than 1
if($last < 1){
	$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_SESSION['PageNumber'])){
	$pagenum = preg_replace('#[^0-9]#', '', $_SESSION['PageNumber']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) { 
    $pagenum = 1; 
} else if ($pagenum > $last) { 
    $pagenum = $last; 
}
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;

// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$sql =  $Query." $limit";
//$sql = "SELECT t.*, t2.SupplierID, t2.SupplierName, t3.CategoryName, t3.CategoryID FROM Products AS t join Suppliers t2 on t.SupplierID = t2.SupplierID JOIN Categories t3 ON t.CategoryID = t3.CategoryID WHERE t3.CategoryName = '$Cate' $limit";	
// This shows the user what page they are on, and the total number of pages
$textline1 = "Testimonials (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
	/* First we check if we are on page one. If we are then we don't need a link to 
	   the previous page or the first page so we do nothing. If we aren't then we
	   generate links to the first page, and to the previous page. */

	if ($pagenum > 1) {
        $previous = $pagenum - 1;
		$paginationCtrls .= '<li class="paginate_button previous" aria-controls="DataTables_Table_0" tabindex="0" id="DataTables_Table_0_previous"><a href="'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&pn='.$previous.'"><i class="fa fa-angle-left"></i></a></li>';
		// Render clickable number links that should appear on the left of the target page number
		for($i = $pagenum-6; $i < $pagenum; $i++){
			if($i > 0){
		        $paginationCtrls .= ' <li class="paginate_button" aria-controls="DataTables_Table_0" tabindex="0"><a href="'.'?'.$_SERVER['QUERY_STRING'].'&pn='.$i.'">'.$i.'</a></li>';
			}
	    }
    }
	// Render the target page number, but without it being a link
	$paginationCtrls .= '<li class="paginate_button active" aria-controls="DataTables_Table_0" tabindex="0"><a href="#">'.$pagenum.'</a></li>';
	// Render clickable number links that should appear on the right of the target page number
	for($i = $pagenum+1; $i <= $last; $i++){
		$paginationCtrls .= '<li class="paginate_button" aria-controls="DataTables_Table_0" tabindex="0"><a href="'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&pn='.$i.'">'.$i.'</a></li>';
		if($i >= $pagenum+4){
			break;
		}
	}
	// This does the same as above, only checking if we are on the last page, and then generating the "Next"
    if ($pagenum != $last) {
        $next = $pagenum + 1;
        $paginationCtrls .= ' <li class="paginate_button next" aria-controls="DataTables_Table_0" tabindex="0" id="DataTables_Table_0_next"><a href="'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&pn='.$next.'"><i class="fa fa-angle-right"></i></a></li>';
    } 
	 
                               
}

$list = '';

return array(DisplayTable($mysqli, $TableDB, $limit, $Type), $paginationCtrls);


	
}
function DeleteRow($mysqli,$TableDB,$ID){
	
	
		$result = $mysqli->query("SELECT * FROM TableManager WHERE TableName = '$TableDB' AND ActiveTable = 'True'");
						while($rows = $result->fetch_array()) {
							$DeleteRule = $rows['DelRow'];
							$Fields = $rows['Fields'];
							
						}

						$AllFields = explode(',',$Fields);

						if(isset($DeleteRule)
						&& !empty($DeleteRule)){
							$stmt = $mysqli->prepare("UPDATE ".$TableDB." SET ".$DeleteRule." = '0' WHERE ".$AllFields[0]." = '$ID'");
							$stmt->execute(); 	
						}else{
							$stmt = $mysqli->prepare("DELETE FROM ".$TableDB." WHERE ".$AllFields[0]." = '$ID' ");
							$stmt->execute(); 		
						}
						
						return 'Deleted';
}
function DisplayEntry($mysqli,$TableName,$HTML,$ID){
	$result = $mysqli->query("SELECT * FROM TableManager WHERE TableName = '$TableName' AND ActiveTable = 'True'");
	while($row = $result->fetch_array()) {
		$AllFieldsNames = $row['Fields'];
		$VisibleFieldsSingle = $row['VisibleFields'];	
		$LinkedTablesSingle = $row['LinkedTables'];
		$VisibleFieldValuesSingle = $row['VisibleFieldsValues'];
	}
	//Converst string from DB into usable arrays
	$AllFieldsArr = explode(',',$AllFieldsNames);
	$VisibleFields = explode(',',$VisibleFieldsSingle);
	$VisibleFieldsValues = explode(',',$VisibleFieldValuesSingle);
	$LinkedTables = explode('/',$LinkedTablesSingle);

	//Set SQL Query to encompass HTML
	if(isset($ID)
		&& !empty($ID)){
		//If an ID is passed
		$NewHTML .= '<?php $result = $connecDB->query("SELECT * FROM '.$TableName.' WHERE '.$AllFieldsArr[0].' = \'$ID\'");
	if(mysqli_num_rows($result) > 0){
		while($row = $result->fetch_array()) { ?>';

	}else{
		//If no ID is passed select all contents from DB
		$NewHTML .= '<?php $result = $connecDB->query("SELECT * FROM '.$TableName.'");
		if(mysqli_num_rows($result) > 0){
		while($row = $result->fetch_array()) { ?>';
	}


	//
	$EditHTML = $HTML;

	foreach($VisibleFields as $Field){
		//Loops through all fields and replaces them with data from DB where possible.
		$EditHTML = str_replace('FIELDNAME-'.$Field,'<?php echo $row[\''.$Field.'\']; ?>',$EditHTML);
	}


	foreach($LinkedTables as $OutputLinked){
		
		$Type = explode('-',$OutputLinked); // Type[0] = Type of query
		$LinkedName = $Type[0]; //Table Name of Linked table
$AllTypes .= $Type[0];
		//If it's a linked ImageProducts Table
		if($Type[0] == 'ImageProducts'
			&& isset($ID)
			&& !empty($ID)){
			

				//$LinkedResult[0][$Key] = YES if image is default/thumbnail
				//$Value = Image URL
				//Start Query
				$LinkedQueryStart = '<?php $LinkedResult = FetchLinkedTable($connecDB,\''.$LinkedName.'\',array(\''.$OutputLinked.'\'),\'ImageProducts\', $ID);	foreach($LinkedResult[0] as $Key => $Value){ ?>';
				$EditHTML = str_replace('LINKEDSTART-'.$LinkedName,$LinkedQueryStart,$EditHTML);
				$LinkedQueryValue = '<?php echo $Value; ?>';
				$EditHTML = str_replace('LINKEDVALUE-'.$LinkedName,$LinkedQueryValue,$EditHTML);
				$LinkedQueryEnd = '<?php } ?>';
				$EditHTML = str_replace('LINKEDEND-'.$LinkedName,$LinkedQueryEnd,$EditHTML);

			
		}elseif($Type[0] == 'ProductOptions'
			&& isset($ID)
			&& !empty($ID)){
			

				//$LinkedResult[0][$Key] = YES if image is default/thumbnail
				//$Value = Image URL
				//Start Query
				$LinkedQueryStart = '<?php $LinkedResult = FetchLinkedTable($connecDB,\''.$LinkedName.'\',array(\''.$OutputLinked.'\'),\'ProductOptions\', $ID); if(isset($LinkedResult) && !empty($LinkedResult)){	foreach($LinkedResult[0][3] as $Key => $Value){ ?>';
				$EditHTML = str_replace('LINKEDSTART-'.$LinkedName,$LinkedQueryStart,$EditHTML);
				$LinkedQueryValue = '<?php echo $Value; ?>';
				$EditHTML = str_replace('LINKEDOPTNAME-'.$LinkedName,$LinkedQueryValue,$EditHTML);
				//Option Stock variables set to $_SESSION['OptionStocks']; 
				//Option Cost variables set to $_SESSION['OptionCosts'];
				$LinkedQueryValue = '<?php $Opts = explode(\',\',$LinkedResult[0][2][$Key]); $_SESSION[\'OptionCosts\'] = explode(\',\',$LinkedResult[0][1][$Key]); $_SESSION[\'OptionStocks\'] = explode(\',\',$LinkedResult[0][0][$Key]);  foreach($Opts as $Option){?>';
				$EditHTML = str_replace('LINKEDOPTIONSTART-'.$LinkedName,$LinkedQueryValue,$EditHTML);
				$LinkedQueryValue = '<?php echo $Option; ?>';
				$EditHTML = str_replace('LINKEDOPTION-'.$LinkedName,$LinkedQueryValue,$EditHTML);
				$LinkedQueryValue = '<?php } ?>';
				$EditHTML = str_replace('LINKEDOPTIONEND-'.$LinkedName,$LinkedQueryValue,$EditHTML);
				$LinkedQueryEnd = '<?php } } ?>';
				$EditHTML = str_replace('LINKEDEND-'.$LinkedName,$LinkedQueryEnd,$EditHTML);
		}else{
			//For dynamic text - may not work
				$LinkedQueryStart = '<?php $LinkedResult = FetchLinkedTable($connecDB,\''.$LinkedName.'\',array(\''.$OutputLinked.'\'),\''.$Type[0].'\', $ID); if(isset($LinkedResult) && !empty($LinkedResult)){	foreach($LinkedResult[0] as $Key => $Value){ ?>';
				$EditHTML = str_replace('LINKEDSTART-'.$LinkedName,$LinkedQueryStart,$EditHTML);
				$LinkedQueryValue = '<?php if($LinkedResult[1][$Key] == $row[\''.$LinkedName.'\']){ echo $Value; } ?>';
				$EditHTML = str_replace('LINKEDVALUE-'.$LinkedName,$LinkedQueryValue,$EditHTML);
				$LinkedQueryEnd = '<?php } } ?>';
				$EditHTML = str_replace('LINKEDEND-'.$LinkedName,$LinkedQueryEnd,$EditHTML);


		}

	}


	//Please complete edited HTML into output, along with closing the SQL Query
	$NewHTML .= $EditHTML;

	$NewHTML .= '<?php } } ?>';




return $NewHTML;

}
function DisplayTable($mysqli, $TableDB, $Limit, $Type){
	$Main = '<tbody>';

					   /*$results = $connecDB->query("SELECT * FROM ".$TableDB);

					while($row = $results->fetch_array()) {
						
						foreach($row as $key => $item){
						$ColumnNames[] = $key;
						$RowData[][] = $item;	
						}
					}  */
					if($TableDB == 'Products'){
						$Total = 0;
						if(isset($Limit)
						&& !empty($Limit)){
						$results = $mysqli->query("SELECT ProductID,ProductName,ProductPrice,ProductShortDesc,SKU FROM ".$TableDB." WHERE ProductLive = '1'".$Limit);
						}else{
						$results = $mysqli->query("SELECT ProductID,ProductName,ProductPrice,ProductShortDesc,SKU FROM ".$TableDB." WHERE ProductLive = '1'");	
						}
						$ColumnNamez = $mysqli->query("SELECT VisibleFields,FieldNames FROM TableManager WHERE TableName = 'Products'");	
						while($row = $ColumnNamez->fetch_array()) {
							$VisiFiel = $row['VisibleFields'];
							$FielNams = $row['FieldNames'];
						}
						$VisiFielArr = explode(',',$VisiFiel);
						$FielNamsArr = explode(',',$FielNams);
						foreach($VisiFielArr as $Key => $Val){
							if($Val == 'SKU'){
								$Disp = $FielNamsArr[$Key];
							}
						}
						$Columns = '<thead><tr><th class="ColumnName" id="ProductID">ID</th><th class="ColumnName" id="ProductName">Name</th ><th class="ColumnName" id="ProductPrice">Price</th><th class="ColumnName" id="ProductShortDesc">Short Description</th><th class="ColumnName" id="SKU">'.$Disp.'</th><th class="text-right">Action</th></tr></thead>';
							while($row = $results->fetch_array()) {
								$Total++;
								$Main .= '<tr>';
								foreach($row as $Key => $item){
									if(!is_numeric($Key)){
								$Main .= '<td>'.CleanString($item).'</td>';	
									}
								} 
								if(isset($Type)
								&& !empty($Type)){
									if($Type == 'Info'){
									$Main .= '<td class="text-right"><a class="btn btn-sm btn-default EditItem" href="EditOrders.php?ID='.$row['ProductID'].'" href="javascript:;"><i class="icon-note"></i></a> <a class=" btn btn-sm btn-danger DeleteRow" id="'.$row['ProductID'].'" ><i class="icons-office-52"></i></a>
                        </td></tr>';
									}
								}else{
								$Main .= '<td class="text-right"><a class="btn btn-sm btn-default EditItem" href="EditItem.php?ID='.$row['ProductID'].'" href="javascript:;"><i class="icon-note"></i></a>  <a class=" btn btn-sm btn-danger DeleteRow" id="'.$row['ProductID'].'" ><i class="icons-office-52"></i></a>
                        </td></tr>';
								}
							}
					}else{
					$result = $mysqli->query("SELECT * FROM TableManager WHERE TableName = '$TableDB' AND ActiveTable = 'True'");
						while($rows = $result->fetch_array()) {
							$AllFields = explode(',',$rows['Fields']);
							$FieldsShown[] = $rows['VisibleFields'];
							$FieldsValues[] = $rows['VisibleFieldsValues'];
							$FieldNames[] = $rows['FieldNames'];

						}
						$Total = 0;
						$MySqliQuery .= 'SELECT '.$AllFields[0].','.implode(',',$FieldsShown).' FROM '.$TableDB;	
						if($TableDB == 'Products'){
							$MySqliQuery .= ' WHERE ProductLive = 1';
						}elseif($TableDB == 'Orders'){
							$MySqliQuery .= ' WHERE ActiveOrder = 1';
						}
						if(isset($Limit)
						&& !empty($Limit)){
						//$MySqliQuery .= $Limit;	
						}
						$Columns = '<thead><tr>';
						$ColumnNames = explode(',',implode('',$FieldNames));
						foreach($ColumnNames as $Col){
						$Columns .= '<th class="ColumnName" id="'.$Col.'">'.$Col.'</th>';	
						}
						$Columns .= '<th class="text-right">Action</th></tr></thead>';
						$results = $mysqli->query($MySqliQuery);
						while($row = $results->fetch_array()) {
								$Total++;
								$Main .= '<tr>';
								foreach($row as $Key => $item){
									if(!is_numeric($Key)){
										if($Key !== $AllFields[0]){
											$Main .= '<td>'.$item.'</td>';	
										}
									}
								} 
								if(isset($Type)
								&& !empty($Type)){
									if($Type == 'Info'){
									$Main .= '<td class="text-right"><a class="btn btn-sm btn-default EditItem" href="EditOrders.php?ID='.$row[$AllFields[0]].'" href="javascript:;"><i class="icon-note"></i></a><a class="btn btn-sm btn-success" href="ViewEntry.php?ID='.$row[$AllFields[0]].'" href="javascript:;"><i class="fa fa-eye"></i></a>   <a class=" btn btn-sm btn-danger DeleteRow" id="'.$row[$AllFields[0]].'" ><i class="icons-office-52"></i></a>
                        </td></tr>';
									}
								}else{

								$Main .= '<td class="text-right">';
if($TableDB=='Newsletters'){
	$NID = $row[$AllFields[0]];
$resultsa = $mysqli->query("SELECT * FROM NewsletterStats WHERE NewsletterID = '$NID'");
if(mysqli_num_rows($resultsa) > 0){ 
$Main .= '<a class="btn btn-sm btn-success" href="ViewNewsletter.php?ID='.$row[$AllFields[0]].'" href="javascript:;"><i class="fa fa-eye"></i></a><a class=" btn btn-sm btn-danger DeleteRow" id="'.$row[$AllFields[0]].'" ><i class="icons-office-52"></i></a>
                        </td></tr>';
}else{

	$Main .='<a class="btn btn-sm btn-default EditItem" href="Newsletter.php?ID='.$row[$AllFields[0]].'" href="javascript:;"><i class="icon-note"></i></a>  <a class=" btn btn-sm btn-danger DeleteRow" id="'.$row[$AllFields[0]].'" ><i class="icons-office-52"></i></a>
                        </td></tr>';
}
}else{
								$Main .='<a class="btn btn-sm btn-default EditItem" href="EditItem.php?ID='.$row[$AllFields[0]].'" href="javascript:;"><i class="icon-note"></i></a>  <a class=" btn btn-sm btn-danger DeleteRow" id="'.$row[$AllFields[0]].'" ><i class="icons-office-52"></i></a>
                        </td></tr>';


}
								}
								
						}
					}
						 
				
		$Main .= '</tbody>';
					 	return array($Columns, $Main, $Total);
}
function FetchAdminPages($mysqli,$Page){
	if($Page == 'Edits'){
		$results = $mysqli->query("SELECT Name,FileName, LinkVar FROM AdminPanel WHERE Permission = 'True' AND ClassName = '$Page'");

while($row = $results->fetch_array()) {
	$Tables[$row['Name']] = $row['FileName'].$row['LinkVar'];

}   	

return $Tables;
	}else{
			$results = $mysqli->query("SELECT Name,FileName, LinkVar FROM AdminPanel WHERE Permission = 'True' AND ClassName = '$Page'");

while($row = $results->fetch_array()) {
	$Tables[$row['Name']] = $row['FileName'].$row['LinkVar'];
}
	return $Tables;
	}
}
function FetchTableLinks($mysqli){
	$results = $mysqli->query("SELECT Name,FileName, LinkVar FROM AdminPanel WHERE Permission = 'True' AND ClassName = 'Table'");

while($row = $results->fetch_array()) {
	$Tables[$row['Name']] = $row['FileName'].$row['LinkVar'];

}   	

return $Tables;
}
function MatchTableID($mysqli, $SelectedTable){
	$SlcTb = '?ID='.$SelectedTable;
	$results = $mysqli->query("SELECT Name,TableName FROM AdminPanel WHERE Permission = 'True' AND ClassName = 'Table' AND LinkVar = '$SlcTb'");

while($row = $results->fetch_array()) {
	return array($row['Name'], $row['TableName']);

}  
	
}
function MatchTableIDVar($mysqli, $SelectedTable,$Type){
	$SlcTb = '?ID='.$SelectedTable;
	$results = $mysqli->query("SELECT Name,TableName FROM AdminPanel WHERE Permission = 'True' AND ClassName = '$Type' AND LinkVar = '$SlcTb'");

while($row = $results->fetch_array()) {
	return array($row['Name'], $row['TableName']);

}  
	
}
function SendMessage($mysqli, $ReceiveID, $SendID,$Message){ //Used to return the website name 
$datum = new DateTime();
$startTime = $datum->format('Y-m-d H:i:s');
mysqli_query($mysqli,"INSERT INTO LiveChat (Message,Date,ReceivedID,SentID,MarkRead) VALUES ('$Message','$startTime','$ReceiveID','$SendID','False')");

return;
}
function FetchUsername($mysqli, $Email){ //Used to return the website name 
$results = $mysqli->query("SELECT FirstName FROM Accounts WHERE Email = '$Email'");


while($row = $results->fetch_array()) {

    return $row["FirstName"];


}   	
}
function FetchProfileImage($mysqli, $Email){ //Used to return the website name 
$results = $mysqli->query("SELECT Profile FROM Accounts WHERE Email = '$Email'");


while($row = $results->fetch_array()) {

    return $row["Profile"];


}   	
}
function FetchAccountImage($mysqli, $ID){ //Used to return the website name 
$results = $mysqli->query("SELECT Profile FROM Accounts WHERE AccountID = '$ID'");


while($row = $results->fetch_array()) {

    return $row["Profile"];


}   	
}
function FetchLinkedTable($mysqli,$TableName,$LinkedTables,$ColumnName, $ID){
	//LinkedTables = string of info detailing which table is linked and how

	foreach($LinkedTables as $Key => $LinkedItem){
		$LinkHead = explode('-',$LinkedItem);
		if($LinkHead[0] == $ColumnName){
		break;	
		}
	}

	if(strpos($LinkHead[1],'*') !== false){//Checks for multi-layer sql (If the query will go further than 2 tables)

		$Strictness = explode('(',$LinkHead[1]);
		$SetTable = explode('*',$Strictness[0]);
		//LinkHead[0] = Product ID
		//TableArr[key][0] = ImageProducts/Images
		//ColumnArr[key][0] = ProductID/ImageID
		//Joiner[key] = ImageID/Def/FileLocation
		$MysqlQuery = 'SELECT ';
		$Letter = 'b';
		$Count = 0;
		foreach($SetTable as $Key =>$Test){
			$TableArr[$Key] = explode('@',$Test);
			$ColumnArr[$Key] = explode('>',$TableArr[$Key][1]);
			$Joiner[$Key] = explode(',',$ColumnArr[$Key][1]);
			if(count($Joiner[$Key])>1){
					if($Count<1){
						$MysqlQuery .= $Letter.'.'.implode(','.$Letter.'.',$Joiner[$Key]);
					}else{
						$MysqlQuery .=','. $Letter.'.'.implode(','.$Letter.'.',$Joiner[$Key]);
					}
			}elseif($Count>0){
				$MysqlQuery .= ','.$Letter.'.'.implode('',$Joiner[$Key]);
			}else{
				$MysqlQuery .= $Letter.'.'.implode('',$Joiner[$Key]);
			}
			
			$Count++;
			$Letter++;
		}
		
		$MysqlQuery .= ' FROM '.$TableName.' AS a';
		$OriginalLetter = 'a';
		$Letters = 'b';
		foreach($SetTable as $Key => $Test){
			$MysqlQuery .= ' INNER JOIN '.$TableArr[$Key][0].' AS '.$Letters.' ON '.$Letters.'.'.$ColumnArr[$Key][0].' = '.$OriginalLetter.'.'.$ColumnArr[$Key][0];

			$Letters++;
			$OriginalLetter++;
			//$MysqlQuery .= 'INNER JOIN '.$TableArr[$Key][0].' AS '.$Letter.' ON a.'.$LinkHead[0].' = '.$Letter.'.'.$ColumnName[$Key][0];
			//$TableArr[$Key][0]; = Joined Tables
			
			
			
			//$results = $mysqli->query("SELECT a.ProductID, c.FileLocation FROM Products AS a INNER JOIN ImageProducts AS b ON a.ProductID = b.ProductID INNER JOIN Images AS c ON b.ImageID = c.ImageID WHERE a.ProductID = '4'"); IF($ID
			//echo $ColumnArr[$Key][1];
		}
		if(isset($ID)
		&& !empty($ID)){
		$MysqlQuery .= ' WHERE a.'.$ColumnArr[0][0].'='.$ID;
		}
		//echo $MysqlQuery.'@@@';

		$results = $mysqli->query($MysqlQuery);

		//return $MysqlQuery;
	//$results = $mysqli->query("SELECT b.".$Strictness[0].",b.".$FetchedColumn[0]." FROM ".$TableName." AS a INNER JOIN ".$Table[0]." AS b ON a.".$LinkHead[0]." = b.".$FetchedColumn[0]);

	}else{
		$Table = explode('@',$LinkHead[1]);
		$FetchedColumn = explode('>',$Table[1]);
		$Strictness = explode('(',$FetchedColumn[1]);
		if($Strictness[1] == 'Strict)'){//Should be useful for selecting images via product table
		
		 $Selection = str_replace(',',',b.',$Strictness[0]);
		 
		
		
		$MysqlQuery .= 'SELECT b.'.$Selection.',b.'.$FetchedColumn[0].' FROM '.$TableName.' AS a INNER JOIN '.$Table[0].' AS b ON a.'.$LinkHead[0].' = b.'.$FetchedColumn[0];
		
		if(isset($ID)
		&& !empty($ID)){
		$MysqlQuery .= ' WHERE a.'.$LinkHead[0].'='.$ID;
		}
		$results = $mysqli->query($MysqlQuery);
		}else{
			if(strpos($Table[0],'Categories') !== false
			or $Table[0] == 'Categories'){//Custom Query for categories to only show categories without a child.
				$results = $mysqli->query("SELECT ".$Strictness[0].",".$FetchedColumn[0].", CategoryLevel FROM ".$Table[0]);
			}else{
				$results = $mysqli->query("SELECT ".$Strictness[0].",".$FetchedColumn[0]." FROM ".$Table[0]);
				
			}
		}
		
	}

	

	if(mysqli_num_rows($results) > 0){
		$County = 0;
		while($row = $results->fetch_array()) {
		
			if(strpos($Table[0],'Categories') !==false
				or $Table[0] == 'Categories'){
				$Level[] = $row['CategoryLevel'];
				$DataGroup[$row[$Strictness[0]]] = $row[$FetchedColumn[0]];	
			}elseif($LinkHead[0] == 'ImageProducts'){
				
				$DataSet[] = $row['FileLocation'];
				$DataID[] = $row['ImageID'];	
				$Extra[] = $row['Def'];
			}elseif($TableArr[0][0] == 'ProductOptions'){
				$DataSet[0][] = $row['OptionStockLevels'];
				$DataSet[1][] = $row['OptionPrices'];
				$DataSet[2][] = $row['OptionName'];
				$DataSet[3][] = $row['OptionGroupName'];
				$DataID[] = $row['OptionID'];
				$County++;
			}elseif($TableArr[0][0] == 'ProductOptions'){
				
				$DataSet[] = $row['OptionName'];
				
				$DataID[] = $row['OptionGroupName'];	
				$Extra[] = $row['OptionStockLevels'];
			}elseif($Table[0] == 'FeaturedProducts'){
				
				$DataSet = $row['Discount'];
				
				$DataID = $row['FeaturePrice'];	

			}else{
			$DataSet[] = $row[$Strictness[0]];
			$DataID[] = $row[$FetchedColumn[0]];	
			
			}
		}
		
		if(strpos($Table[0],'Categories') !== false
			or $Table[0] == 'Categories'){
		
		foreach($DataGroup as $Key=> $Item){
			if(!in_array($Item,$Level)){
				$DataID[] = $Item;
				$DataSet[] = $Key;
			}
		
		}
	}
	}else{
	return;
	}

	return array($DataSet,$DataID, $Extra);
}
function FetchOrderDetail($mysqli,$ID){
	$results = $mysqli->query("SELECT  OrderID, OrderQty, ShipName, ShipAddressOne, ShipAddressTwo, City, ShipCounty, ShipCountry, ShipPostCode, OrderDate, OrderStatus, ShippingOption, PayPalFee, DeliveryNotice, Email FROM Orders WHERE OrderID = '$ID'");
	while($row = $results->fetch_array()){
		$Order['OrderID'] = $row['OrderID'];
		$Order['PayPalFee'] = $row['PayPalFee'];
		$Order['Date'] = $row['OrderDate'];
		$Order['ShippingOption'] = $row['ShippingOption'];
		$Order['Status'] = $row['OrderStatus'];
		$Order['DeliveryNotice'] = $row['DeliveryNotice'];
		$Order['ShipName']=$row['ShipName'];
						if(isset($row['Email']) 
						&& !empty($row['Email'])){
							$Order['Email'] =$row['Email'];
						}else{
						$Order['Email'] ='None Provided';	
						}
						
						$Order['Address'] =$row['ShipAddressOne'].'<br>'.$row['ShipAddressTwo'].'<br>'.$row['City'].'<br>'.$row['ShipCounty'].'<br>'.$row['ShipCountry'].'<br>'.$row['ShipPostCode'];
	}
$results = $mysqli->query("SELECT a.OrderProductID,a.Price,a.Quantity,a.Opt,b.ProductName FROM OrderDetails AS a INNER JOIN Products AS b ON a.OrderProductID = b.ProductID WHERE a.OrderID = '$ID'");
while($row = $results->fetch_array()){
	$Order['Product'][] = $row['ProductName'];
	$Order['ProductPrice'][] = $row['Price'];
	$Order['Quantity'][] = $row['Quantity'];
	$Order['Options'][] = $row['Opt'];
}
	return $Order;
}
function FetchEditForm($mysqli,$TableName, $ID){
	$results = $mysqli->query("SELECT TableName,Fields,VisibleFields,VisibleFieldsValues,FieldNames,LinkedTables FROM TableManager WHERE ActiveTable = 'True' AND TableName = '$TableName'");
		$Count = 0;
	if(mysqli_num_rows($results) > 0){
		while($row = $results->fetch_array()) {
			$Fields = $row['Fields'];
			$VisibleFields = $row['VisibleFields'];
			$VisibleValues = $row['VisibleFieldsValues'];
			$Linked = $row['LinkedTables'];
			$FieldNames = $row['FieldNames'];
		}
		
		$AllFields = explode(',',$Fields);
		$Values = explode(',',$VisibleValues);
		$ColumnNames = explode(',',$VisibleFields);
		$LabelNames = explode(',',$FieldNames);
		$LinkedTables = explode('/',$Linked);
		if(isset($ID)
		&& !empty($ID)
		&& $ID !== 'None'){
			if(strpos($ID,'Text')){
				$results = $mysqli->query("SELECT * FROM ".$TableName);
			if(mysqli_num_rows($results) > 0){
				while($row = $results->fetch_array()) {
					foreach($ColumnNames as $FieldN){
							$SingleResult[] = $row[$FieldN];
					}
					
				}
			}
			}elseif(strpos($ID,'GallTex')){
				$results = $mysqli->query("SELECT * FROM ".$TableName);
			if(mysqli_num_rows($results) > 0){
				while($row = $results->fetch_array()) {
					foreach($ColumnNames as $FieldN){
							$SingleResult[] = $row[$FieldN];
					}
					
				}
			}
			}else{
		$results = $mysqli->query("SELECT * FROM ".$TableName." WHERE ".$AllFields[0]." = ".$ID);
			if(mysqli_num_rows($results) > 0){
				while($row = $results->fetch_array()) {
					foreach($ColumnNames as $FieldN){
							$LookUpResults[] = $row[$FieldN];
					}
					
				}
			}
			}
		}
		
		foreach($LinkedTables as $LinkedItem){
			$LinkHead = explode('-',$LinkedItem);
			$LinkedColumn[] = $LinkHead[0];
		}
		
			foreach($Values as $Key => $Value){
				$DropDown = explode('(',$Value);
				if($Value == 'Text'){
					if($TableName == 'Coupons'){
						$LookUpResults[$Key] = str_replace('&pound','£',$LookUpResults[$Key]);
					}
					
					$Form .= '<div class="form-group">
                                <label for="'.$ColumnNames[$Key].'">'.$LabelNames[$Key].'</label>
                                <input type="text" class="form-control InputField" name="'.$ColumnNames[$Key].'" id="'.$ColumnNames[$Key].'" placeholder="Enter '.$LabelNames[$Key].'" value="'.$SingleResult[$Key].$LookUpResults[$Key].'">
                              </div>';
					
				}elseif($Value == 'StartDate'){
					$Form .= '  <div class="input-daterange b-datepicker input-group" id="datepicker"><div class="form-group">
                                <label for="'.$ColumnNames[$Key].'">'.$LabelNames[$Key].'</label>
								<input type="text" class="input-sm form-control InputField"data-date-format="dd/mm/yyyy"  name="start" id="'.$ColumnNames[$Key].'" placeholder="Beginning..." value="'.$LookUpResults[$Key].'"/>
                              </div>';
					
				}elseif($Value == 'EndDate'){
					$Form .= '<div class="form-group">
                                <label for="'.$ColumnNames[$Key].'">'.$LabelNames[$Key].'</label>
								<input type="text" class="input-sm form-control InputField" data-date-format="dd/mm/yyyy" name="end" id="'.$ColumnNames[$Key].'" placeholder="Ending..." value="'.$LookUpResults[$Key].'"/>
                              </div></div>';
					
				}elseif($Value == 'Random'){
					if(isset($ID)
					&& !empty($ID)
					&& $ID !== 'None'){
						$Form .= '<div class="form-group">
                                <label for="'.$ColumnNames[$Key].'">'.$LabelNames[$Key].'</label>
                                <input type="text" class="form-control InputField" name="'.$ColumnNames[$Key].'" id="'.$ColumnNames[$Key].'" placeholder="Enter '.$LabelNames[$Key].'" value="'.$LookUpResults[$Key].'">
                              </div>';
					}else{
					$Form .= '<div class="form-group">
                                <label for="'.$ColumnNames[$Key].'">'.$LabelNames[$Key].'</label>
                                <input type="text" class="form-control InputField" name="'.$ColumnNames[$Key].'" id="'.$ColumnNames[$Key].'" placeholder="Enter '.$LabelNames[$Key].'" value="'.random_string(6).'">
                              </div>';
					}
				}elseif($Value == 'Number'){
					$Form .=	'<div class="form-group">
                                <label for="'.$ColumnNames[$Key].'">'.$LabelNames[$Key].'</label>
                                <input type="number" class="form-control InputField" name="'.$ColumnNames[$Key].'" id="'.$ColumnNames[$Key].'" placeholder="Enter '.$LabelNames[$Key].'" value="'.$LookUpResults[$Key].$SingleResult[$Key].'">
                              </div>';
					
				}elseif($Value == 'Date'){
					$Form .=	'<div class="form-group">
                                <label for="'.$ColumnNames[$Key].'">'.$LabelNames[$Key].'</label>
                                 <div class="prepend-icon">
                          <input type="text" name="timepicker" class="b-datepicker form-control InputField" id="'.$ColumnNames[$Key].'" placeholder="Select a date..." value="'.$LookUpResults[$Key].$SingleResult[$Key].'">
                          <i class="icon-calendar"></i>
                        </div>



                            ';
					
				}elseif($Value == 'Address'){
					$Form .=	'<div class="form-group">
                                <label for="'.$ColumnNames[$Key].'">'.$LabelNames[$Key].'</label>
                                <input type="text" class="form-control InputField searchInput controls" name="'.$ColumnNames[$Key].'" id="'.$ColumnNames[$Key].'" placeholder="Enter '.$LabelNames[$Key].'" value="'.$LookUpResults[$Key].$SingleResult[$Key].'">
                              </div>';
					
				}elseif($Value == 'HTML'){
					$HTMLEditors .= '<div class="col-lg-6"><h3>'.$LabelNames[$Key].'</h3><textarea cols="80" rows="10" class="cke-editor InputField" id="'.$ColumnNames[$Key].'" >'.$LookUpResults[$Key].$SingleResult[$Key].'</textarea></div>';
					
				}elseif($Value == 'DynamicText'){
					if(in_array($ColumnNames[$Key],$LinkedColumn)){
						$Name = $ColumnNames[$Key];
						$DynamicInfo = FetchLinkedTable($mysqli,$TableName,$LinkedTables,$ColumnNames[$Key], $ID);
						$Form .= ' <div class="form-group">
                                <label for="'.$Name.'">'.$LabelNames[$Key].'</label>
                                <select class="form-control InputField" id="'.$Name.'" data-search="true">';
								foreach($DynamicInfo[0] as $Keys => $Info){
									if($LookUpResults[$Key] == $DynamicInfo[1][$Keys]){
									$Form.= '<option value="'.$DynamicInfo[1][$Keys].'" selected>'.$Info.'</option>';
									}else{
									$Form.= '<option value="'.$DynamicInfo[1][$Keys].'">'.$Info.'</option>';
									}
								}
								
                        $Form .='</select>
                              </div>';
					}else{
					$Form .= ' <div class="form-group">
                                <label for="'.$ColumnNames[$Key].'">'.$LabelNames[$Key].'</label>
                                <select id="'.$ColumnNames[$Key].'" class="form-control InputField" data-search="true">
                                <option value="1">Test</option>
                                <option value="1" selected>Rest</option>
                                </select>
                              </div>';
					}
				}elseif($DropDown[0] == 'Dropdown'){
					$Drops = explode('/',$DropDown[1]);

						$Form .= ' <div class="form-group">
                                <label for="'.$Name.'">'.$LabelNames[$Key].'</label>
                                <select class="form-control InputField" id="'.$ColumnNames[$Key].'" data-search="true">';
								foreach($Drops as $Info){
									$DropdownSelection = explode('@',$Info);
									if($LookUpResults[$Key] == $DropdownSelection[1]){
									$Form.= '<option value="'.$DropdownSelection[1].'" selected>'.$DropdownSelection[0].'</option>';
									}else{
									$Form.= '<option value="'.$DropdownSelection[1].'">'.$DropdownSelection[0].'</option>';
									}
								}
								
                        $Form .='</select>
                              </div>';
					
				}elseif($TableName == 'Orders'){
					$OrderProducts .='  <div class="ProductOrders">';
						if(isset($ID)
					&& !empty($ID)
					&& $ID !== 'None'){
					$results = $mysqli->query("SELECT b.Price,b.Quantity,b.Opt,c.ProductName,b.OrderProductID,b.OrderDetailID FROM Orders AS a INNER JOIN OrderDetails AS b ON a.OrderID = b.OrderID INNER JOIN Products AS c ON b.OrderProductID = c.ProductID WHERE a.OrderID = '$ID'");
					while($row = $results->fetch_array()){
						$ProductNames[] = $row['ProductName'];
						$ProductID[] = $row['OrderProductID'];
						$QtyBought[] = $row['Quantity'];
						$Price[] = $row['Price'];
						$Option[] = $row['Opt'];
						$OrderDetailID[] = $row['OrderDetailID'];
					}
					$results = $mysqli->query("SELECT ProductID, ProductName FROM Products WHERE ProductLive = '1'");
					while($row = $results->fetch_array()){
						$Products[] = $row['ProductName'];
						$ProductIDs[] = $row['ProductID'];
					}
					foreach($ProductNames as $Keyq => $Prod){
						$OrderProducts .= ' <div class="form-group" id="'.$OrderDetailID[$Keyq].'">
						<button type="button" class="btn btn-danger RemoveOrderProduct">Remove Product</button>
                                <label for="'.$OrderDetailID.'">'.$Prod.'</label>
                                <select class="form-control InputField OrderDetails" id="OrderProductID" data-search="true">';
								foreach($ProductIDs as $Keys => $Info){
									if($ProductID[$Keyq] == $Info){
									$OrderProducts.= '<option value="'.$Info.'" selected>'.$Products[$Keys].'</option>';
									}else{
									$OrderProducts.= '<option value="'.$Info.'">'.$Products[$Keys].'</option>';
									}
								}
								
                        $OrderProducts .='</select>
						 <label for="'.$OrderDetailID.'">Quantity</label>
						<input type="number" class="form-control InputField OrderDetails" id="Quantity" placeholder="Enter Quantity" value="'.$QtyBought[$Keyq].'">
						 <label for="'.$OrderDetailID.'">Individual Sale Price</label>
						<input type="number" class="form-control InputField OrderDetails" id="Price" placeholder="Enter Price" value="'.$Price[$Keyq].'">';
						if($Option[$Keyq] == 'EMPTY'){
							$OrderProducts .= '<label for="'.$OrderDetailID.'">Option(s) selected</label>
						<input type="text" class="form-control InputField OrderDetails" id="Opt" placeholder="Enter Options">';
						}else{
							
						$OrderProducts .= '<label for="'.$OrderDetailID.'">Option(s) selected</label>
						<input type="text" class="form-control InputField OrderDetails" id="Opt" placeholder="Enter Options" value="'.strip_tags($Option[$Keyq]).'">';
						
						}
						$OrderProducts .='  </div><br />
<br />
';
						
					
					}
				
					
					}else{
							$results = $mysqli->query("SELECT ProductID, ProductName FROM Products WHERE ProductLive = '1'");
					while($row = $results->fetch_array()){
						$Products[] = $row['ProductName'];
						$ProductIDs[] = $row['ProductID'];
					}
					$OrderProducts .= ' <div class="form-group" id="NewOrder">
											<button type="button" class="btn btn-danger RemoveOrderProduct">Remove Product</button>

                                <label>Product Name</label>
                                <select class="form-control InputField OrderDetails" id="OrderProductID" data-search="true">';
								foreach($ProductIDs as $Keys => $Info){
									
									$OrderProducts.= '<option value="'.$Info.'">'.$Products[$Keys].'</option>';
									
								}
								
                        $OrderProducts .='</select>
						 <label >Quantity</label>
						<input type="number" class="form-control InputField OrderDetails" id="Quantity" placeholder="Enter Quantity" >
						 <label >Individual Sale Price</label>
						<input type="number" class="form-control InputField OrderDetails" id="Price" placeholder="Enter Price" >';
						
							$OrderProducts .= '<label>Option(s) selected</label>
						<input type="text" class="form-control InputField OrderDetails" id="Opt" placeholder="Enter Options">';
						
						$OrderProducts .='  </div><br />
<br />';
					}

					$OrderProducts .='  </div>';
					$OrderProducts .='<button type="button" class="btn btn-white" id="NewOrderProduct"><i class="fa fa-plus"></i> Add New Product Sale</button>';

				}elseif($Value == 'GalleryText'){
					$Form = 'Please upload your images, you can remove or add captions to images on the next step.';
					$results = $mysqli->query("SELECT * FROM TableManager WHERE TableName = '$TableName'");
while($row = $results->fetch_array()){
	$VisFi = $row['VisibleFields'];
	$VisNa = $row['FieldNames'];
}
$Names = explode(',',$VisNa);
$Fields = explode(',',$VisFi);
					$Counta = 0;
							$results = $mysqli->query("SELECT * FROM ".$TableName);
					while($row = $results->fetch_array()){
						
                         
                           	$Images .= '<figure class="effect-lily ImagesMulti" id="'.$row[$Fields[0]].'" style="background-size:contain;background-repeat:no-repeat;background-image:url(http://'.$_SESSION['WebURL'].'/'.$row[$Fields[0]].');"> 
								
                                  <figcaption style="text-align:right;">
                     				<button type="button" class="btn btn-danger btn-square RemoveImage" id="'.$row[$Fields[0]].'">Remove</button>
								<br />
								</figcaption>';	
									$HeightDiff = 0;
foreach($Fields as $Kc => $Valz){
	
	if($Kc>0){
	$Images .='<div><input class="form-control InputField input-sm" id="'.$Valz.'" placeholder="'.$Names[$Kc].'
                      		" type="text" value ="'.$row[$Fields[$Kc]].'" style=position:absolute;bottom:'.$HeightDiff*$Kc.'px;" /></div>';
                      		$HeightDiff = 20;
                      	}
                      	
}
                              $Images .= ' </figure>';


                           }


                           $Uploader = ' <div class="col-lg-6">
<form action="Pages/Uploaders/TableImageUploader.php" class="dropzone">
                        <div class="fallback">
                          <input name="file" type="file" multiple />
                        </div>
                      </form></div>';
                     
				}elseif($Value == 'ImagesMulti'){
					//$Form .='ed';
					if(isset($ID)
					&& !empty($ID)
					&& $ID !== 'None'
					&& is_numeric($ID)){
					$DynamicInfo = FetchLinkedTable($mysqli,$TableName,$LinkedTables,'ImageProducts', $ID);
	
				foreach($DynamicInfo[0] as $Key => $Info){
					$Images .= '<figure class="effect-lily ImagesMulti" id="'.$Info.'" style="background-size:contain;background-repeat:no-repeat;background-image:url(http://'.$_SESSION['WebURL'].'/'.$Info.');"> 
								
                                  <figcaption style="text-align:right;">
                     				<button type="button" class="btn btn-danger btn-square RemoveImage" id="'.$Info.'">Remove</button>
								<br />';
if($DynamicInfo[2][$Key] == 'YES'){
                                $Images .=' <label> Default Image <input type="radio" name="radio1" data-radio="iradio_square" class="DefaultImage" id="'.$Info.'" checked></label>';
}else{
                               $Images .=' <label> Default Image <input type="radio" name="radio1" data-radio="iradio_square" class="DefaultImage" id="'.$Info.'"></label>';
}
								  
                      		$Images .= '</figcaption>
                               </figure>';
							   }
							  
					$Uploader = ' <div class="col-lg-6">
<form action="Pages/Uploaders/TableImageUploader.php" class="dropzone">
                        <div class="fallback">
                          <input name="file" type="file" multiple />
                        </div>
                      </form></div>';
				
				}else{
					if(isset($ID)
						&& !empty($ID)
						&& !is_numeric($ID)
						&& strpos($ID,'Gallery')){
						
						$results = $mysqli->query("SELECT URL FROM ".$TableName);
					while($row = $results->fetch_array()){
						$Images .= '<figure class="effect-lily ImagesMulti" id="'.$row['URL'].'" style="background-size:contain;background-repeat:no-repeat;background-image:url(http://'.$_SESSION['WebURL'].'/'.$row['URL'].');"> 
								
                                  <figcaption style="text-align:right;">
                     				<button type="button" class="btn btn-danger btn-square RemoveImage" id="'.$row['URL'].'">Remove</button>
								<br />';								  
                      		$Images .= '</figcaption>
                               </figure>';

                           }
					}else{
							//If it's just a image gallery with mutliple images.
						if($VisibleValues == 'ImagesMulti'){

							$results = $mysqli->query("SELECT URL FROM ".$TableName);
					while($row = $results->fetch_array()){
						$Images .= '<figure class="effect-lily ImagesMulti" id="'.$row['URL'].'" style="background-size:contain;background-repeat:no-repeat;background-image:url(http://'.$_SESSION['WebURL'].'/'.$row['URL'].');"> 
								
                                  <figcaption style="text-align:right;">
                     				<button type="button" class="btn btn-danger btn-square RemoveImage" id="'.$row['URL'].'">Remove</button>
								<br />
								';								  
                      		$Images .= '</figcaption>
                               </figure>';
                           }
						}else{
							$Images = ' ';
							//$Form .= $Value.'@';
						}
					}   
					$Uploader = ' <div class="col-lg-6">
<form action="Pages/Uploaders/TableImageUploader.php" class="dropzone">
                        <div class="fallback">
                          <input name="file" type="file" multiple />
                        </div>
                      </form></div>';
				}
					
				}elseif($Value == 'Thumbnail'){
						if($VisibleValues == 'Thumbnail'){
							$results = $mysqli->query("SELECT URL FROM ".$TableName);
					while($row = $results->fetch_array()){
						$Images .= '<figure class="effect-lily ImagesMulti" id="'.$row['URL'].'" style="background-size:contain;background-repeat:no-repeat;background-image:url(http://'.$_SESSION['WebURL'].'/'.$row['URL'].');"> 
								
                                  <figcaption style="text-align:right;">
                     				<button type="button" class="btn btn-danger btn-square RemoveImage" id="'.$row['URL'].'">Remove</button>
								<br />';								  
                      		$Images .= '</figcaption>
                               </figure>';
                           }
                           $Uploader = ' <div class="col-lg-6">
<form action="Pages/Uploaders/TableImageUploader.php" class="dropzone">
                        <div class="fallback">
                          <input name="file" type="file" multiple />
                        </div>
                      </form></div>';
						}else{

							if(isset($ID)
						&& !empty($ID)
						&& !is_numeric($ID)
						&& strpos($ID,'GallTex')){
									$results = $mysqli->query("SELECT URL FROM ".$TableName);
					while($row = $results->fetch_array()){
						$Images .= '<figure class="effect-lily ImagesMulti" id="'.$row['URL'].'" style="background-size:contain;background-repeat:no-repeat;background-image:url(http://'.$_SESSION['WebURL'].'/'.$row['URL'].');"> 
								
                                  <figcaption style="text-align:right;">
                     				<button type="button" class="btn btn-danger btn-square RemoveImage" id="'.$row['URL'].'">Remove</button>
								<br />';								  
                      		$Images .= '</figcaption>
                               </figure>';
                           }
                           $Uploader = ' <div class="col-lg-6">
<form action="Pages/Uploaders/TableImageUploader.php" class="dropzone">
                        <div class="fallback">
                          <input name="file" type="file" multiple />
                        </div>
                      </form></div>';

							}elseif(isset($ID)
							&& !empty($ID)
							&& $ID !== 'None'){

					$Images .= '<figure class="effect-lily ImagesMulti" id="'.$LookUpResults[$Key].'" style="background-size:contain;background-repeat:no-repeat;background-image:url(http://'.$_SESSION['WebURL'].'/'.$LookUpResults[$Key].');"> 
								
                                  <figcaption style="text-align:right;">
                     				<button type="button" class="btn btn-danger btn-square RemoveImage DeleteImageSingle DefaultImage" id="'.$LookUpResults[$Key].'">Remove</button>
								<br />';								  
                      		$Images .= '</figcaption>
                               </figure>';
							   
							   
					$Uploader = ' <div class="col-lg-6">
<form action="Pages/Uploaders/TableImageUploader.php" class="dropzone">
                        <div class="fallback">
                          <input name="file" type="file" multiple />
                        </div>
                      </form></div>';
				
				}else{
					$Images = ' ';   
					$Uploader = ' <div class="col-lg-6">
<form action="Pages/Uploaders/TableImageUploader.php" class="dropzone">
                        <div class="fallback">
                          <input name="file" type="file" multiple />
                        </div>
                      </form></div>';
				}
				}
				}elseif($Value == 'Categories'){
					$DynamicInfo = FetchLinkedTable($mysqli,$TableName,$LinkedTables,$ColumnNames[$Key], $ID);
					$Name = $ColumnNames[$Key];
					$Form .= ' <div class="form-group">
                                <label for="'.$ColumnNames[$Key].'">'.$LabelNames[$Key].'</label>
								<p>Select the category you want to edit.</p>
                                <select class="form-control InputField" data-search="true" id="'.$ColumnNames[$Key].'">
								<option value="Empty">Select a Category to Edit</option>';
								foreach($DynamicInfo[0] as $Key => $Info){
									$Form.= '<option value="'.$DynamicInfo[1][$Key].'">'.$Info.'</option>';
								}
                        $Form .='</select>
                              </div>';
					$Form .= ' <div class="form-group" >
                                <label for="'.$Name.'">Add a New Category</label>
                               <input type="text" class="form-control InputField" name="'.$Name.'" id="'.$Name.'@New" placeholder="Enter Category">
                              </div><div class="modal-container" data-toggle="modal" data-target="#modal-responsive"></div>';
							  
							  
				}elseif($Value == 'Tags'){
					if(isset($ID)
					&& !empty($ID)
					&& $ID !== 'None'){
						$Form .='<div class="form-group">
					 <label>'.$LabelNames[$Key].'</label>
                        <p>Press the comma key after each new word (",")</p>
                            <input class="select-tags  form-control TagBox InputField" id="'.$ColumnNames[$Key].'" value="'.$LookUpResults[$Key].$SingleResult[$Key].'">

						</div>';
					}else{
					$Form .='<div class="form-group">
					 <label>'.$LabelNames[$Key].'</label>
                        <p>Press the comma key after each new word (",")</p>
                            <input class="select-tags form-control TagBox InputField" id="'.$ColumnNames[$Key].'">
						</div>';
					}
							  
				}elseif($Value == 'Featured'){
					if(isset($ID)
					&& !empty($ID)
					&& $ID !== 'None'){
						$DynamicInfo = FetchLinkedTable($mysqli,$TableName,$LinkedTables,'FeaturedProducts', $ID);
						
						$Form .='<div class="form-group">
					 <label>Featured Prices</label>
                        <p>If you want to discount your product fill in these fields otherwise leave blank.</p>
                        <input type="text" class="form-control InputField" name="Featured" id="Featured" placeholder="Enter Featured Discount" value="'.$DynamicInfo[0].'">
	                                <input type="number" class="form-control InputField" name="FeaturedPrice" id="FeaturedPrice" placeholder="Enter Featured Price" value="'.$DynamicInfo[1].'">

						</div>';
					}else{
					$Form .='<div class="form-group">
					 <label>Featured Prices</label>
                        <p>If you want to discount your product fill in these fields otherwise leave blank.</p>
                        <input type="text" class="form-control InputField" name="Featured" id="Featured" placeholder="Enter Featured Discount">
	                                <input type="number" class="form-control InputField" name="FeaturedPrice" id="FeaturedPrice" placeholder="Enter Featured Price" >

						</div>';
					}
							  
				}elseif($Value == 'Options'){
					if(isset($ID)
					&& !empty($ID)
					&& $ID !== 'None'){
						$DynamicInfo = FetchLinkedTable($mysqli,$TableName,$LinkedTables,'ProductOptions', $ID);
						if(isset($DynamicInfo)
						&& !empty($DynamicInfo)){
							
							$Options[0] .='<div class="Options">';
						foreach($DynamicInfo[0][3] as $Keys => $OptionName){
							$Options[0] .= '<div class="form-group">
							<button type="button" class="btn btn-danger RemoveOptionProduct" style="float:right;">Remove Option</button>
                                <label for="ProductOptions">Product Options</label>
                                <input type="text" class="form-control InputField" name="ProductOptions" id="NewOptionName" placeholder="Enter Option Name" value="'.$OptionName.'">
                              
                          <label>Options</label>
                        <p>Press the comma key after each new option (",")</p>
                            <input class="select-tags form-control TagBox InputField" id="NewOptions" value="'.$DynamicInfo[0][2][$Keys].'">
							<p>Editing the individual prices/stock will prevent changes to the option until the product is uploaded, if you leave the individual options empty then they will use the values set on step 1.</p>
							<button type="button" class="btn btn-blue" id="NewOptionLevels"><i class="fa fa-pencil"></i> Edit Individual Prices/Stock</button>
                          </div>
                          
                       ';
						$Opts = explode(',',$DynamicInfo[0][2][$Keys]);
						$OptCosts = explode(',',$DynamicInfo[0][1][$Keys]);
						$OptStocks = explode(',',$DynamicInfo[0][0][$Keys]);
						$Options[2] .= '<div id="StockLe" class="'.$OptionName.' OptionSet" style="display:none;">';
						$Options[1] .= '<div id="Costing" class="'.$OptionName.' OptionSet" style="display:none;">';

						foreach($Opts as $Keyt => $OptDetail){
						$Options[1] .= '<div class="form-group">
                                <label for="ProductOptions" class="CostName">'.$OptDetail.'</label>
                                <input type="text" class="form-control InputField" name="OptionCost" id="OptionCost" placeholder="Enter Option Cost" value="'.$OptCosts[$Keyt].'">
                     </div>';
						$Options[2] .= '<div class="form-group">
                                <label for="ProductOptions" class="CostName">'.$OptDetail.'</label>
                                <input type="number" class="form-control InputField" name="OptionStock" id="OptionStock" placeholder="Enter Option Stock" value="'.$OptStocks[$Keyt].'">
                      </div>';
						}
						$Options[1] .= '</div>';
						$Options[2] .= '</div>';
						
						}
						}else{
							$Options[0] .= '<div class="form-group">
                                <label for="ProductOptions">Product Options</label>
                                <input type="text" class="form-control InputField" name="ProductOptions" id="NewOptionName" placeholder="Enter Option Name">
                              
                          <label>Options</label>
                        <p>Press the comma key after each new option (",")</p>
                            <input class="select-tags form-control TagBox InputField" id="NewOptions">
							<p>Editing the individual prices/stock will prevent changes to the option until the product is uploaded, if you leave the individual options empty then they will use the values set on step 1.</p>
							<button type="button" class="btn btn-blue" id="NewOptionLevels"><i class="fa fa-pencil"></i> Edit Individual Prices/Stock</button>
                          </div>
                         
                      ';
						}
					}else{
						$Options[0] .= '<div class="form-group">
                                <label for="ProductOptions">Product Options</label>
                                <input type="text" class="form-control InputField" name="ProductOptions" id="NewOptionName" placeholder="Enter Option Name">
                              
                          <label>Options</label>
                        <p>Press the comma key after each new option (",")</p>
                            <input class="select-tags form-control TagBox InputField" id="NewOptions">
							<p>Editing the individual prices/stock will prevent changes to the option until the product is uploaded, if you leave the individual options empty then they will use the values set on step 1.</p>
							<button type="button" class="btn btn-blue" id="NewOptionLevels"><i class="fa fa-pencil"></i> Edit Individual Prices/Stock</button>
                          </div>
                         
                        ';
					}
												$Options[0] .='</div>';

					$Options[0] .=' <button type="button" class="btn btn-white" id="NewOption"><i class="fa fa-plus"></i> Add New Option</button>';
					
				}
				
			}
			return array($Form,$HTMLEditors, $Images, $Uploader, $Options,$OrderProducts);
	}
	
	
	
}
function UpdateTableQuerySimple($mysqli,$TableName,$Fields,$Values,$IDName,$ID){
			foreach($Fields as $Key => $Field){
				$Query[] = $Field."='".$Values[$Key]."' ";
			}
			$QueryString = implode(',',$Query);
			$stmt = $mysqli->prepare("UPDATE ".$TableName." SET ".$QueryString." WHERE  ".$IDName." = '$ID'");
			$stmt->execute(); 

}
function UpdateTableQuery($mysqli,$TableName,$Fields,$Values,$IDName,$ID){
			foreach($Fields as $Key => $Field){
				$Query[] = $Field."='".$Values[$Field]."' ";
			}
			$QueryString = implode(',',$Query);
			$stmt = $mysqli->prepare("UPDATE ".$TableName." SET ".$QueryString." WHERE  ".$IDName." = '$ID'");
			$stmt->execute(); 

}
function CreateAdminPages($connecDB,$PageName,$FieldNames,$PageType,$FieldTypes,$WebPageName){

	$LinkedTables = '';
	$TableName = random_string(9);

	$FieldName = explode(',',$FieldNames);
	foreach($FieldTypes as $Key => $Types){
		if(isset($Types)
			&& !empty($Types)){
			
			$FieldTypeArray[] = $Types;

		}
	}
	foreach($FieldName as  $Field){
		if(isset($Field)
			&& !empty($Field)){
		$FieldArray[] = $Field;
		$FieldArrayGen[] = random_string(9);			
		$TableType[] = 'varchar';
		$TableSize[] = '255';
		}
	}
foreach($FieldArrayGen as $Key => $Item){
			if($FieldTypeArray[$Key] == 'ImagesMulti'
				or $FieldTypeArray[$Key] == 'Thumbnail'
				or $FieldTypeArray[$Key] == 'GalleryText'){
				if($PageType == 'Regular'){
				$FieldArrayGenNew[] = 'ProductThumb';
				$ImageID = random_string(9);
				$ImageProductID = random_string(9);
				CreateSimpleTables($connecDB,$ImageID,'ImageID',array('FileLocation','Tags'), array('varchar','varchar'), array('255','255'));
				CreateSimpleTables($connecDB,$ImageProductID,'ImageProductID',array('ID','ImageID','Def'), array('varchar','varchar','varchar'), array('30','30','30'));
				$LinkedTables .= 'ImageProducts-'.$ImageProductID.'@ID>ImageID,Def*'.$ImageID.'@ImageID>FileLocation(Strict)';
				}else{
				$FieldArrayGenNew[] = 'URL';
				}
			}else{
				$FieldArrayGenNew[] = random_string(9);
	
			}

			if($FieldTypeArray[$Key] == 'Number'){
				$TableType[$Key] = 'float';
			}
			if($FieldTypeArray[$Key] == 'HTML'){
				$TableSize[$Key] = '6000';
			}
			if($FIeldTypeArray[$Key] == 'Categories'){
				$LinkedTables .= 'CategoryID-Categories@CategoryID>CategoryName(Lose)';
			}


}
$Primary = 'ID';

$FieldTypeList = implode(',',$FieldTypeArray);
$VisibleFields = implode(',',$FieldArrayGenNew);
$FieldArray = implode(',',$FieldArray);
foreach($FieldTypeArray as $Item){
	if($Item == 'GalleryText'){
		$FieldTypeList = 'GalleryText';
		$VisibleFields = 'URL,Text';
		$FieldArray = 'URL,Text';
		//EDIT HERE
		$FieldArrayGenNew = array('URL','Text');
	}
}
if($PageType == 'Regular'){
	$FileName = 'ViewTable.php';
	$Class = 'Table';
	$TableAddon = '';
}else{
	$TableAddon = $PageType;
	$LinkVar = $PageType;
	$FileName = 'EditItem.php';
	$Class = 'Edits';
}

if($PageType == 'Categories'){  
	$Primary = 'CategoryID';
	$FileName = 'ViewTable.php';
	$Class = 'Table';
	$VisibleFields = 'CategoryName';
	$FieldTypeArray = 'Categories';
	$FieldArray = 'Category Name';
	$FieldArrayGenNew = array('CategoryName','CategoryLevel','Root');
	$TableType = array('varchar','varchar','varchar');
	$TableSize = array('255','255','255');
}
//if FieldTypeArray == imagesmulti or thumbnail then tabletype[] == URL

$AdminPanelCols = array('Name','Permission','FileName','ClassName','TableName','LinkVar','WebsitePageName');

$TableCols = array('TableName','Fields','VisibleFields','VisibleFieldsValues','FieldNames','LinkedTables','ActiveTable','SaveTables','SaveRules','DelRow');

$AdminPanelVals = array($PageName,'True',$FileName,$Class,$TableName.$TableAddon,'?ID='.$TableName.$LinkVar,$WebPageName);

$TableVals = array($TableName.$TableAddon,$Primary.','.implode(',',$FieldArrayGenNew),$VisibleFields,$FieldTypeList,$FieldArray,$LinkedTables,'True','','','');

InsertIntoTable($connecDB,'AdminPanel',$AdminPanelCols,$AdminPanelVals);

InsertIntoTable($connecDB,'TableManager',$TableCols,$TableVals);

CreateSimpleTables($connecDB, $TableName.$TableAddon,$Primary,$FieldArrayGenNew, $TableType, $TableSize);

$results = $connecDB->query("SELECT * FROM AdminPanel");
echo mysqli_num_rows($results);


}

function UpdateTable($mysqli,$FieldNames,$FieldValues,$TableName,$Images,$DefaultImage,$ID,$OrderDetailsName,$OrderDetailsVal,$OrderDetailsID){

	$results = $mysqli->query("SELECT TableName,Fields,VisibleFields,DelRow,VisibleFieldsValues,FieldNames,LinkedTables,SaveTables,SaveRules FROM TableManager WHERE ActiveTable = 'True' AND TableName = '$TableName'");
	if(!isset($DefaultImage)){
		$DefaultImage = $Images[0];
	}

		$Count = 0;
	if(mysqli_num_rows($results) > 0){
		while($row = $results->fetch_array()) {
			$Fields = $row['Fields'];
			$VisibleFields = $row['VisibleFields'];
			$VisibleValues = $row['VisibleFieldsValues'];
			$Linked = $row['LinkedTables'];
			$SaveTbl = $row['SaveTables'];
			$TblRules = $row['SaveRules'];
			$DeleteRow = $row['DelRow'];
			//$FieldNames = $row['FieldNames'];
		}
		$LinkedArr = explode('/',$Linked); //CONTINUE HERE
		foreach($LinkedArr as $Key => $Value){
			$LinkedType[$Key] = explode('(',$Value);
			$LinkedNameArr[$Key] = explode('-',$LinkedType[$Key][0]);
			$LinkedName[$Key] = $LinkedNameArr[$Key][0]; //ImageProducts
			if($LinkedName[$Key] == 'ImageProducts'){

			$LinkedData[$Key] = $LinkedNameArr[$Key][1];
			$LinkedTableData[$Key] = explode('*',$LinkedData[$Key]);
			foreach($LinkedTableData[$Key] as $NewKey => $NewVal){
				$LinkedTableName[$Key][$NewKey] = explode('@',$NewVal);//[0] = Table name

				$LinkedTablePrimary[$Key][$NewKey] = explode('>',$LinkedTableName[$Key][$NewKey][1]);//[0] = Primary Key Name

				$LinkedTableFieldsArr[$Key][$NewKey] = explode(',',$LinkedTablePrimary[$Key][$NewKey][1]);//[] = Fields Involved
			}
			}
		}
		$TableRules = explode('/',$TblRules);
		$VisibleFieldRules = explode(',',$VisibleValues);
		$VisibleFieldNamesRules = explode(',',$VisibleFields);
		foreach($TableRules as $Rule){
			$ValidationRules = explode('-',$Rule);	
			
			$ValidateColumn[] = $ValidationRules[0];
			$ValidateRule[] = $ValidationRules[1];
			
		}
		$AllFields = explode(',',$Fields);
		$Values = explode(',',$VisibleValues);
		$ColumnNames = explode(',',$VisibleFields);
		$LabelNames = explode(',',$FieldNames);

		if(isset($ID)
			&& !empty($ID)
			&& !is_numeric($ID) ){
			if(strpos($ID,'Gallery') !== false){
				
			mysqli_query($mysqli,"TRUNCATE TABLE ".$TableName);
			$TotalImgs = count($FieldValues)/count($Images);
			$TempTotal = $TotalImgs;
			$Begin = 0;
			foreach($Images as $Key => $Image){
				if(strpos($ID,'Text') !== false){

					if(count($FieldValues)>0){
$ColValsA = '';
$ColValsA[] = $Image;
					
					for($x=$Begin;$x<$TotalImgs;$x++){
						$ColValsA[] = $FieldValues[$x];
					}

					$Begin=$TotalImgs;
					$TotalImgs = $TempTotal + $TotalImgs;
					
					
					
				InsertIntoTable($mysqli,$TableName,$ColumnNames,$ColValsA);

				
					}else{
				InsertIntoTable($mysqli,$TableName,$ColumnNames,array($Image,$FieldValues[$Key]));

			}
				}else{

				InsertIntoTable($mysqli,$TableName,$ColumnNames,array($Image));
				}
			}
			

		}elseif(strpos($ID,'Text')){
			
			foreach($FieldValues as $Field){
				$CleanFieldValues[] = mysqli_real_escape_string($mysqli,$Field);
			}

			mysqli_query($mysqli,"TRUNCATE TABLE ".$TableName);

			InsertIntoTable($mysqli,$TableName,$ColumnNames,$CleanFieldValues);
		}elseif(strpos($ID,'GallTex')){
			foreach($FieldValues as $Field){
				$CleanFieldValues[] = mysqli_real_escape_string($mysqli,$Field);
			}
			$CleanFieldValues[] = $Images[0];


			mysqli_query($mysqli,"TRUNCATE TABLE ".$TableName);

			InsertIntoTable($mysqli,$TableName,$ColumnNames,$CleanFieldValues);
			
		}else{


			$results = $mysqli->query("SELECT * FROM '$TableName'");
		if(mysqli_num_rows($results) > 0){
			UpdateTableQuery($mysqli,trim($TableName),$ColumnNames,$FieldValues,'ID','1');

		}else{

			InsertIntoTable($mysqli,$TableName,$ColumnNames,$FieldValues);
		}
		}
			//
			return 'Success';
		}
		
	foreach($FieldNames as $Key => $Field){

		$Input[$Field] = mysql_real_escape_string($FieldValues[$Key]);
		if($Field == 'Featured'){
			$ProdDiscount = $FieldValues[$Key];
		}elseif($Field == 'FeaturedPrice'){
			$ProdNewPrice = $FieldValues[$Key];
		}elseif($Field == 'NewOptionName'){
			$OptionName[] = $FieldValues[$Key];
			$Name = $FieldValues[$Key];
		}elseif($Field == 'OptionCost'){
			$OptionCosts[] = $FieldValues[$Key];
		}elseif($Field == 'OptionStock'){
			$OptionStock[] = $FieldValues[$Key];
		}elseif($Field == 'NewOptions'){
			$Options[] = CleanString($FieldValues[$Key]);
		}
		
	}

	if(isset($Options)
	&& !empty($Options)){
		$Counter = 0;
		foreach($Options as $Keys=>$NewOpt){
			
				$ProdOpts = explode(',',$NewOpt);
				foreach($ProdOpts as $Key => $Opt){
					if(empty($OptionCosts[$Counter])){
						$ProdOptCost[$Keys][] = $Input['ProductPrice'];
					}else{
						$ProdOptCost[$Keys][] = $OptionCosts[$Counter];
					}
					
					if(empty($OptionStock[$Counter])){
						$ProdOptStock[$Keys][] = $Input['ProductStock'];
					}else{
						$ProdOptStock[$Keys][] = $OptionStock[$Counter];
					}
						$Counter++;
				}
			
		}
	}
	
	$TableSaveInfo = explode('/',$SaveTbl);
	$Unique = $AllFields[0];
		unset($AllFields[0]);

	foreach($AllFields as $Keyew => $Field){
		

		if(isset($Input[$Field])
		&& !empty($Input[$Field])){
	
		$FinalValue[$Field] = $Input[$Field];
		}else{
			$FinalValue[$Field] = ' ';

		foreach($VisibleFieldRules as $Keyq => $visi){
			
			if($visi == 'Thumbnail'){
				if($Field == $VisibleFieldNamesRules[$Keyq]){
				$FinalValue[$Field] = $DefaultImage;
			}
			}
		}
		}

		foreach($TableSaveInfo as $Rule){
			if(strpos($Rule,'-') !== false){
				$Vl = explode('-',$Rule);
				if($Vl[0] == $Field){
					if($Vl[1] == 'YMD'){
					$FinalValue[$Field] = date("Y-m-d");
					}elseif($Vl[1] == 'DMY'){
					$FinalValue[$Field] = date("d-m-Y");
					}elseif($Vl[1] == 'Def'){
					$FinalValue[$Field] = $DefaultImage;
					}elseif($Vl[1] == 'Random'){
					$FinalValue[$Field] = random_string(11);
					}else{
					$FinalValue[$Field] = $Vl[1];
					}
				}
			}elseif(strpos($Rule,'=') !==false){
				$Vl = explode('=',$Rule);
				if($Vl[0] == $Field){
					$FinalValue[$Field] = $Input[$Vl[1]];
					$FinalValue[$Vl[1]]= $Input[$Vl[1]];
				}
			}
		}
		
	}

	if(isset($ID)
	&& !empty($ID)){

		foreach($ValidateColumn as $Keyf => $ValColm){

		foreach($AllFields as $FieldCol){
			if($ValColm == $FieldCol){
				if($ValidateRule[$Keyf] == 'Required'){
					if(isset($FinalValue[$FieldCol])
					&& !empty($FinalValue[$FieldCol])
					&& $FinalValue[$FieldCol] !== ' '){
						
					}else{
						return 'Empty Fields';	
					}
				}

				if($ValidateRule[$Keyf] == 'Email'){
					if(filter_var($FinalValue[$FieldCol], FILTER_VALIDATE_EMAIL)){

					}else{
						return 'Invalid Email';
					}
				}
			}
		}
	}
	}else{
	foreach($ValidateColumn as $Keyf => $ValColm){

		foreach($AllFields as $FieldCol){
			if($ValColm == $FieldCol){
				if($ValidateRule[$Keyf] == 'Unique'){
					
					if(CheckIfRowExists($mysqli,$TableName,$ValColm,$FinalValue[$FieldCol],$DeleteRow)){
						return 'Non Unique Column';
					}
				}elseif($ValidateRule[$Keyf] == 'Required'){
					if(isset($FinalValue[$FieldCol])
					&& !empty($FinalValue[$FieldCol])
					&& $FinalValue[$FieldCol] !== ' '){
						
					}else{
						return 'Empty Fields';	
					}
				}
				if($ValidateRule[$Keyf] == 'Email'){
					if(filter_var($FinalValue[$FieldCol], FILTER_VALIDATE_EMAIL)){

					}else{
						return 'Invalid Email';
					}
				}
			}
		}
	}
	}
//return print_r($AllFields).print_r($FieldValues);
	//return UpdateTableQuery($mysqli,trim($TableName),$AllFields,$FinalValue,$Unique,$ID);
	if(isset($ID)
	&& !empty($ID)){
		
		UpdateTableQuery($mysqli,trim($TableName),$AllFields,$FinalValue,$Unique,$ID);
		$ProdID = $ID;
		$FilterTest = array_filter($OrderDetailsID);
		if(isset($FilterTest)
		&& !empty($FilterTest)){
			$stmt = $mysqli->prepare("DELETE FROM OrderDetails WHERE OrderID = '$ID'");
			$stmt->execute(); 
			
			foreach($OrderDetailsID as $Kd => $OrderID){
				if(!in_array('OrderID',$OrderFinal[$OrderID])){
					$OrderFinal[$OrderID][] = 'OrderID';
					$OrderFinalval[$OrderID][] = $ID;
				}
					$OrderFinal[$OrderID][] = $OrderDetailsName[$Kd];
					$OrderFinalval[$OrderID][] = $OrderDetailsVal[$Kd];
			}
			
			foreach($OrderFinal as $Jey => $OrderInput){
			InsertIntoTable($mysqli,'OrderDetails',$OrderInput,$OrderFinalval[$Jey]);
			}
		}elseif(isset($OrderDetailsName)
		&& !empty($OrderDetailsName)){
			foreach($OrderDetailsName as $Kd => $OrderName){
				if(!in_array('OrderID',$OrderFinal[$OrderName])){
					$OrderFinal[$OrderName][] = 'OrderID';
					$OrderFinalval[$OrderName][] = $ID;
				}
				$OrderFinal[$OrderName][] = $OrderDetailsName[$Kd];
				$OrderFinalval[$OrderName][] = $OrderDetailsVal[$Kd];
			}
				InsertIntoTable($mysqli,'OrderDetails',$OrderInput,$OrderFinalval[$Jey]);

		}
		
		if((isset($ProdNewPrice)
		&& !empty($ProdNewPrice))
		or(isset($ProdDiscount)
		&& !empty($ProdDiscount))){
			UpdateTableQuerySimple($mysqli,'FeaturedProducts', array('ProductID','Discount','FeaturePrice'),array($ID,$ProdDiscount,$ProdNewPrice),'ProductID',$ID);
		}
		$FilterTest = array_filter($OptionName);
		if(isset($FilterTest)
		&& !empty($FilterTest)){
			
			foreach($OptionName as $OptionNames){
				
				InsertIntoTable($mysqli,'OptionGroups', array('OptionGroupName'), array($OptionNames));
				$OptGrpID[] = FetchLatestEntry($mysqli);
			}
			foreach($OptGrpID as $Key => $OptGrp){
				InsertIntoTable($mysqli,'Options', array('OptionGroupID','OptionName'), array($OptGrp,$Options[$Key]));		
				$OptNameID[] = FetchLatestEntry($mysqli);	
			}
			$stmt = $mysqli->prepare("DELETE FROM ProductOptions WHERE ProductID = '$ID'");
			$stmt->execute(); 
			foreach($OptNameID as $Keya => $OptNID){
				
				InsertIntoTable($mysqli,'ProductOptions', array('ProductID','OptionID','OptionStockLevels','OptionPrices'),array($ID,$OptNID,implode(',',$ProdOptStock[$Keya]),implode(',',$ProdOptCost[$Keya])));	
			}
		}
		$FilterTest = array_filter($Images);
		if(isset($FilterTest)
		&& !empty($FilterTest)){

			foreach($LinkedTableName as $Key => $Value){
				foreach($LinkedTableName[$Key] as $NewKey => $NewValue){
					$ImagesLinked[] = $NewValue[0];
					$PrimaryLinked[] = $LinkedTablePrimary[$Key][$NewKey][0];
				}
			}
			
			foreach($Images as $Img){
				InsertIntoTable($mysqli,$ImagesLinked[1], array('FileLocation'), array($Img));
				$ImgID[] = FetchLatestEntry($mysqli);
			}
			$stmt = $mysqli->prepare("DELETE FROM $ImagesLinked[0] WHERE $PrimaryLinked[0] = '$ID'");
			$stmt->execute(); 
			foreach($ImgID as $Key => $IDs){
				
				if($Images[$Key] == $DefaultImage){
					
					 InsertIntoTable($mysqli,$ImagesLinked[0],array($PrimaryLinked[0],'ImageID','Def'),array($ID,$IDs,'YES'));
				}else{
					 InsertIntoTable($mysqli,$ImagesLinked[0],array($PrimaryLinked[0],'ImageID','Def'),array($ID,$IDs,'NO'));
				}
			}

		}
	}else{
		InsertIntoTable($mysqli,trim($TableName),$AllFields,$FinalValue);
		$ProdID = FetchLatestEntry($mysqli);
		if(isset($OrderDetailsID)
		&& !empty($OrderDetailsID)){
			$stmt = $mysqli->prepare("DELETE FROM OrderDetails WHERE OrderID = '$ID'");
			$stmt->execute(); 
			
			foreach($OrderDetailsID as $Kd => $OrderID){
				if(!in_array('OrderID',$OrderFinal[$OrderID])){
					$OrderFinal[$OrderID][] = 'OrderID';
					$OrderFinalval[$OrderID][] = $ProdID;
				}
					$OrderFinal[$OrderID][] = $OrderDetailsName[$Kd];
					$OrderFinalval[$OrderID][] = $OrderDetailsVal[$Kd];
			}
			
			foreach($OrderFinal as $Jey => $OrderInput){
			InsertIntoTable($mysqli,'OrderDetails',$OrderInput,$OrderFinalval[$Jey]);
			}
		}elseif(isset($OrderDetailsName)
		&& !empty($OrderDetailsName)){
			foreach($OrderDetailsName as $Kd => $OrderName){
				if(!in_array('OrderID',$OrderFinal[$OrderName])){
					$OrderFinal[$OrderName][] = 'OrderID';
					$OrderFinalval[$OrderName][] = $ProdID;
				}
				$OrderFinal[$OrderName][] = $OrderDetailsName[$Kd];
				$OrderFinalval[$OrderName][] = $OrderDetailsVal[$Kd];
			}
				InsertIntoTable($mysqli,'OrderDetails',$OrderInput,$OrderFinalval[$Jey]);

		}
		if((isset($ProdNewPrice)
		&& !empty($ProdNewPrice))
		or(isset($ProdDiscount)
		&& !empty($ProdDiscount))){
			InsertIntoTable($mysqli,'FeaturedProducts', array('ProductID','Discount','FeaturePrice'), array($ProdID,$ProdDiscount,$ProdNewPrice));
		}
		$FilterTest = array_filter($OptionName);
		if(isset($FilterTest)
		&& !empty($FilterTest)){
			foreach($OptionName as $OptionNames){
				InsertIntoTable($mysqli,'OptionGroups', array('OptionGroupName'), array($OptionNames));
				$OptGrpID[] = FetchLatestEntry($mysqli);
			}
			foreach($OptGrpID as $Key => $OptGrp){
				InsertIntoTable($mysqli,'Options', array('OptionGroupID','OptionName'), array($OptGrp,$Options[$Key]));		
				$OptNameID[] = FetchLatestEntry($mysqli);	
			}
			foreach($OptNameID as $Keya => $OptNID){
				InsertIntoTable($mysqli,'ProductOptions', array('ProductID','OptionID','OptionStockLevels','OptionPrices'), array($ProdID,$OptNID,implode(',',$ProdOptStock[$Keya]),implode(',',$ProdOptCost[$Keya])));		
			}
		}
		if(isset($Images)
		&& !empty($Images)){
				foreach($LinkedTableName as $Key => $Value){
				foreach($LinkedTableName[$Key] as $NewKey => $NewValue){
					$ImagesLinked[] = $NewValue[0];
					$PrimaryLinked[] = $LinkedTablePrimary[$Key][$NewKey][0];
				}
			}
			foreach($Images as $Img){
				InsertIntoTable($mysqli,$ImagesLinked[1], array('FileLocation'), array($Img));
				$ImgID[] = FetchLatestEntry($mysqli);
			}
			foreach($ImgID as $Key => $IDs){

				if($Images[$Key] == $DefaultImage){

					InsertIntoTable($mysqli,$ImagesLinked[0], array($PrimaryLinked[0],'ImageID','Def'), array($ProdID,$IDs,'YES'));
				}else{
					InsertIntoTable($mysqli,$ImagesLinked[0], array($PrimaryLinked[0],'ImageID','Def'), array($ProdID,$IDs,'NO'));
				}
			}
		}
	}

	return 'Success';
	//InsertIntoTable($mysqli,'RepeatViews', array('IP','Date'),array('2','01/02/2016'));
	//return FetchLatestEntry($mysqli);
	}
}
function FetchLatestEntry($mysqli){
	return mysqli_insert_id($mysqli);
}
function RetrieveOptionValues($TableName, $ColumnName, $ID){
	$results = $mysqli->query("SELECT a.ProductID,a.OptionID,a.OptionStockLevels,a.OptionPrices");
			if(mysqli_num_rows($results) > 0){
				while($row = $results->fetch_array()) {
					
				}
				
			}
}
function PreviewUploadedImages($ImageArray, $Type, $Thumb,$mysqli){
	if($Thumb == 'Thumb'){
		// DeleteImageSingle DefaultImage
		foreach($ImageArray as $Image){
		$SplitImg = explode('/',$Image);
								$Images .= '<figure class="effect-lily ImagesMulti" id="'.'uploads/'.end($SplitImg).'" style="background-size:contain;background-repeat:no-repeat;background-image:url(http://'.$_SESSION['WebURL'].'/uploads/'.end($SplitImg).');"> 
								
                                  <figcaption style="text-align:right;">
                     				<button type="button" class="btn btn-danger btn-square RemoveImage DeleteImageSingle DefaultImage" id="'.'uploads/'.end($SplitImg).'">Remove</button>
								<br />';

                              // $Images .=' <label> Default Image <input type="radio" name="radio1" data-radio="iradio_square" class="DefaultImage NewDefault" id="'.'/uploads/'.end($SplitImg).'"></label>';

								  
                      		$Images .= '</figcaption>
                               </figure>';	
	}
	}elseif($Thumb == 'Text'){
		$Table = $_SESSION['TableName'];
		$results = $mysqli->query("SELECT * FROM TableManager WHERE TableName = '$Table'");
while($row = $results->fetch_array()){
	$VisFi = $row['VisibleFields'];
	$VisNa = $row['FieldNames'];
}
$Names = explode(',',$VisNa);
$Fields = explode(',',$VisFi);
		foreach($ImageArray as $Image){
$SplitImg = explode('/',$Image);
	/*$query = "SELECT * FROM ".$_SESSION['TableName'];

	$results = mysqli_query($mysqli,$query);
					$finfo = mysqli_fetch_fields($results);*/
								$Images .= '<figure class="effect-lily ImagesMulti" id="'.'uploads/'.end($SplitImg).'" style="background-size:contain;background-repeat:no-repeat;background-image:url(http://'.$_SESSION['WebURL'].'/uploads/'.end($SplitImg).');"> 
								
                                  <figcaption style="text-align:right;">
                     				<button type="button" class="btn btn-danger btn-square RemoveImage" id="'.'uploads/'.end($SplitImg).'">Remove</button>
								<br />';

                              // $Images .=' <label> Default Image <input type="radio" name="radio1" data-radio="iradio_square" class="DefaultImage NewDefault" id="'.'/uploads/'.end($SplitImg).'"></label>';

								  
                      		$Images .= '</figcaption>
                      		';
                      		$HeightDiff = 0;
foreach($Fields as $Kc => $Valz){
	
	if($Kc>0){
	$Images .='<div><input class="form-control InputField input-sm" id="'.$Valz.'" placeholder="'.$Names[$Kc].'
                      		" type="text" style=position:absolute;bottom:'.$HeightDiff*$Kc.'px;" /></div>';
                      		$HeightDiff = 20;
                      	}
                      	
}
                      		

                             $Images .='  </figure>';	
                           }
	}else{
	foreach($ImageArray as $Image){
		$SplitImg = explode('/',$Image);
								$Images .= '<figure class="effect-lily ImagesMulti" id="'.'uploads/'.end($SplitImg).'" style="background-size:contain;background-repeat:no-repeat;background-image:url(http://'.$_SESSION['WebURL'].'/uploads/'.end($SplitImg).');"> 
								
                                  <figcaption style="text-align:right;">
                     				<button type="button" class="btn btn-danger btn-square RemoveImage" id="'.'uploads/'.end($SplitImg).'">Remove</button>
								<br />';

                              // $Images .=' <label> Default Image <input type="radio" name="radio1" data-radio="iradio_square" class="DefaultImage NewDefault" id="'.'/uploads/'.end($SplitImg).'"></label>';

								  
                      		$Images .= '</figcaption>

                               </figure>';	
	}
	}
	
	
	if($Type == 'New'){
	$Final =  '<fieldset class="withScroll show-scroll ImagesPreview">
                          <legend>Upload/Edit Images</legend>
                          <div class="form-group" id="ImageManager">
                                <label for="exampleInputPassword1">Select Images</label>
                                <div class="row">
                                	<div class="col-lg-12 portlets">
                                		<div class="panel panel-transparent">
                                			<div class="panel-content">
                                <div class="portfolioContainer grid">
                            		'.$Images.'
                                  
                         		</div>
                       						</div>
                                        </div>
                                  </div>
                          </div></div>
                        </fieldset>';
	}else{
		$Final = $Images;	
	}
						return $Final;
}
function UpdateTables($mysqli,$TableName){
	$results = $mysqli->query("SELECT TableName,VisibleFieldsValues FROM TableManager WHERE ActiveTable = 'True' AND TableName = '$TableName'");
		$Count = 0;
	if(mysqli_num_rows($results) > 0){
		while($row = $results->fetch_array()) {
			$VisibleValues = $row['VisibleFieldsValues'];
		}
		$Values = explode(',',$VisibleValues);
	}
	if(strpos($TableName,'Categories') !== false
		or $TableName == 'Categories'){
	$Scripts .= '<script src="Pages/UpdateTables/UpdateCategories.js"></script>';
	}elseif($TableName == 'Products'){
	$Scripts .= '<script src="Pages/UpdateTables/UpdateProducts.js"></script>';
	}elseif($TableName == 'Orders'){
	$Scripts .= '<script src="Pages/UpdateTables/UpdateOrders.js"></script>';
	}else{
	$Scripts .='<script src="Pages/UpdateTables/UpdateGenericTable.js"></script>';	
	}
	if(strpos($VisibleValues,'ImagesMulti')
		or $VisibleValues == 'ImagesMulti'){
	$Scripts .=	' <script src="../assets/global/plugins/dropzone/dropzone.min.js"></script>';
	}elseif(strpos($VisibleValues,'Thumbnail')
		or $VisibleValues == 'Thumbnail'){
	$Scripts .=	' <script src="../assets/global/plugins/dropzone/dropzone.thumb.min.js"></script>';
	}elseif(strpos($VisibleValues,'GalleryText')
		or $VisibleValues == 'GalleryText'){
	$Scripts .=	' <script src="../assets/global/plugins/dropzone/dropzone.gallerytext.min.js"></script>';
	}
	return $Scripts
	;
}
function FetchTotalNotifications($mysqli){
	$results = $mysqli->query("SELECT ID FROM Notifications WHERE MarkRead = 'False'");
		$Count = 0;
	if(mysqli_num_rows($results) > 0){

	while($row = $results->fetch_array()) {
		$Count++;
    	
	}   	
	if($Count>0){
	return $Count.' Unread Notifications';
	}
	}else{
	return 'No New Notifications.';	
	}
	
}
function CheckPermission($mysqli, $Name){ //Used to return the website name 
$results = $mysqli->query("SELECT Permission FROM AdminPanel WHERE Name = '$Name'");
	while($row = $results->fetch_array()) {
		if($row["Permission"] == 'True'){
			
			return true;
		}else{
		return false;	
		}
    	
	}   	
}
function FetchOrderStats($mysqli){ //Used to return the website name 

$Date = date("Y-m-d");
$results = $mysqli->query("SELECT b.Price,b.OrderID, b.Quantity FROM Orders AS a INNER JOIN OrderDetails AS b ON a.OrderID = b.OrderID WHERE a.ActiveOrder = '1' AND MONTH(a.OrderDate) = MONTH(CURRENT_DATE)");
	while($row = $results->fetch_array()) {
		$Ordercosts[] = $row['Price']*$row['Quantity'];    	
		$Orders[] = $row['OrderID'];
	}   	
	if(empty($Orders)){
		$Costs[] = '£0.00';
		$OrderTotals[] = 0;
	}else{
	$Costs[] = '£'.number_format((float)array_sum($Ordercosts), 2, '.', '');
	$OrderTotals[] = count(array_unique($Orders));
	}

	

$results = $mysqli->query("SELECT b.Price,b.OrderID,b.Quantity FROM Orders AS a INNER JOIN OrderDetails AS b ON a.OrderID = b.OrderID WHERE a.ActiveOrder='1' AND a.OrderDate >= NOW() - INTERVAL 1 WEEK");
	while($row = $results->fetch_array()) {
		$OrdercostsA[] = $row['Price']*$row['Quantity'];    	
		$OrdersA[] = $row['OrderID'];
	}  	 
	if(empty($OrdersA)){
		$Costs[] = '£0.00';
		$OrderTotals[] = 0;
	}else{
	$Costs[] = '£'.number_format((float)array_sum($OrdercostsA), 2, '.', '');
	$OrderTotals[] = count(array_unique($OrdersA));
	}
	

$results = $mysqli->query("SELECT b.Price,b.OrderID,b.Quantity FROM Orders AS a INNER JOIN OrderDetails AS b ON a.OrderID = b.OrderID WHERE a.ActiveOrder='1' AND MONTH(a.OrderDate) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)");
	while($row = $results->fetch_array()) {
		$OrdercostsB[] = $row['Price']*$row['Quantity'];    	
		$OrdersB[] = $row['OrderID'];
	}  
	if(empty($OrdersB)){
		$Costs[] = '£0.00';
		$OrderTotals[] = 0;
	}else{
	$Costs[] = '£'.number_format((float)array_sum($OrdercostsB), 2, '.', '');
	$OrderTotals[] = count(array_unique($OrdersB));	
	}
	return array($Costs, $OrderTotals);


}
function FetchTotalViews($mysqli){//retrieves total views
$results = $mysqli->query("SELECT Views FROM TotalViews");
while($row = $results->fetch_array()) {

    return $row["Views"];
} 	
}
function FetchAccountID($mysqli, $Email){
$results = $mysqli->query("SELECT AccountID FROM Accounts WHERE Email = '$Email'");
while($row = $results->fetch_array()) {
	return $row['AccountID'];
}	 
}
function UpdateAccSetting($mysqli,$ID,$Column, $Status){
	
	if($Status == 'True'){
	$stmt = $mysqli->prepare("UPDATE Accounts SET ".$Column." = '1' WHERE  AccountID = '$ID'");
	$stmt->execute(); 
	}else{
	$stmt = $mysqli->prepare("UPDATE Accounts SET ".$Column." = '0' WHERE  AccountID = '$ID'");
	$stmt->execute(); 
	}
return;
}
function CheckAccSetting($mysqli,$ID,$Column){
	
	$results = $mysqli->query("SELECT ".$Column." FROM Accounts WHERE AccountID = '$ID'");
while($row = $results->fetch_array()) {
	if($row[$Column]>0){
	return 'checked';	
	}else{
	return;	
	}
}
}
function MarkLiveChatRead($mysqli,$SendID,$ReceivedID){
	if($SendID == 'ALL'){
		$stmt = $mysqli->prepare("UPDATE LiveChat SET MarkRead = 'True' WHERE  ReceivedID = '$ReceivedID'");
	$stmt->execute(); 
return;
	}else{
	$stmt = $mysqli->prepare("UPDATE LiveChat SET MarkRead = 'True' WHERE SentID = '$SendID' AND ReceivedID = '$ReceivedID' AND MarkRead = 'False'");
	$stmt->execute(); 
return;
	}
}
function CheckUnreadMessages($mysqli,$SendID, $ReceivedID){
	$Counter = 0;
	$results = $mysqli->query("SELECT ID FROM LiveChat WHERE SentID = '$SendID' AND ReceivedID = '$ReceivedID' AND MarkRead = 'False'");
	while($row = $results->fetch_array()) {
	$Counter++;
	}
if($Counter>0){
return '<div class="pull-right badge badge-danger">'.$Counter.'</div>';	
}else{
return;	
}
	
}
function CheckUnreadMessagesTotal($mysqli,$ReceivedID){
	$Counter = 0;
	$results = $mysqli->query("SELECT ID FROM LiveChat WHERE ReceivedID = '$ReceivedID' AND MarkRead = 'False'");
	while($row = $results->fetch_array()) {
	$Counter++;
	}
if($Counter>0){
return '<span class="badge badge-danger badge-header">'.$Counter.'</span>';	
}else{
return ' ';	
}
	
}
function FetchLiveChatMessages($mysqli, $Email, $MessageID){
	$results = $mysqli->query("SELECT AccountID FROM Accounts WHERE Email = '$Email'");
while($row = $results->fetch_array()) {
	$ID = $row['AccountID'];
}//SELECT b.Price,b.OrderID, b.Quantity FROM Orders AS a INNER JOIN OrderDetails AS b ON a.OrderID = b.OrderID
	$results = $mysqli->query("SELECT a.Date,a.Message,a.ReceivedID,a.SentID,a.MarkRead,b.AccountID,b.Profile FROM LiveChat AS a INNER JOIN Accounts AS b ON a.SentID = b.AccountID WHERE a.SentID = '$ID' AND a.ReceivedID = '$MessageID'");
while($row = $results->fetch_array()) {
	$Messages[$row['Date']] = ' <li class="img"><span>
	<div class="chat-detail chat-right" >
                   
				 
					 <img title="Sent '.date('j M Y g:i A', strtotime($row['Date'])).'" src="../../../assets/global/images/avatars/'.$row['Profile'].'" data-retina-src="assets/images/avatars/avatar1_2x.png"/>
					  <div class="chat-detail">';
                      if($row['MarkRead'] == 'True'){
						  $Messages[$row['Date']] = $Messages[$row['Date']].'<div class="chat-bubble" title="Seen">
                        <span>'.$row['Message'].'</span>
                      </div>
                    </div></div></span>
                  </li>';
					  }else{
					$Messages[$row['Date']] = $Messages[$row['Date']].'<div class="chat-bubble" title="Unread">
                        <span>'.$row['Message'].'</span>
                      </div>
                    </div></div></span>
                  </li>';
					  }
                     
					  
                      
				  
				  
}
$results = $mysqli->query("SELECT a.Date,a.Message,a.ReceivedID,a.SentID,b.AccountID,a.MarkRead,b.Profile FROM LiveChat AS a INNER JOIN Accounts AS b ON a.SentID = b.AccountID WHERE a.SentID = '$MessageID' AND a.ReceivedID = '$ID'");
while($row = $results->fetch_array()) {
	$Messages[$row['Date']] = ' <li class="img">
                    <div class="chat-detail" >
                      <span class="chat-date">'.date('j M Y g:i A', strtotime($row['Date'])).'</span>
                      <div class="conversation-img">
                        <img title="'.date('j M Y g:i A', strtotime($row['Date'])).'" src="../../../assets/global/images/avatars/'.$row['Profile'].'" alt="avatar 4"/>
                      </div>';
					  if($row['MarkRead'] == 'True'){
						  $Messages[$row['Date']] = $Messages[$row['Date']].'
                      <div class="chat-bubble" title="Seen">
                        <span>'.$row['Message'].'</span>
                      </div>
                    </div>
                  </li>';
					  }else{
						  $Messages[$row['Date']] = $Messages[$row['Date']].'
                      <div class="chat-bubble" title="Unread">
                        <span>'.$row['Message'].'</span>
                      </div>
                    </div>
                  </li>';
					  }
}
$SortedMessages = ksort($Messages);
return '<ul>'.implode(' ',$Messages).'</ul>';

}
function CheckAccSettings($mysqli,$ID, $Column){
	$results = $mysqli->query("SELECT ".$Column." FROM Accounts WHERE AccountID = '$ID'");

while($row = $results->fetch_array()) {
	return $row[$Column];
}
}
function SetStatus($mysqli,$Status,$AccID){
	if($Status == 'SetOnline'){
	$stmt = $mysqli->prepare("UPDATE Accounts SET Status = 'Available' WHERE  AccountID = '$AccID'");
	$stmt->execute(); 
	return 's';
	}elseif($Status == 'SetBusy'){
	$stmt = $mysqli->prepare("UPDATE Accounts SET Status = 'Busy' WHERE  AccountID = '$AccID'");
	$stmt->execute(); 
	}else{
	$stmt = $mysqli->prepare("UPDATE Accounts SET Status = 'False' WHERE  AccountID = '$AccID'");
	$stmt->execute(); 
	}
	return;
}
function CheckStatus($mysqli,$ID){
	if(CheckAccSettings($mysqli,$ID,'ShowAvailability')>0){
		$results = $mysqli->query("SELECT Status FROM Accounts WHERE AccountID = '$ID'");
		while($row = $results->fetch_array()) {
	return $row['Status'];

		}
	}else{
		
		return 'Invisible';
		
	}
}
function FetchUsersChat($mysqli,$ID){
	if(CheckAccSettings($mysqli,$ID,'ShowFullName')>0){
	$results = $mysqli->query("SELECT AccountID,FirstName,LastName,Profile,Status FROM Accounts WHERE Status != 'False' AND AccountID != '$ID'");
	}else{
	$results = $mysqli->query("SELECT AccountID,FirstName,Profile,Status FROM Accounts WHERE Status != 'False' AND AccountID != '$ID'");
	}
$Count = 0;
while($row = $results->fetch_array()) {
	$User[$Count]['Name'] = $row['FirstName'];
	if(CheckAccSettings($mysqli,$ID,'ShowFullName')>0){
	$User[$Count]['LastName'] = $row['LastName'];
	}
	$User[$Count]['Profile'] = $row['Profile'];
	$User[$Count]['Status'] = $row['Status'];
	$User[$Count]['ID'] = $row['AccountID'];
	$Count++; 
} 	
return $User;
}
function FetchUniqueViews($mysqli){//Retrieves all unique views
$results = $mysqli->query("SELECT ID FROM UniqueViews");

$Views = 0;
while($row = $results->fetch_array()) {

    $Views++;


} 	
return $Views;
}
function FetchNotifications($mysqli){//Retrieves all unique views

$results = $mysqli->query("SELECT * FROM Notifications WHERE MarkRead = 'False'");
date_default_timezone_set('Europe/London');
$datetime1 = new DateTime();
$Count = 0;
while($row = $results->fetch_array()) {
$datetime2 = new DateTime($row['Date']);
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%a days');
// %h hours %i minutes %S seconds
if($elapsed == '0 days'){
	$elapsed = $interval->format('%h hours');
	if($elapsed == '0 hours'){
		$elapsed = $interval->format('%i minutes');
		if($elapsed == '0 minutes'){
			$elapsed = $interval->format('%S seconds');
		}elseif($elapsed == '1 minutes'){
			$elapsed = '1 minute';	
		}
	}elseif($elapsed =='1 hours'){
		$elapsed = '1 hour';
	}
}elseif($elapsed == '1 days'){
	$elapsed = '1 day';	
}

	
	$Count++;
    $Notifications[] = '<li >
                        <a href="'.$row['Link'].'" class="NotificationLink" id="Noty'.$row['ID'].'">
                        <i class="'.$row['Icon'].'"></i>
                       '.$row['Message'].'
                        <span class="dropdown-time">'.ucwords($elapsed).' Ago</span>
                        </a>
                        </li>';




} 	
return array($Notifications , $Count);
}
function MarkNotificationRead($mysqli, $ID){
	if($ID == 'All'){
	$stmt = $mysqli->prepare("UPDATE Notifications SET MarkRead = 'True',Icon = 'fa fa-check'");
	$stmt->execute(); 	
	return;
	}else{
	$Search = explode('y',$ID);
	$Lookup = $Search[1];
	$stmt = $mysqli->prepare("UPDATE Notifications SET MarkRead = 'True', Icon = 'fa fa-check' WHERE ID = '$Lookup'");
	$stmt->execute(); 
	return $Lookup;
	}
}
function FetchTotalSales($mysqli){ //Retrieves total sales
$results = $mysqli->query("SELECT OrderID FROM Orders WHERE ActiveOrder = '1'");

$Views = 0;
while($row = $results->fetch_array()) {

    $Views++;


} 	
return $Views;

}
function FetchTotalSalesRevenue($mysqli){ //Retrieves total revenue from sales
$results = $mysqli->query("SELECT b.Price,b.OrderID, b.Quantity FROM Orders AS a INNER JOIN OrderDetails AS b ON a.OrderID = b.OrderID WHERE a.ActiveOrder = '1'");
	while($row = $results->fetch_array()) {
		$Ordercosts[] = $row['Price']*$row['Quantity'];    	
	}   	
 	
return '£'.number_format((float)array_sum($Ordercosts), 2, '.', '');;
}
function FetchTotalPayPalFee($mysqli){ //Retrieves total revenue from sales
$results = $mysqli->query("SELECT PayPalFee FROM Orders WHERE ActiveOrder = '1'");
	while($row = $results->fetch_array()) {
		$Ordercosts[] = $row['PayPalFee'];    	
	}   	
 	
return '£'.number_format((float)array_sum($Ordercosts), 2, '.', '');;
}
function FetchTotalProductsSold($mysqli){ //Retrieves total revenue from sales
$results = $mysqli->query("SELECT a.OrderDetailID, a.Quantity FROM OrderDetails AS a INNER JOIN Orders AS b ON a.OrderID = b.OrderID WHERE b.ActiveOrder = '1'");
$Count = 0;
	while($row = $results->fetch_array()) {
		$Count +=  $row['Quantity'];	
	}   	
 	
return $Count;
}
function CleanString($String){//Used to clean strings ready for database user
	$cleanfirstname = filter_var($String, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
	$StringClean = mysql_real_escape_string($cleanfirstname);
	return $StringClean;
}
function LookupUniqueViewsOverPeriods($WebsiteConnect){ //Used to return the views in specific date ranges from the database
$TodaysDate = date("d/m/Y");
 $query = "SELECT ID FROM UniqueViews WHERE Date = '$TodaysDate'";
		 $result = mysql_query($query, $WebsiteConnect);
		 $X = 0;
		while($row = mysql_fetch_array($result)){  
		$X++;
		}
		$Date = date("Y-m-j G:i:s");
		$Date = date ("d/m/Y", strtotime ( '-1 day' . $Date ) );
 $query = "SELECT ID FROM UniqueViews WHERE Date = '$Date'";
		 $result = mysql_query($query, $WebsiteConnect);
		 $Z = 0;
		while($row = mysql_fetch_array($result)){  
		$Z++;
		}
for($i=0; $i<6; $i++){
    $last_week_dates[] = date('d/m/Y', strtotime('last monday + '.$i.' day'));
}
 $A = 0;
foreach($last_week_dates as $Date){
 $query = "SELECT ID FROM UniqueViews WHERE Date = '$Date'";
		 $result = mysql_query($query, $WebsiteConnect);
		
		while($row = mysql_fetch_array($result)){  
		$A++;
		}
}	

return array($A, $Z, $X);
}
function DateRange( $first, $last, $step = '+1 day', $format = 'd/m/Y' ) {

	$dates = array();
	$current = strtotime( $first );
	$last = strtotime( $last );

	while( $current <= $last ) {

		$dates[] = date( $format, $current );
		$current = strtotime( $step, $current );
	}

	return $dates;
}
function CheckIfRowExists($mysqli,$TableName,$Column,$Value, $Live){
	if(isset($Live)
	&& !empty($Live)){
	$results = $mysqli->query("SELECT ".$Column." FROM ".$TableName." WHERE ".$Column." = '$Value' AND ".$Live." = '1'");
	}else{
	$results = $mysqli->query("SELECT ".$Column." FROM ".$TableName." WHERE ".$Column." = '$Value'");
	}

	if(mysqli_num_rows($results) > 0){
		return true;
	}else{
		return false;
	}
}
function MainGraphsJSON($mysqli, $Selector, $Range){//retrieves total views
if($Selector == 'Unique'){
$results = $mysqli->query("SELECT ID, Date FROM UniqueViews");
$Count = 0;
while($row = $results->fetch_array()) {
	$Count++;
	if($Count == 1){
	$Start = $row['Date'];	
	}
	$End = $row['Date'];
   $Date[$row['Date']]++ ;
}

$dated = str_replace('/', '-', $Start);


$DateSelection = dateRange(date('Y-m-d', strtotime($dated)), date('Y/m/d', strtotime(str_replace('/', '-', $End))));
for($x = 0; $x<count($DateSelection);$x++){
	if(array_key_exists($DateSelection[$x],$Date)){
	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), $Date[$DateSelection[$x]]);
	}else{
	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), 0);	
	}
}


	return json_encode($UniqueViews);
}elseif($Selector == 'Total'){
	$results = $mysqli->query("SELECT ID, Date FROM TotalViewsDated");
$Count = 0;
while($row = $results->fetch_array()) {
	$Count++;
	if($Count == 1){
	$Start = $row['Date'];	
	}
	$End = $row['Date'];
   $Date[$row['Date']]++ ;
 
}
$dated = str_replace('/', '-', $Start);


$DateSelection = dateRange(date('Y-m-d', strtotime($dated)), date("Y-m-d"));
for($x = 0; $x<count($DateSelection);$x++){
	if(array_key_exists($DateSelection[$x],$Date)){
	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), $Date[$DateSelection[$x]]);
	}else{
	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), 0);	
	}
}

	return json_encode($UniqueViews);
}elseif($Selector == 'Orders'){
		$results = $mysqli->query("SELECT OrderID, OrderDate FROM Orders WHERE ActiveOrder = '1'");
$Count = 0;
while($row = $results->fetch_array()) {
	$Count++;
	if($Count == 1){
	$Start = $row['OrderDate'];	
	}
	$End = $row['OrderDate'];
   $Date[$row['OrderDate']]++ ;
 
}



$DateSelection = dateRange( $Start, date("Y-m-d"));
for($x = 0; $x<count($DateSelection);$x++){
	if(array_key_exists(date('Y-m-d', strtotime(str_replace('/', '-', $DateSelection[$x]))),$Date)){


	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), $Date[date('Y-m-d', strtotime(str_replace('/', '-', $DateSelection[$x])))]);
	}else{
	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), 0);	
	}
}

	return json_encode($UniqueViews);
}elseif($Selector == 'UniqueRange'){
$results = $mysqli->query("SELECT ID, Date FROM UniqueViews");
while($row = $results->fetch_array()) {


   $Date[$row['Date']]++ ;
}




$DateSelection = dateRange(date('Y-m-d', strtotime('today - '.$Range.'')), date('Y/m/d'));
for($x = 0; $x<count($DateSelection);$x++){
	if(array_key_exists($DateSelection[$x],$Date)){
	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), $Date[$DateSelection[$x]]);
	}else{
	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), 0);	
	}
}


	return json_encode($UniqueViews);
}elseif($Selector == 'Revenue'){
	$results = $mysqli->query("SELECT b.Price,b.OrderID, a.OrderDate, b.Quantity FROM Orders AS a INNER JOIN OrderDetails AS b ON a.OrderID = b.OrderID WHERE a.ActiveOrder = '1'");
$Count = 0;
while($row = $results->fetch_array()) {
	$Count++;
	if($Count == 1){
	$Start = $row['OrderDate'];	
	}
	$End = $row['OrderDate'];
   $Date[$row['OrderDate']] += $row['Price']*$row['Quantity'];
 
}



$DateSelection = dateRange( $Start, date("Y-m-d"));
for($x = 0; $x<count($DateSelection);$x++){
	if(array_key_exists(date('Y-m-d', strtotime(str_replace('/', '-', $DateSelection[$x]))),$Date)){


	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), $Date[date('Y-m-d', strtotime(str_replace('/', '-', $DateSelection[$x])))]);
	}else{
	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), 0);	
	}
}

	return json_encode($UniqueViews);
}elseif($Selector == 'SalesVolume'){
		$results = $mysqli->query("SELECT b.OrderDetailID, a.OrderDate, b.Quantity FROM Orders AS a INNER JOIN OrderDetails AS b ON a.OrderID = b.OrderID WHERE a.ActiveOrder = '1'");
$Count = 0;
while($row = $results->fetch_array()) {
	$Count++;
	if($Count == 1){
	$Start = $row['OrderDate'];	
	}
	$End = $row['OrderDate'];
   $Date[$row['OrderDate']] +=  $row['Quantity'];
 
}



$DateSelection = dateRange( $Start, date("Y-m-d"));
for($x = 0; $x<count($DateSelection);$x++){
	if(array_key_exists(date('Y-m-d', strtotime(str_replace('/', '-', $DateSelection[$x]))),$Date)){


	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), $Date[date('Y-m-d', strtotime(str_replace('/', '-', $DateSelection[$x])))]);
	}else{
	$UniqueViews[] = array((DateToTimeStamp($DateSelection[$x],'d/m/Y')*1000), 0);	
	}
}

	return json_encode($UniqueViews);
}
}
function LookupViewsRange($mysqli, $Selector, $Range){
	if($Selector == 'Unique'){
	$results = $mysqli->query("SELECT ID, Date FROM UniqueViews");
	
while($row = $results->fetch_array()) {


   $Date[$row['Date']]++ ;
}




$DateSelection = dateRange(date('Y-m-d', strtotime('today - '.$Range.'')), date('Y/m/d'));
for($x = 0; $x<count($DateSelection);$x++){
	if(array_key_exists($DateSelection[$x],$Date)){
	$UniqueViews[] = $Date[$DateSelection[$x]];
	}else{
	$UniqueViews[] = 0;	
	}
}


	return array_sum($UniqueViews);
	}
}
function UniqueViewByAreaJSON($WebsiteConnect){//Fetches all unique views with the area for use in the world map
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 


							
$query = "SELECT * FROM UniqueViews";
		 $result = mysql_query($query, $WebsiteConnect);
$X = 0;
		while($row = mysql_fetch_array($result)){
			$ips[$X] = $row['IP'];
$X++;
}

$Z = 0;
$db_host = "localhost";
$db_username = "madmunster";
$db_password = "#wsoX6lsk1lV";
$db_name = "madmunst_Anglers";

$Connect = mysql_connect ("$db_host","$db_username","$db_password") or die ("Could not connect to MySQL");
mysql_select_db("$db_name", $Connect) or die("No database");

$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
$conn = new mysqli($db_host, $db_username, $db_password, $db_name);
foreach($ips as $ipadd){
$sql = 'SELECT 
	            c.country, i.country
	        FROM 
	            ip2nationCountries c,
	            ip2nation i 
	        WHERE 
	            i.ip < INET_ATON("'.$ipadd.'") 
	            AND 
	            c.code = i.country 
	        ORDER BY 
	            i.ip DESC 
	        LIMIT 0,1';
	
	list($countryName[$Z]) = mysql_fetch_row(mysql_query($sql, $Connect));
	$Z++;
	// Output full country name
	

}
$Duplicates = array_count_values($countryName);
				$countryNameUnique = array_unique($countryName);
				$total = 0;
		foreach($countryNameUnique as $country){
			if(!empty($Duplicates[$country])){
				$query = "SELECT code FROM ip2nationCountries WHERE country = '$country' ";
		 $result = mysql_query($query, $Connect);

		while($row = mysql_fetch_array($result)){
		$Code = $row['code'];
}
if($country !== 'Private'){
	if($Code == 'uk'){
		$Code = 'GB';
		if($Duplicates[$country]>100){
		#d8854f
		$Area[] = array(code=> strtoupper($Code),
           name=> $country,
           value=> $Duplicates[$country],
          color=> "#d8854f");
		}else{
		$Area[] = array(code=> strtoupper($Code),
           name=> $country,
           value=> $Duplicates[$country],
          color=> "#8aabb0");	
		}
}else{
	if($Duplicates[$country]>100){
		#d8854f
		$Area[] = array(code=> strtoupper($Code),
           name=> $country,
           value=> $Duplicates[$country],
          color=> "#d8854f");
		}else{
		$Area[] = array(code=> strtoupper($Code),
           name=> $country,
           value=> $Duplicates[$country],
          color=> "#8aabb0");	
		}
}
}
		}
			
}
foreach($Area as $item){
$Output .= json_encode($item).'@@@';	

}
return $Output;
}






function RetrieveViewsPrevMonths($WebsiteConnect, $HistoryLength, $UniqueStatus){// Retrieves views in JSON format
	if($UniqueStatus == 'Months'){
		for ($i = 1; $i <=  $HistoryLength; $i++) {
    $months[] = date("m", strtotime( Date( 'Y-m' )." -$i months"));
		}
	foreach($months as $monthNum){
		$dateObj   = DateTime::createFromFormat('!m', $monthNum);
		$monthName[] = $dateObj->format('F');
	}
	return json_encode(array_reverse($monthName));

		
	}elseif($UniqueStatus == 'TotalViewsDated'){
		
	for ($i = 1; $i <=  $HistoryLength; $i++) {
    $months[] = date("m/Y", strtotime( Date( 'Y-m' )." -$i months"));
}
 $Z = 0;
foreach($months as $SearchMonthYear){
	$SearchMonthYear = '%/'.$SearchMonthYear;
 $query = "SELECT ID FROM ".$UniqueStatus." WHERE Date LIKE '$SearchMonthYear'";
		 $result = mysql_query($query, $WebsiteConnect);
		
		while($row = mysql_fetch_array($result)){  
		$Views[$Z] ++;
		}
		if($Views[$Z]<1){
		$Views[$Z] = 0;
		}
		$Z++;
}

	

return json_encode(array_reverse($Views));	
		
		
	}else{
for ($i = 1; $i <=  $HistoryLength; $i++) {
    $months[] = date("m/Y", strtotime( Date( 'Y-m' )." -$i months"));
}
 $Z = 0;
foreach($months as $SearchMonthYear){
	$SearchMonthYear = '%/'.$SearchMonthYear;
 $query = "SELECT ID FROM ".$UniqueStatus." WHERE Date LIKE '$SearchMonthYear'";
		 $result = mysql_query($query, $WebsiteConnect);
		
		while($row = mysql_fetch_array($result)){  
		$Views[$Z] ++;
		}
		if($Views[$Z]<1){
		$Views[$Z] = 0;
		}
		$Z++;
}

	

return json_encode(array_reverse($Views));
}
}
function RenameToPHP($directory){// Renanmes all HTML files to PHP
foreach (glob($directory."*.html") as $filename) {
    $file = realpath($filename);
    rename($file, str_replace(".html",".php",$file));
}
}
function DateToTimeStamp($Date,$Format){//Converts any date to a timestamp
	$dt = DateTime::createFromFormat($Format, $Date);
	return $dt->getTimestamp();
}
function hex2rgb($hex) {// Converts Hexadecimal to RGB
   $hex = str_replace("#", "", $hex);

   if(strlen($hex) == 3) {
      $r = hexdec(substr($hex,0,1).substr($hex,0,1));
      $g = hexdec(substr($hex,1,1).substr($hex,1,1));
      $b = hexdec(substr($hex,2,1).substr($hex,2,1));
   } else {
      $r = hexdec(substr($hex,0,2));
      $g = hexdec(substr($hex,2,2));
      $b = hexdec(substr($hex,4,2));
   }
   $rgb = array($r, $g, $b);
   return implode(",", $rgb); // returns the rgb values separated by commas
   //return $rgb; // returns an array with the rgb values
}
function ReturnMostCommonColour($CSS){ //Returns all hex colours in a string
preg_match_all('/#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})[\s;]*\n/',$CSS,$matches);

return $matches;
}
function MostCommonArray($input){ //Returns the most common elements in an array, limited to 4
$result = array_count_values($input);
 asort($result);
 $NewResults = array_reverse($result);
 $itemOld = 0;
 foreach($NewResults as $key => $item){
	 if($itemOld<4){
		$CommonColours[] = $key; 
	 }else{
		break; 
	 } 
	  $itemOld++;
 }

return  $CommonColours;
}
function ReturnArrayInMostCommonOrder($input){ //Returns the most common elements in an array
$result = array_count_values($input);
 asort($result);
 $NewResults = array_reverse($result);
 foreach($NewResults as $key => $item){
	$CommonColours[] = $key; 
 }

return  $CommonColours;
}



function RetrieveFiles($Directory, $Type){ //Searches directory with the file extension type, returns as array
$di = new RecursiveDirectoryIterator($Directory);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    $Files[] = $filename;
}
foreach($Files as $FileName){
foreach(explode('/',$FileName) as $File){
		if (strpos($File,$Type) !== false) {
			
			if(strpos($FileName,'Functions') !==false){
				
			}else{
			if(strpos($FileName,'PHP') !==false){
				
			}else{
			if(strpos($FileName,'scripts') !==false){
				
				
			}else{
				if(strpos($FileName,'DatabaseBuilder') !==false){
				
			}else{
				if(strpos($FileName,'PageEditor') !==false){
				
			}else{
			$FileArr[] = $FileName;	
			}
			}
			}
			}
			}
			
		}
}
}
return $FileArr;
}
function RetrieveFilesLimit($Directory, $Type){ //Searches directory with the file extension type, returns as array
$di = new RecursiveDirectoryIterator($Directory);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    $Files[] = $filename;
}
foreach($Files as $FileName){
foreach(explode('/',$FileName) as $File){
		if (strpos($File,$Type) !== false) {
			if(strpos($FileName, 'Page') !== false){

			
			}else{
			
			if(strpos($FileName, 'PHP') !== false){
			
			}else{
				$FileArr[] = $FileName;	
			}
			
				
			}
			
			
		}
}
}
return $FileArr;
}
function RetrieveColours($Path, $Type){//Retrieves all colours from a file, accept file path and file type as parameters, returns an array
foreach(RetrieveFiles($Path,$Type) as $File){
$Colours[] = ReturnMostCommonColour(file_get_contents($File));
}
foreach($Colours as $SheetArr){
	foreach($SheetArr as $Sheet){
		foreach($Sheet as $Colour){
		$ColourArray[] = $Colour;		
		}
	
	}
 
}
return $ColourArray;
}
function CheckStringContained($String, $Contained){//Checks a string for another string
if (strpos($Contained,$String) !== false) {
    return true;
}else{
return false;	
}
}
function CheckDirectoryEmpty($Directory){ //Checks if a directory is empty, returns true if it is.
$dirPath = $Directory;

$destdir = $dirPath;

$handle = opendir($destdir);
$c = 0;
while ($file = readdir($handle)&& $c<3) {
    $c++;
}

if ($c>2) {
    return false;
} else {
    return true;
} 
}
function AutoCheck($Check){//Used instead of an isset/!empty if statement, returns true if all elements in check array are set and not empty
	$Proceed = false;
	$Counter = 0;
foreach($Check as $item){
if(isset($item) && !empty($item)){
	

}else{
$Counter++;	
}
}
if($Counter == 0){
$Proceed = true;	

}else{
$Proceed = false;	
}
return $Proceed;
}
function NavigationBar($HTML, $ID, $Class, $Node){ //Used to create a dynamic navbar in all php pages
	mysql_query("UPDATE Elements SET Node=CONCAT(Node,'$Node,') WHERE ID='2'");
	mysql_query("UPDATE Elements SET Class=CONCAT(Class,'$Class,') WHERE ID='2'");
	mysql_query("UPDATE Elements SET DivID=CONCAT(DivID,,$ID,') WHERE ID='2'");
	file_put_contents('../../FileManager/files/Pages/Navbar.php',str_replace('.html','.php',$HTML));
	$IncludePage = "<?php INCLUDE'Pages/Navbar.php'; ?>";
	$f =0;
	$start = substr($HTML, 0, 60);
	$end = substr($HTML, -60);
	
	foreach(RetrieveFiles('../../FileManager/files', '.php') as $FileName){
		file_put_contents($FileName, preg_replace('#('.preg_quote($start).')(.*)('.preg_quote($end).')#si',$IncludePage,html_entity_decode(file_get_contents($FileName))));
	}
}
function FindStartElement($start, $FileName){
				if(strlen($start)<4){
					return $start;
				}else if(preg_match($start, file_get_contents($FileName))){
			return $start;
		}else{
			return FindStartElement(substr($start,0,-1), $FileName);
		}
}
function StringBetween($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

function FindCode($FileSingle, $start, $end){// takes filesingle and start/end (from SearchForHTML), returns true if the code is found, false if not
if(strpos(trim(preg_replace('/\s\s+/', ' ', $FileSingle)), trim(preg_replace('/\s\s+/', ' ',trim(preg_replace('/\s\s+/', ' ', $start)).StringBetween(trim(preg_replace('/\s\s+/', ' ', $FileSingle)),trim(preg_replace('/\s\s+/', ' ', $start)), trim(preg_replace('/\s\s+/', ' ', $end))).trim(preg_replace('/\s\s+/', ' ', $end)))))!== false){
	return true;
}else{
	return false;
}
}
function SearchForHTML($HTML, $FileName){//Searches filename for html, returns true if found- false if not found
		$CheckSize = strlen($HTML); 
		$Checker = true;
		$FileSingle = file_get_contents($FileName);
		
		while($Checker){
	$StringChecks = CheckStringSizeCalc($HTML, $CheckSize, $Name);
	$start = $StringChecks[0];
	$end = $StringChecks[1];
	$DynamicStart = $StringChecks[2];
	$DynamicLength = $StringChecks[3];
	$CheckSize = ($CheckSize-$DynamicLength);
				/*if(strpos(trim(preg_replace('/\s\s+/', ' ', $FileSingle)), trim(preg_replace('/\s\s+/', ' ', $start))) !== false){
				EditConsole('Found Start'.trim(preg_replace('/\s\s+/', ' ', $start)).trim(preg_replace('/\s\s+/', ' ', $end)).'@@@'.$FileName,'');
				}
				if(strpos(trim(preg_replace('/\s\s+/', ' ', $FileSingle)), trim(preg_replace('/\s\s+/', ' ', $end))) !== false){
				EditConsole('Found End'.trim(preg_replace('/\s\s+/', ' ', $end)).$FileName,'');
				}*/

			/*if(strpos(trim(preg_replace('/\s\s+/', ' ', $FileSingle)), trim(preg_replace('/\s\s+/', ' ',trim(preg_replace('/\s\s+/', ' ', $start)).StringBetween(trim(preg_replace('/\s\s+/', ' ', $FileSingle)),trim(preg_replace('/\s\s+/', ' ', $start)), trim(preg_replace('/\s\s+/', ' ', $end))).trim(preg_replace('/\s\s+/', ' ', $end))))) !== false){	*/
			
			if(FindCode($FileSingle, $start, $end) !== false){	
			
		//if(strpos($FileSingle, $start.StringBetween($FileSingle, $start, $end).$end) !== false){
			return true;
			 
			
		}else{
			if($CheckSize>20){
				
			$CheckSize = $CheckSize -1;
			//$StringChecks = CheckStringSizeCalc($HTML, $CheckSize, $Name);
			//$start = $StringChecks[0];
			//$end = $StringChecks[1];
			//EditConsole($start.$end,'');
			//$DynamicStart = $StringChecks[2];
			//EditConsole($CheckSize,'');
			}else{
				
				//EditConsole('Unable to make the element dynamic'.$start.$end,'');
			return false;
			}
			
			
			
		}
		
		}
}
function CreateDynamicElement($HTML, $ID, $Class, $Node, $Name){ //Used to create a dynamic navbar in all php pages
file_put_contents('../../FileManager/files/Pages/'.$Name.'.php',$HTML);
	$CheckElement = mysql_query("SELECT ElementName from Elements WHERE ElementName = '$Name'");
	if (mysql_num_rows($CheckElement) > 0) {
	mysql_query("UPDATE Elements SET Node=CONCAT(Node,'$Node,') WHERE ElementName='$Name'");
	mysql_query("UPDATE Elements SET Class=CONCAT(Class,'$Class,') WHERE ElementName='$Name'");
	mysql_query("UPDATE Elements SET DivID=CONCAT(DivID,$ID,') WHERE ElementName='$Name'");
	}else{
	mysql_query("INSERT INTO Elements (ElementName,Node,Class,DivID) VALUES ('$Name', '$Node,','$Class,','$ID,')");	
	}
	
	$IncludePage = "<!--Start-".$Name."--><?php INCLUDE'Pages/".$Name.".php'; ?><!--End-".$Name."-->";
	
	 $Changer = random_string(6);

	foreach(RetrieveFilesLimit('../../FileManager/files', '.php') as $FileName){
		
		$CheckSize = strlen($HTML); 
		$Checker = true;
		$FileSingle = file_get_contents($FileName);
		
		while($Checker){
	$StringChecks = CheckStringSizeCalc($HTML, $CheckSize, $Name);
	$start = $StringChecks[0];
	$end = $StringChecks[1];
	$DynamicStart = $StringChecks[2];
	$DynamicLength = $StringChecks[3];
	$CheckSize = ($CheckSize-$DynamicLength);
	
				/*if(strpos(trim(preg_replace('/\s\s+/', ' ', $FileSingle)), trim(preg_replace('/\s\s+/', ' ', $start))) !== false){
				EditConsole('Found Start'.trim(preg_replace('/\s\s+/', ' ', $start)).trim(preg_replace('/\s\s+/', ' ', $end)).'@@@'.$FileName,'');
				}
				if(strpos(trim(preg_replace('/\s\s+/', ' ', $FileSingle)), trim(preg_replace('/\s\s+/', ' ', $end))) !== false){
				EditConsole('Found End'.trim(preg_replace('/\s\s+/', ' ', $end)).$FileName,'');
				}*/

			/*if(strpos(trim(preg_replace('/\s\s+/', ' ', $FileSingle)), trim(preg_replace('/\s\s+/', ' ',trim(preg_replace('/\s\s+/', ' ', $start)).StringBetween(trim(preg_replace('/\s\s+/', ' ', $FileSingle)),trim(preg_replace('/\s\s+/', ' ', $start)), trim(preg_replace('/\s\s+/', ' ', $end))).trim(preg_replace('/\s\s+/', ' ', $end))))) !== false){	*/
			
			if(FindCode($FileSingle, $start, $end) !== false){
			
			
			CreateBackup($FileName, $Changer);
		//if(strpos($FileSingle, $start.StringBetween($FileSingle, $start, $end).$end) !== false){
			file_put_contents($FileName,str_replace(trim(preg_replace('/\s\s+/', ' ',trim(preg_replace('/\s\s+/', ' ', $start)).StringBetween(trim(preg_replace('/\s\s+/', ' ', $FileSingle)),trim(preg_replace('/\s\s+/', ' ', $start)), trim(preg_replace('/\s\s+/', ' ', $end))).trim(preg_replace('/\s\s+/', ' ', $end)))),$IncludePage,trim(preg_replace('/\s\s+/', ' ', $FileSingle))));
	
	
	EditConsole('Dynamic element created: '.$Name,'');		 
			break;	
		}else{
			if($CheckSize>20){
				
			$CheckSize = $CheckSize -1;
			//$StringChecks = CheckStringSizeCalc($HTML, $CheckSize, $Name);
			//$start = $StringChecks[0];
			//$end = $StringChecks[1];
			//EditConsole($start.$end,'');
			//$DynamicStart = $StringChecks[2];
			//EditConsole($CheckSize,'');
			}else{
				EditConsole('Unable to create dynamic element: '.$Name,'');
				//EditConsole('Unable to make the element dynamic'.$start.$end,'');
			break;	
			}
			
			
			
		}
		
		}
			//file_put_contents('../../FileManager/files/Pages/'.$Name.'.php',$HTML);

			//file_put_contents($FileName,str_replace($start.StringBetween(file_get_contents($FileName), $start, $end).$end,$IncludePage,file_get_contents($FileName)));
			
		//file_put_contents($FileName, preg_replace('#('.preg_quote(FindStartElement($start, $FileName)).')(.*)('.preg_quote($end).')#si',$IncludePage,html_entity_decode(file_get_contents($FileName)))); 
		
	} 
	
	//return FindStartElement($start, '../../FileManager/files/index.php').'@@'.$start.StringBetween(file_get_contents('../../FileManager/files/index.php'), $start, $end).$end;
}
function SaveHTMLCode($HTML, $PageName, $DynamicPageName){ //Used to create a dynamic navbar in all php pages
	$CheckElement = mysql_query("SELECT ElementName from Elements WHERE ElementName = '$Name'");
	if (mysql_num_rows($CheckElement) > 0) {
	mysql_query("UPDATE Elements SET Node=CONCAT(Node,'$Node,') WHERE ElementName='$Name'");
	mysql_query("UPDATE Elements SET Class=CONCAT(Class,'$Class,') WHERE ElementName='$Name'");
	mysql_query("UPDATE Elements SET DivID=CONCAT(DivID,$ID,') WHERE ElementName='$Name'");
	}else{
	mysql_query("INSERT INTO Elements (ElementName,Node,Class,DivID) VALUES ('$Name', '$Node,','$Class,','$ID,')");	
	}
	
	$IncludePage = "<!--Start-".$Name."--><?php INCLUDE'Pages/".$Name.".php'; ?><!--End-".$Name."-->";
	
	 

	foreach(RetrieveFilesLimit('../../FileManager/files', '.php') as $FileName){
		
		$CheckSize = strlen($HTML); 
		$Checker = true;
		$FileSingle = file_get_contents($FileName);
		
		while($Checker){
	$StringChecks = CheckStringSizeCalc($HTML, $CheckSize, $Name);
	$start = $StringChecks[0];
	$end = $StringChecks[1];
	$DynamicStart = $StringChecks[2];
	$DynamicLength = $StringChecks[3];
	$CheckSize = ($CheckSize-$DynamicLength);
				/*if(strpos(trim(preg_replace('/\s\s+/', ' ', $FileSingle)), trim(preg_replace('/\s\s+/', ' ', $start))) !== false){
				EditConsole('Found Start'.trim(preg_replace('/\s\s+/', ' ', $start)).trim(preg_replace('/\s\s+/', ' ', $end)).'@@@'.$FileName,'');
				}
				if(strpos(trim(preg_replace('/\s\s+/', ' ', $FileSingle)), trim(preg_replace('/\s\s+/', ' ', $end))) !== false){
				EditConsole('Found End'.trim(preg_replace('/\s\s+/', ' ', $end)).$FileName,'');
				}*/

			if(strpos(trim(preg_replace('/\s\s+/', ' ', $FileSingle)), trim(preg_replace('/\s\s+/', ' ',trim(preg_replace('/\s\s+/', ' ', $start)).StringBetween(trim(preg_replace('/\s\s+/', ' ', $FileSingle)),trim(preg_replace('/\s\s+/', ' ', $start)), trim(preg_replace('/\s\s+/', ' ', $end))).trim(preg_replace('/\s\s+/', ' ', $end))))) !== false){	
		//if(strpos($FileSingle, $start.StringBetween($FileSingle, $start, $end).$end) !== false){
			file_put_contents($FileName,str_replace(trim(preg_replace('/\s\s+/', ' ',trim(preg_replace('/\s\s+/', ' ', $start)).StringBetween(trim(preg_replace('/\s\s+/', ' ', $FileSingle)),trim(preg_replace('/\s\s+/', ' ', $start)), trim(preg_replace('/\s\s+/', ' ', $end))).trim(preg_replace('/\s\s+/', ' ', $end)))),$IncludePage,trim(preg_replace('/\s\s+/', ' ', $FileSingle))));
	
	EditConsole('match:'.$start.$end.'File:'.$FileName,''); 
			 
			break;	
		}else{
			if($CheckSize>20){
				
			$CheckSize = $CheckSize -1;
			//$StringChecks = CheckStringSizeCalc($HTML, $CheckSize, $Name);
			//$start = $StringChecks[0];
			//$end = $StringChecks[1];
			//EditConsole($start.$end,'');
			//$DynamicStart = $StringChecks[2];
			//EditConsole($CheckSize,'');
			}else{
				
				//EditConsole('Unable to make the element dynamic'.$start.$end,'');
			break;	
			}
			
			
			
		}
		
		}
			//file_put_contents('../../FileManager/files/Pages/'.$Name.'.php',$HTML);

			//file_put_contents($FileName,str_replace($start.StringBetween(file_get_contents($FileName), $start, $end).$end,$IncludePage,file_get_contents($FileName)));
			
		//file_put_contents($FileName, preg_replace('#('.preg_quote(FindStartElement($start, $FileName)).')(.*)('.preg_quote($end).')#si',$IncludePage,html_entity_decode(file_get_contents($FileName)))); 
		
	} 
	file_put_contents('../../FileManager/files/Pages/'.$Name.'.php',$HTML);

	//return FindStartElement($start, '../../FileManager/files/index.php').'@@'.$start.StringBetween(file_get_contents('../../FileManager/files/index.php'), $start, $end).$end;
}

function CheckStringSizeCalc($HTML, $Size, $Name){
	if (strpos($HTML, ' Dynamic Dynamic-') !== false) {
		$Remove = ' Dynamic Dynamic-'.$Name;
    $start = substr(str_replace($Remove,'',$HTML), 0, $Size);
	$DynamicStart = substr($HTML,0,($Size+strlen($Remove)));
	$end = substr(str_replace(' Dynamic Dynamic-'.$Name,'',$HTML), -$Size);
	}else{
		$Remove = ' class="Dynamic Dynamic-'.$Name.'"';
	$start = substr(str_replace($Remove,'',$HTML), 0, $Size);
	$DynamicStart = substr($HTML,0,($Size+strlen($Remove)));
	$end = substr(str_replace(' class="Dynamic Dynamic-'.$Name.'"','',$HTML), -$Size);	
	}
	$DynamicLength = strlen($Remove);
	return array($start, $end, $DynamicStart, $DynamicLength);
}

function EditLink($HTML, $Before, $PageName){
	$Changer = random_string(6);
	if($PageName == 'ALL'){
	foreach(RetrieveFiles('../../FileManager/files', '.php') as $FileName){
	$FileContents = file_get_contents($FileName);
	CreateBackup($FileName, $Changer);
	file_put_contents($FileName,str_replace($Before, $HTML,$FileContents));
			
	} 	
	foreach(RetrieveFiles('../../FileManager/files/Pages', '.php') as $FileName){
			$FileContents = file_get_contents($FileName);
			CreateBackup($FileName, $Changer);
			file_put_contents($FileName,str_replace($Before, $HTML,$FileContents));
			
	} 	
	EditConsole($HTML.' Link updated on all pages','');
	}else{
	CreateBackup('../../FileManager/files/'.$PageName, $Changer);
	file_put_contents('../../FileManager/files/'.$PageName,str_replace($Before, $HTML,file_get_contents('../../FileManager/files/'.$PageName)));
	EditConsole(' Link updated on '.$PageName,'');

	
	}
}
function RemoveElement($HTML, $PageName){
	$start = substr($HTML, 0, 60);
	$end = substr($HTML, -60);

	file_put_contents('../../FileManager/files/'.$PageName,str_replace($start.StringBetween(file_get_contents('../../FileManager/files/'.$PageName), $start, $end).$end,'',file_get_contents('../../FileManager/files/'.$PageName)));

	EditConsole('Element removed from: '.$PageName,'');
	
}

function ReplaceBetween($str, $needle_start, $needle_end, $replacement) {//used to replace everything in between needles in string with replacement
    $pos = strpos($str, $needle_start);
    $start = $pos === false ? 0 : $pos + strlen($needle_start);

    $pos = strpos($str, $needle_end, $start);
    $end = $start === false ? strlen($str) : $pos;
 
    return substr_replace($str,$replacement,  $start, $end - $start);
}



function Recurse_Copy($src,$dst) { 
    $dir = opendir($src); 
    @mkdir($dst); 
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                Recurse_Copy($src . '/' . $file,$dst . '/' . $file); 
            } 
            else { 
                copy($src . '/' . $file,$dst . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
} 
function GetTables(){
  $tableList = array();
  $res = mysqli_query($this->conn,"SHOW TABLES");
  while($cRow = mysqli_fetch_array($res))
  {
    $tableList[] = $cRow[0];
  }
  return $tableList;
}
function CreateDirectories($DBArray){
	if (!file_exists('../../FileManager/files/Pages')) {
    mkdir('../../FileManager/files/Pages', 0755, true);
	}
	if (!file_exists('../../FileManager/files/Undo')) {
    mkdir('../../FileManager/files/Undo', 0755, true);
	}
	if (!file_exists('../../FileManager/files/uploads')) {
    mkdir('../../FileManager/files/uploads', 0755, true);
	}
    Recurse_Copy('../CodeEditor/','../../FileManager/files/');
	
	if (!file_exists('../../FileManager/files/PHP')) {
    mkdir('../../FileManager/files/PHP', 0755, true);
	$start[] = '$db_host';
	$start[] = '$db_username';
	$start[] = '$db_password';
	$start[] = '$db_name';
	$end = ';';
	$File = file_get_contents('../../PHP/databaseconnect.php');
	foreach($start as $key => $item){
		if($key == 0){
	$NewFile = ReplaceBetween($File, $item, $end, ' ="'.$DBArray[$key].'"');
		}else{
	$NewFile = ReplaceBetween($NewFile, $item, $end, ' ="'.$DBArray[$key].'"');		
		}
	}
	file_put_contents('../../FileManager/files/PHP/databaseconnect.php',$NewFile);
	}
	if (!file_exists('../../FileManager/files/Functions')) {
    mkdir('../../FileManager/files/Functions', 0755, true);
	copy('../../Functions/MainFunctions.php','../../FileManager/files/Functions/MainFunctions.php');
	}	
	if (!file_exists('../../FileManager/files/scripts')) {
    mkdir('../../FileManager/files/scripts', 0755, true);
	}	
}
function AssembleWebsite($Element, $HTML, $ID, $Class, $Node, $Name){ //Used to decide what to do with each element	
if($Element == '2'){//Element is Navigation Bar
	return NavigationBar($HTML, $ID, $Class, $Node);
}else{
	return CreateDynamicElement($HTML, $ID, $Class, $Node, $Name);
}
}
function Encryptor($Password){
	$Passwords = password_encrypt($Password); //First line of encryption on password.
	$EncryptedPassword = crypt($Password, $Passwords);//Double encryption on password.
	return $EncryptedPassword;
}
function RunMySqli($dbConnection, $query){//Used to process a mysqli query
$result = mysqli_query($dbConnection, $query);	
return $result;
}
function CreateAccountsTable($dbConnection, $Email, $RegPassword){//Used to create the accounts table with one account

$query = "SELECT AccountID FROM Accounts";
$result = RunMySqli($dbConnection, $query);

				if(empty($result)) {
                $query = "CREATE TABLE IF NOT EXISTS Accounts (
                           AccountID int(11) AUTO_INCREMENT NOT NULL,
  Email varchar(300) NOT NULL,
  Password varchar(60) NOT NULL,
  FirstName varchar(50) NOT NULL,
  LastName varchar(50) NOT NULL,
  County varchar(50) NOT NULL,
  Country varchar(50) NOT NULL,
  PostCode varchar(15) NOT NULL,
  ContactNumber int(15) NOT NULL DEFAULT '0',
  AddressOne varchar(100) NOT NULL,
  AddressTwo varchar(100) NOT NULL DEFAULT 'EMPTY',
  IP varchar(100) NOT NULL,
  Active varchar(100) NOT NULL,
  Reset varchar(100) NOT NULL DEFAULT 'EMPTY',
  RegisterDate date NOT NULL,
  Cart varchar(500) NOT NULL DEFAULT 'EMPTY',
  Profile varchar(255) NOT NULL,
  AdminLevel int(1) NOT NULL DEFAULT '0',
  Status varchar(255) NOT NULL,
  ShowFullName int(11) NOT NULL DEFAULT '1',
  ShowProfileImage int(11) NOT NULL DEFAULT '1',
  ShowAvailability int(11) NOT NULL DEFAULT '1', PRIMARY KEY  (AccountID)
)";
				RunMySqli($dbConnection, $query);
				if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
					    	$ip2 = $_SERVER['HTTP_CLIENT_IP'];
						} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
					   	 	$ip2 = $_SERVER['HTTP_X_FORWARDED_FOR'];
						} else {
					   	 	$ip2 = $_SERVER['REMOTE_ADDR'];
						}
						$Date = date('y-m-d');
				$Emails = explode(',',$Email);
				$Passwords = explode(',',$RegPassword);
				foreach($Emails as $Key => $EmailSingle){
					InsertIntoTable($dbConnection,'Accounts',array('Email', 'Password', 'FirstName', 'IP', 'Active', 'Reset', 'RegisterDate','Profile', 'AdminLevel'),array($EmailSingle,$Passwords[$Key], 'Admin',$ip2,'1','EMPTY',$Date,'avatar12.png','1'));

				}
				
				}else{
				$Emails = explode(',',$Email);
				$Passwords = explode(',',$RegPassword);
				foreach($Emails as $Key => $EmailSingle){
					$query = mysqli_query($dbConnection, "SELECT Email FROM Accounts WHERE Email = '".$EmailSingle."'");
					if((mysqli_num_rows($query) > 0)){
					
					}else{
						InsertIntoTable($dbConnection,'Accounts',array('Email', 'Password', 'FirstName', 'IP', 'Active', 'Reset', 'RegisterDate','Profile', 'AdminLevel'),array($EmailSingle,$Passwords[$Key], 'Admin','62.172.166.93','1','EMPTY','2015-01-01','avatar12.png','1'));
					}
				}

				}
}
function CreateLiveChatTable($dbConnection){
  $query = "CREATE TABLE IF NOT EXISTS LiveChat (
                          ID int(11) AUTO_INCREMENT,
                          Message varchar(2500) NOT NULL,
                          Date timestamp NOT NULL,
						  ReceivedID int(11),
						  SentID int(11),
						  MarkRead varchar(20),
                          PRIMARY KEY  (ID)
                          )";
				RunMySqli($dbConnection, $query);	
}
function CreateNotesTable($dbConnection){
  $query = "CREATE TABLE IF NOT EXISTS Notes (
                          ID int(11) AUTO_INCREMENT,
                          Note varchar(2500) NOT NULL,
                          Title varchar(2300) NOT NULL,
						  Date timestamp,
                          PRIMARY KEY  (ID)
                          )";
				RunMySqli($dbConnection, $query);	
				  $query = "CREATE TABLE IF NOT EXISTS `Notifications` (
  `ID` int(11) AUTO_INCREMENT NOT NULL,
  `Message` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `Icon` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `MarkRead` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
  	PRIMARY KEY  (ID)
) ";
				RunMySqli($dbConnection, $query);
}
function CreateCommerceTables($dbConnection){
  $query = "CREATE TABLE IF NOT EXISTS Products  (
   ProductID  int(12) AUTO_INCREMENT NOT NULL,
   ProductName  varchar(30) NOT NULL,
   ProductPrice  varchar(8) NOT NULL,
   ProductWeight  varchar(8) NOT NULL,
   ProductShortDesc  varchar(255) NOT NULL,
   ProductLongDesc  varchar(2000) NOT NULL,
   ProductThumb  varchar(100) NOT NULL,
   CategoryID  int(11) NOT NULL,
   ProductDate  varchar(10) NOT NULL,
   ProductUpdateDate  date NOT NULL,
   ProductStock  int(3) NOT NULL,
   ProductLive  int(1) NOT NULL,
   PurchasePrice  varchar(10) NOT NULL,
   SupplierID  int(11) NOT NULL,
   SKU  varchar(30) NOT NULL,
   Tags  varchar(600) NOT NULL,
                          PRIMARY KEY  (ProductID)
                          )";
RunMySqli($dbConnection, $query);
$query ="CREATE TABLE IF NOT EXISTS ProductReviews  (
   ReviewID  int(11) AUTO_INCREMENT NOT NULL,
   ProductID  int(11) NOT NULL,
   ReviewText  varchar(500) NOT NULL,
   ReviewEmail  varchar(60) NOT NULL,
   ReviewName  varchar(60) NOT NULL,
   Date    date NOT NULL,
   						 PRIMARY KEY  (ReviewID)
)";
RunMySqli($dbConnection, $query);	
$query ="CREATE TABLE IF NOT EXISTS    Orders    (
     OrderID    int(11) AUTO_INCREMENT NOT NULL,
     AccountID    int(11) NOT NULL,
     OrderQty    int(11) NOT NULL,
     ShipName    varchar(30) NOT NULL,
     ShipAddressOne    varchar(70) NOT NULL,
     ShipAddressTwo    varchar(70) NOT NULL,
     City    varchar(255) NOT NULL,
     ShipCounty    varchar(40) NOT NULL,
     ShipCountry    varchar(40) NOT NULL,
     ShipPostCode    varchar(15) NOT NULL,
     OrderDate    date NOT NULL,
     OrderStatus    varchar(30) NOT NULL,
     ShippingOption    varchar(15) NOT NULL,
     PayPalFee    varchar(255) NOT NULL,
     ActiveOrder    int(1) NOT NULL DEFAULT '1',
     											PRIMARY KEY  (OrderID)
)";
RunMySqli($dbConnection, $query);
$query ="CREATE TABLE IF NOT EXISTS    OrderDetails    (
     OrderDetailID    int(11) AUTO_INCREMENT NOT NULL,
     OrderID    int(11) NOT NULL,
     OrderProductID    int(11) NOT NULL,
     Price    varchar(15) NOT NULL,
     Quantity    int(5) NOT NULL,
     Opt    varchar(255) NOT NULL,
          						  PRIMARY KEY  (OrderDetailID)

)";
RunMySqli($dbConnection, $query);
$query ="CREATE TABLE IF NOT EXISTS    Options    (
     OptionID    int(11) AUTO_INCREMENT NOT NULL,
     OptionGroupID    int(11) NOT NULL,
     OptionName    varchar(1500) NOT NULL,
     									PRIMARY KEY  (OptionID)
)";
RunMySqli($dbConnection, $query);
$query ="CREATE TABLE IF NOT EXISTS    OptionGroups    (
     OptionGroupID    int(11) AUTO_INCREMENT NOT NULL,
     OptionGroupName    varchar(60) NOT NULL,
     										PRIMARY KEY  (OptionGroupID)
)";
RunMySqli($dbConnection, $query);
$query ="CREATE TABLE IF NOT EXISTS    Images    (
     ImageID    int(11) AUTO_INCREMENT NOT NULL,
     FileLocation    varchar(70) NOT NULL,
     Tags    varchar(255) NOT NULL,
     								PRIMARY KEY  (ImageID)
)";
RunMySqli($dbConnection, $query);
$query ="CREATE TABLE IF NOT EXISTS    ImageProducts    (
     ImageProductID    int(11) AUTO_INCREMENT NOT NULL,
     ProductID    int(11) NOT NULL,
     ImageID    int(11) NOT NULL,
     Def    varchar(5) NOT NULL,
     							PRIMARY KEY  (ImageProductID)
)";
RunMySqli($dbConnection, $query);
$query ="CREATE TABLE IF NOT EXISTS    Suppliers    (
     SupplierID    int(11) AUTO_INCREMENT NOT NULL,
     SupplierName    varchar(50) NOT NULL,
     SupplierContact    varchar(60) NOT NULL,
     SupplierLogo    varchar(50) NOT NULL,
     										PRIMARY KEY  (SupplierID)
)";
RunMySqli($dbConnection, $query);
$query ="CREATE TABLE IF NOT EXISTS    rating    (
     id    int(11) AUTO_INCREMENT NOT NULL,
     p_id    int(10) NOT NULL,
     rate    varchar(10) NOT NULL,
     								PRIMARY KEY  (id)
)";
RunMySqli($dbConnection, $query);
$query ="CREATE TABLE IF NOT EXISTS    Categories    (
     CategoryID    int(11) AUTO_INCREMENT NOT NULL,
     CategoryName    varchar(35) NOT NULL,
     CategoryLevel    int(11) NOT NULL,
     Root    int(5) NOT NULL,
     						PRIMARY KEY  (CategoryID)
)";
RunMySqli($dbConnection, $query);
$query ="CREATE TABLE IF NOT EXISTS    Coupons    (
     CouponID    int(11) AUTO_INCREMENT NOT NULL,
     CouponDiscountAmount    varchar(255) NOT NULL,
     CouponCode    varchar(255) NOT NULL,
     Expiry    varchar(60) NOT NULL,
     Uses    varchar(11) NOT NULL,
     StartDate    varchar(60) NOT NULL,
     									PRIMARY KEY  (CouponID)
)";
RunMySqli($dbConnection, $query);
return 'd';
}
function CreateTableManager($dbConnection){
$query ="CREATE TABLE IF NOT EXISTS    TableManager    (
     ID    int(11) AUTO_INCREMENT NOT NULL,
     TableName    varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     Fields    varchar(1500) COLLATE utf8_unicode_ci NOT NULL,
     VisibleFields    varchar(1500) COLLATE utf8_unicode_ci NOT NULL,
     VisibleFieldsValues    varchar(2500) COLLATE utf8_unicode_ci NOT NULL,
     FieldNames    varchar(2500) COLLATE utf8_unicode_ci NOT NULL,
     LinkedTables    varchar(2500) COLLATE utf8_unicode_ci NOT NULL,
     ActiveTable    varchar(10) COLLATE utf8_unicode_ci NOT NULL,
     SaveTables    varchar(1500) COLLATE utf8_unicode_ci NOT NULL,
     SaveRules    varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     DelRow    varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     														PRIMARY KEY  (ID)
)";
RunMySqli($dbConnection, $query);	
}
function CreateIPTable($dbConnection){//used to create the more unique IP table
$query = "SELECT code FROM ip2nationCountries";
$result = RunMySqli($dbConnection, $query);

				if(empty($result)) {
                 $query = "CREATE TABLE ip2nationCountries (
                          code varchar(4),
                          iso_code_2 varchar(2) NOT NULL DEFAULT '',
                          iso_code_3 varchar(3) DEFAULT '',
                          iso_country varchar(255) NOT NULL DEFAULT '',
						  country varchar(255) NOT NULL DEFAULT '',
						  lat float NOT NULL DEFAULT '0',
						  lon float NOT NULL DEFAULT '0',
                          PRIMARY KEY  (code)
                          )";
				RunMySqli($dbConnection, $query);
				InsertPHPArrayMySql($dbConnection, 'ip2nationCountries', 'ip2nationCountries.php', array('code', 'iso_code_2', 'iso_code_3', 'iso_country', 'country', 'lat', 'lon'));
				}
}
function InsertPHPArrayMySql($dbConnection, $TableName, $FileName, $Fields){//Used to take a PHP file with an array and insert the data into a table
	$Field = implode(',',$Fields);
	INCLUDE$FileName;
			foreach($Array as $Item){
			$InsString[] = implode("','",$Item);	
			
			}
			$InsertString = implode("'),('",$InsString);
$query ="INSERT INTO $TableName ($Field) VALUES ('$InsertString')";
	RunMySqli($dbConnection, $query);
}
function InsertIntoTable($dbConnection,$TableName, $Fields, $Values){ //function to insert into table easily

	$Field = implode(',',$Fields);
	$Value = implode("','",$Values);
	$query = "INSERT INTO $TableName ($Field) VALUES ('$Value')";
	RunMySqli($dbConnection, $query);

}
function CreateAdmin($dbConnection, $Email){//function to create top admin table and insert default
	$query = "SELECT ID FROM TopAdmins";
$result = RunMySqli($dbConnection, $query);

				if(empty($result)) {
                $query = "CREATE TABLE TopAdmins (
                          ID int(11) AUTO_INCREMENT,
                          AccountsID int(11) NOT NULL,
                          Email varchar(300) NOT NULL,
                          PRIMARY KEY  (ID)
                          )";
				RunMySqli($dbConnection, $query);
				InsertIntoTable($dbConnection,'TopAdmins',array('AccountsID','Email'),array('1',$Email));
				}
}
function CreateIPNation($dbConnection){//function to create IP table
	$query = "SELECT ip FROM ip2nation";
$result = RunMySqli($dbConnection, $query);

				if(empty($result)) {
                $query = "CREATE TABLE ip2nation (
                          ip int(11) unsigned NOT NULL DEFAULT '0',
                          country char(2) NOT NULL DEFAULT '')";
				RunMySqli($dbConnection, $query);
				//InsertPHPArrayMySql($dbConnection, 'ip2nation', 'ip2nation.php', array('ip', 'country')); Can't run query, assuming to large - need to find work around
				}
}
function CreateSimpleTables($dbConnection, $TableName,$Primary, $Fields, $FieldType, $FieldSize, $Email, $WebsiteName){//function to create simple tables
	 
	$query = "SELECT $Primary FROM $TableName";
$result = RunMySqli($dbConnection, $query);

				if(empty($result)) {
                $query = "CREATE TABLE $TableName (
                          ".$Primary." int(11) AUTO_INCREMENT,";
						  
						  
						  foreach($Fields as $Key => $Field){
							$query .= $Field." ".$FieldType[$Key]."(".$FieldSize[$Key].") NOT NULL,";
						  }
						  $query .= "PRIMARY KEY  (".$Primary."))";
                         
				RunMySqli($dbConnection, $query);
				if($TableName == 'TotalViews'){
			InsertIntoTable($dbConnection,'TotalViews',array('Views'),array('1'));	
			}elseif($TableName == 'MiscInfo'){
			InsertIntoTable($dbConnection,'MiscInfo',array('ContactEmail','StoreName'),array($Email,$WebsiteName));		
			}
				}
			
				
}
function CreateBaseTables($DatabaseName, $db_password, $db_username, $db_host, $Email, $RegPassword, $WebsiteName){ //assembled main database structure and populates as much as possible
	$dbConnection = new mysqli($db_host, $db_username, $db_password, $DatabaseName);
	CreateAccountsTable($dbConnection, $Email, $RegPassword);
	CreateNotesTable($dbConnection);
	CreateLiveChatTable($dbConnection);
	CreateAdmin($dbConnection, $Email); 
	CreateIPTable($dbConnection);
	CreateIPNation($dbConnection);
	//CreateCommerceTables($dbConnection);
	CreateTableManager($dbConnection);
	$Emails = explode(',',$Email);
	CreateSimpleTables($dbConnection, 'AdminPanel','ID', array('Name','Permission','FileName','ClassName','TableName','LinkVar'), array('varchar','varchar','varchar','varchar','varchar','varchar'), array('255','12','255','255','255','255'));
	CreateSimpleTables($dbConnection, 'TotalViewsDated','ID', array('Date'), array('varchar'), array('15'));
	CreateSimpleTables($dbConnection, 'TotalViews','ID', array('Views'), array('int'), array('11'));
	CreateSimpleTables($dbConnection, 'Newsletters','ID', array('Header','MainText','Date'), array('varchar','varchar','varchar'), array('30','2500','255'));
	CreateSimpleTables($dbConnection, 'NewsletterStats','ID', array('Emails','NewsletterID'), array('varchar','int'), array('10000','11'));
	CreateSimpleTables($dbConnection, 'Emails','ID', array('Email','Rand'), array('varchar','varchar'), array('255','11'));
	CreateSimpleTables($dbConnection, 'UniqueViews','ID', array('IP', 'Date'), array('varchar', 'varchar'), array('255','20'));
	CreateSimpleTables($dbConnection, 'MiscInfo','ID', array('ContactEmail', 'ContactNumber', 'StoreName','Address','NewsletterEmail'), array('varchar','varchar','varchar','varchar','varchar'), array('300','35','255','500','255'),$Emails[0],$WebsiteName);
	
}
function AddEditor(){//Adds Editor to all pages
	$Files = RetrieveFiles('../../FileManager/files', '.php');
	$Include = "<?php INCLUDE'../../Pages/PageEditor/Assembler.php'; ?> </body>";

	foreach($Files as $File){
		if(strpos(file_get_contents($File),$Include)){
			//EditConsole('Editor  '.$File,'../PageEditor/');
		}elseif(SearchForHTML('Assembler.php', $File) !== false){
			//EditConsole('Not Contained '.$File,'../PageEditor/');
		}else{
			
			file_put_contents($File,str_replace("</body>",$Include,file_get_contents($File)));	
		}
	
	}
}
function RemoveEditor(){//Removed Editor from all pages
	$Files = RetrieveFiles('../../FileManager/files', '.php');
	foreach($Files as $File){
	file_put_contents($File,str_replace("<?php INCLUDE'../../Pages/PageEditor/Assembler.php'; ?>",file_get_contents($File)));
	}
}
function StatisticRecorder(){ //Updates views
		mysql_query("UPDATE TotalViews SET `Views` = `Views`+1 WHERE id='1'");
	
 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}
$checkip = mysql_query("SELECT * FROM UniqueViews");
	$x = 1;
 while ($info = mysql_fetch_array( $checkip)){
	$recentip[$x] =  $info['ip'];
	 $x = $x + 1;
	 }
	 $maxip = "SELECT MAX(ID) as num FROM UniqueViews";
	 $highestip = mysql_query($maxip) or die (died);
	 while($iprow = mysql_fetch_assoc($highestip)){
		 $maxip = $iprow['num'];
	 }

$datetime =date("d/m/Y");
	mysql_query("INSERT INTO TotalViewsDated (Date) VAlUES ('$datetime')");
if(!mysql_num_rows(mysql_query("SELECT IP FROM UniqueViews WHERE IP = '$ip'"))){
 mysql_query("INSERT INTO UniqueViews (IP, Date) VAlUES ('$ip', '$datetime')");
}	
}
function EditConsole($Message, $Path){
file_put_contents($Path.'Console.txt',file_get_contents($Path.'Console.txt').date('d-m-Y H:i:s').': '.$Message."\n");
}
function AddBasicPHP($BooleanCheck){//Adds base website PHP- boolean checks if the document already contains the basic php
if(!$BooleanCheck){
	$Files = RetrieveFilesLimit('../../FileManager/files', '.php'); 
	$start = "<title><?php session_start(); INCLUDE'PHP/databaseconnect.php';INCLUDE'Functions/MainFunctions.php';StatisticRecorder(); ?><?php echo FetchWebsiteName($connecDB); ?></title>";
	$Include = "<?php session_start(); INCLUDE'PHP/databaseconnect.php';INCLUDE'Functions/MainFunctions.php';StatisticRecorder(); ?><?php echo FetchWebsiteName(\$connecDB); ?>";
	foreach($Files as $File){
		if(strpos(file_get_contents($File),$Include) !== false){
			
		}else{
			
	file_put_contents($File,ReplaceBetween(file_get_contents($File), $start, $end,$Include ));
		}
	}
}
}
function CreateBackup($Pages, $Changer){
	
	$_SESSION['Backups'][] = $Changer;
	$PageName = explode('/', $Pages);
	$Page = explode('.',end($PageName));
	file_put_contents('../../FileManager/files/Undo/'.$Page[0].'BACKUP'.$Changer.'.'.$Page[1],file_get_contents($Pages));
	/*if(in_array($Pages)){
		foreach($Pages as $PageName){
	
		$Page = explode('.',$PageName);
		
		if(!file_exists('../../FileManager/files/Undo/'.$Page[0].'BACKUP'.$Changer.'.'.$Page[1])){
		file_put_contents('../../FileManager/files/Undo/'.$Page[0].'BACKUP'.$Changer.'.'.$Page[1],file_get_contents('../../FileManager/files/'.$PageName));	
		}else{
		EditConsole('Error creating backup page: '.$PageName,'');
		}
	
		}
	}else{
		$PageName = $Pages;
	if (!file_exists('../../FileManager/files/Undo/'.$PageName)) {
	file_put_contents('../../FileManager/files/Undo/'.$PageName,file_get_contents('../../FileManager/files/'.$PageName));
	}else{
		$Page = explode('.',$PageName);
		
		if(!file_exists('../../FileManager/files/Undo/'.$Page[0].'BACKUP'.$Changer.'.'.$Page[1])){
		file_put_contents('../../FileManager/files/Undo/'.$Page[0].'BACKUP'.$Changer.'.'.$Page[1],file_get_contents('../../FileManager/files/'.$PageName));	
		}else{
		EditConsole('Error creating backup page: '.$PageName,'');
		}
	}	
	} */
}
function SaveCode($HTML, $PageName){
	 $Changer = random_string(6);
	CreateBackup('../../FileManager/files/'.$PageName, $Changer);
	file_put_contents('../../FileManager/files/'.$PageName, $HTML);
	EditConsole('Code saved on page: '.$PageName,'');
}

function Undo(){
	if(AutoCheck($_SESSION['Backups'])){
	$Check = 0;
	$UndoFiles = scandir('../../FileManager/files/Undo/');
	while($Check == 0){
	$RecentChange = array_pop($_SESSION['Backups']);
		foreach($UndoFiles as $Files){
			if(strpos($Files, $RecentChange) !== false){
				$Undo[] = $Files;#
				
				$Check++;
			}
		}
	}
	foreach($Undo as $FileName){
		
			$SplitName = explode('BACKUP', $FileName);
		
			if(file_exists('../../FileManager/files/'.$SplitName[0].'.php')){
				file_put_contents('../../FileManager/files/'.$SplitName[0].'.php',file_get_contents('../../FileManager/files/Undo/'.$FileName));
				unlink('../../FileManager/files/Undo/'.$SplitName[0].'.php');
				EditConsole('Undone, changed made to: '.$SplitName[0].'.php','');
			}elseif(file_exists('../../FileManager/files/Pages/'.$SplitName[0].'.php')){
				file_put_contents('../../FileManager/files/Pages/'.$SplitName[0].'.php',file_get_contents('../../FileManager/files/Undo/'.$FileName));
				unlink('../../FileManager/files/Undo/'.$FileName);
				EditConsole('Undone, changed made to: '.$SplitName[0].'.php','');
			}else{
				EditConsole('Error, undo failed.','');
			}
	
		
	}
	
	}else{
	EditConsole("Can't undo any further.",'');	
	}
	
}
/*function CategoryCode($Level, $ID){
	if($Level == 0){
$FirstLevel = '<div class="accordion-group">
            <div class="accordion-heading">
                <a class="accordion-toggle collapsed" data-toggle="collapse" href="#collapse'.$ID.'">';
	}
	return $FirstLevel;
}
function CheckChildren($ID, $CategoryLevels, $CategoryNames, $Child){
	
	if($Child == true){
		$Child = false;
	foreach($CategoryLevels as $Key => $Level){
		if($Level == $ID){
		$KeyVals[] = $Key;	
		$Child = true;
		}
	}
	if($Child == true){	

		return RetrieveAllCategories(($Key-1), $CategoryLevels, $CategoryNames, $Child);		
	
	}else{
	return 	$Child;	
	}
	}else{
		
	return 	$Child;
	}	
}

function RetrieveAllCategories($ID, $CategoryLevels, $CategoryNames, $Child, $ParentsID, $CategoryList, $CategoryID, $CategoryProducts){
	
	if($Child == true){
		$Child = false;
	foreach($CategoryLevels as $Key => $Level){
		if($Level == $ID){
		$KeyVals[] = $Key;	
		$Child = true;
		}
	}
	if($Child == true){
		$FirstLevel = ' <div class="accordion-heading">
                                <a href="#collapseSub'.$ParentsID.'" data-toggle="collapse" class="collapsed" >'.$CategoryNames[$ID-1].'</a>
                            </div>
                            <div id="collapseSub1" class="accordion-body collapse in">
                                <ul>';
                                   
                               
							
	$FirstClose = '</ul> </div>';						
		foreach($KeyVals as $item){
			if(CheckChildren($CategoryID[$item], $CategoryLevels, $CategoryNames, true) == true){
				$CategoryList .= '<div class="accordion-heading">
                                <a href="#collapseSub'.$CategoryID[$item].'" data-toggle="collapse" class="collapsed">'.$CategoryNames[$item].'</a></div>'.RetrieveAllCategories($CategoryID[$item], $CategoryLevels, $CategoryNames, true, $CategoryID[$item],"", $CategoryID).'</li>';	
			}else{
				if(in_array($CategoryID[$item], $CategoryProducts)){
		$CategoryList .=  '<li><a href="category-grid-2.php?category='.$CategoryNames[$item].'">'.$CategoryNames[$item]."</a></li>";		
				}
			}
		}
		return RetrieveAllCategories($Key, $CategoryLevels, $CategoryNames, $Child, $ParentsID, $CategoryList);		
	}else{
		$CategoryList = '<div id="collapseSub'.$ParentsID.'" class="accordion-body collapse">
                                <ul>'.$CategoryList.'</ul></div>';
	return 	$CategoryList;	
	}
	}else{
		$CategoryList = '<div id="collapseSub'.$ParentsID.'" class="accordion-body collapse">
                                <ul>'.$CategoryList.'</ul></div>';
	return 	$CategoryList;
	}	
}
function TreeSearch($ID, $CategoryLevels, $CategoryNames, $CategoryID, $CategoryProducts){

	
	
	foreach($CategoryLevels as $Key => $Level){
		if($Level == $ID){
		$KeyVals[] = $Key;	
		}
	}
	
	foreach($KeyVals as $Key){
		
		if(CheckChildren($CategoryID[$Key], $CategoryLevels, $CategoryNames, true) == true){
		$InnerString .= '~~~~~~~~<div class="accordion-heading">
                                <a href="#collapseSub'.$CategoryID[$Key].'" data-toggle="collapse" class="collapsed">'.$CategoryNames[$Key].'</a></div>'.RetrieveAllCategories($CategoryID[$Key], $CategoryLevels, $CategoryNames, true, $CategoryID[$Key],"", $CategoryID, $CategoryProducts).'~~~~~~~~~~~';	
		$CategoryJSONs[0]['text'] = $CategoryNames[$Key];
		$CategoryJSONs[0]['icon'] = 'fa fa-tags';
		$CategoryJSON[] = $CategoryJSONs[0];
		}else{
			if(in_array($CategoryID[$Key], $CategoryProducts)){
		$InnerString .= '@@@@@@@@@<li><a href="category-grid-2.php?category='.$CategoryNames[$Key].'">'.$CategoryNames[$Key].'</a></li>@@@@@@@@@@@';
			$CategoryJSONs[0]['text'] = $CategoryNames[$Key];
			$CategoryJSONs[0]['icon'] = 'fa fa-tags';
			$CategoryJSON[] = $CategoryJSONs[0];
			}
		}
	} 
	
	$InnerString = $InnerString;
	
	return $CategoryJSON;
}

function DisplayCategoryTree($CategoryNames, $CategoryLevels, $CategoryID, $CategoryProducts){
	$CloseCategory = 0;
	$CloseCategoryOld = 1;
				foreach($CategoryLevels as $Key => $CatLevel){
					
					if($CatLevel == 0){
						if(CheckChildren($CategoryID[$Key], $CategoryLevels, $CategoryNames, true) == true){
						$CloseCategory++;
						
					$CategoryTree .= CategoryCode($CatLevel, $CategoryID[$Key]).$CategoryNames[$Key].$CategoryID[$Key];
					$CategoryJSON['text'] = $CategoryNames[$Key];
					$CategoryJSON['icon'] = 'fa fa-tags';
					$CategoryJSON['state']['selected'] = 'false';
					$CategoryJSON['children'][] = TreeSearch($CategoryID[$Key], $CategoryLevels, $CategoryNames, $CategoryID, $CategoryProducts);
					$JSON .= json_encode($CategoryJSON).',';
					//$CategoryJSON[$CategoryID[$Key]] = TreeSearch($CategoryID[$Key], $CategoryLevels, $CategoryNames, $CategoryID, $CategoryProducts);
					}
					}
					
					
					
					
					if($CatLevel == 0){
						$CloseCategoryOld = $CloseCategory;
					}
				}
	//return $CategoryTree;
	
	return $JSON;
}

function DisplayEditableCategories($CategoryTable){
	if($CategoryTable == 'Categories'){
		$query = "SELECT * FROM Categories";
		$result = mysql_query($query);
		while($row = mysql_fetch_array($result)){  
				$CategoryNames[] = $row['CategoryName'];
				
				$CategoryLevels[] = $row['CategoryLevel'];
				
				$CategoryID[] = $row['CategoryID'];
		}
		$query = "SELECT CategoryID FROM Products";
		$result = mysql_query($query);
		while($row = mysql_fetch_array($result)){  
				$CategoryProducts[] = $row['CategoryID'];
		}
		$Test[0]['text'] = 'my pictures';
		$Test[0]['Icon'] = 'fa fa';
		$Test[0]['State']['Selected'] = 'false';
		$Test[1]['text'] = 'my pictures';
		$Test[1]['Icon'] = 'fa fa';

		$Test[1]['Children'][0]['text'] = 'test';
		$Test[1]['Children'][1]['text'] = 'test';
		
		//return json_encode(array(DisplayCategoriesJSON($CategoryNames,$CategoryID,$CategoryLevels)));
		return DisplayCategoryTree($CategoryNames, $CategoryLevels, $CategoryID, $CategoryProducts);
	}else{
		return;	
	}
}*/
//ABOVE IS UNFINISHED~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?>