<?php
include '../db/db.php';
session_start();

if(isset($_SESSION['userID'])) {
	$log = htmlspecialchars(strip_tags(trim($_SESSION['userID'])), ENT_QUOTES, 'UTF-8');
} else {
	$log = '';
}

if (empty($log)) {     
	$redirectUrl = "../";
	echo "<script type=\"text/javascript\">";
	echo "window.location.href = '$redirectUrl'";
	echo "</script>";
	 
} else {
	$sqlu = "SELECT id FROM user_acc_tbl WHERE userID='$log' and access=1 and val=1";
	$stmtu = mysqli_query($conn, $sqlu);
	$countu = mysqli_num_rows($stmtu);
	
	if($countu == 1) {
		$rowu = mysqli_fetch_assoc($stmtu);
		$uid = $rowu['id'];
		
		date_default_timezone_set('Asia/Colombo');
		$date = date("Y-m-d");
		include("resize_class.php");
		
		/*************************** Insert ***************************/

		function GetImageExtension($imagetype) {
			if(empty($imagetype)) return false;
			switch($imagetype) {
				case 'image/jpeg': return '.jpg';
				case 'image/png': return '.png';
				default: return false;
			}
		}
		
		/*Resizes image on upload to match the given Maximum Dimension*/
		function resizer($file_name_2) {
			$maxDim = 450; /*Adjusts image giving maxDim as width*/
			list($width, $height, $type, $attr) = getimagesize( $file_name_2 );
			if ( $width > $maxDim || $height > $maxDim ) {
				$target_filename = $file_name_2;
				$ratio = $width/$height;
				if( $ratio > 1) {
					$new_width = $maxDim;
					$new_height = $maxDim/$ratio;
				
				} else {
					$new_width = $maxDim*$ratio;
					$new_height = $maxDim;
				}
				$src = imagecreatefromstring( file_get_contents( $file_name_2 ) );
				$dst = imagecreatetruecolor( $new_width, $new_height );
				imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
				imagedestroy( $src );
				imagepng( $dst, $target_filename ); 
				imagedestroy( $dst );
			}
		}
		
		function insert_new_option($conn, $tbl_name, $name) {
			$name = htmlspecialchars(strip_tags(trim($name)), ENT_QUOTES, 'UTF-8');
			$item_name1 = str_replace(["-", "–"], '' ,$name);
			$item_name2 = preg_replace('/\s+/', ' ', $item_name1);
			$search_id = strtolower(str_replace(" ","-",$item_name2));
			
			$sql = mysqli_query($conn, "SELECT id FROM $tbl_name WHERE search_id='$search_id'");
			if(mysqli_num_rows($sql) == 0) {
				$sql_op = mysqli_query($conn, "INSERT INTO $tbl_name SET name='$name', search_id='$search_id'");
				
				if ($sql_op) {
					$sql_it = mysqli_query($conn, "SELECT id FROM $tbl_name WHERE search_id='$search_id'");
					$row_it = mysqli_fetch_assoc($sql_it);
					$row_id = $row_it['id'];
				
				} else {
					$row_id = '';
				}
				
			} else {
				$row = mysqli_fetch_assoc($sql);
				$row_id = $row['id'];
			}
			
			return $row_id;
		}
		
		if(isset($_POST['cat_id'])) {
			$main_cat = $_POST['cat_id'];
			$name = htmlspecialchars(strip_tags(trim($_POST['name'])), ENT_QUOTES, 'UTF-8');
			$price = htmlspecialchars(strip_tags(trim($_POST['price'])), ENT_QUOTES, 'UTF-8');
			$isbn = htmlspecialchars(strip_tags(trim($_POST['isbn'])), ENT_QUOTES, 'UTF-8');
			$item_code = htmlspecialchars(strip_tags(trim($_POST['item_code'])), ENT_QUOTES, 'UTF-8');
			$descrip = htmlspecialchars(strip_tags(trim($_POST['descrip'])), ENT_QUOTES, 'UTF-8');
			$keywords = htmlspecialchars(strip_tags(trim($_POST['keywords'])), ENT_QUOTES, 'UTF-8');
			$width = htmlspecialchars(strip_tags(trim($_POST['width'])), ENT_QUOTES, 'UTF-8');
			$height = htmlspecialchars(strip_tags(trim($_POST['height'])), ENT_QUOTES, 'UTF-8');
			$weight = htmlspecialchars(strip_tags(trim($_POST['weight'])), ENT_QUOTES, 'UTF-8');
			$discount = htmlspecialchars(strip_tags(trim($_POST['discount'])), ENT_QUOTES, 'UTF-8');
			$eng_name = htmlspecialchars(strip_tags(trim($_POST['eng_name'])), ENT_QUOTES, 'UTF-8');
			
			$item_name1 = str_replace(["-", "–"], '' , $name);
			$item_name1 = preg_replace('/\s+/', ' ', $item_name1);
			$search_id = strtolower(str_replace(" ","-",$item_name1)).'-sri-lanka';
			
			$item_name2 = str_replace(["-", "–"], '' ,$eng_name);
			$item_name2 = preg_replace('/\s+/', ' ', $item_name2);
			
			$author_n = htmlspecialchars(strip_tags(trim($_POST['author'])), ENT_QUOTES, 'UTF-8');
			$author = 0;
			$authID_arr = array();
			
			if(!empty($author_n)) {
				$auth_arr = explode(',', $author_n);
				$tbl_name = 'author';
				foreach($auth_arr as $auth) {
					if(!empty($auth)) {
						$author = insert_new_option($conn, $tbl_name, trim($auth));
						array_push($authID_arr, $author);
					}
				}
			}
			
			$publisher_n = htmlspecialchars(strip_tags(trim($_POST['publisher'])), ENT_QUOTES, 'UTF-8');
			$publisher = 0;
			if(!empty($publisher_n)) {
				$tbl_name = 'publisher';
				$publisher = insert_new_option($conn, $tbl_name, $publisher_n);
			}
			
			if(isset($_POST['new_pro'])) {
				$new_pro = htmlspecialchars(strip_tags(trim($_POST['new_pro'])), ENT_QUOTES, 'UTF-8');
			} else {
				$new_pro = 0;
			}
			
			if(isset($_POST['stock_out'])) {
				$stock_out = htmlspecialchars(strip_tags(trim($_POST['stock_out'])), ENT_QUOTES, 'UTF-8');
			} else {
				$stock_out = 0;
			}
			
			if(isset($_POST['feature_pro'])) {
				$feature_pro = htmlspecialchars(strip_tags(trim($_POST['feature_pro'])), ENT_QUOTES, 'UTF-8');
			} else {
				$feature_pro = 0;
			}
			
			if(isset($_POST['best_sell'])) {
				$best_sell = htmlspecialchars(strip_tags(trim($_POST['best_sell'])), ENT_QUOTES, 'UTF-8');
			} else {
				$best_sell = 0;
			}
			
			if(isset($_POST['kids_book'])) {
				$kids_book = htmlspecialchars(strip_tags(trim($_POST['kids_book'])), ENT_QUOTES, 'UTF-8');
			} else {
				$kids_book = 0;
			}
			
			$cat_name = '';
			foreach($main_cat as $catID) {
				if(!empty($catID)) {
					$sql_cat = mysqli_fetch_assoc(mysqli_query($conn, "SELECT category FROM category WHERE id=$catID"));
					$cat_name .= $sql_cat['category'].', ';
				}
			}
			
			$keyw = '';
			if(!empty($cat_name)) { $keyw .= $cat_name; }
			if(!empty($name)) { $keyw .= $name.", "; }
			if(!empty($isbn)) { $keyw .= $isbn.", "; }
			if(!empty($author_n)) { $keyw .= $author_n.", "; }
			if(!empty($descrip)) { $keyw .= $descrip.", "; }
			if(!empty($keywords)) { $keyw .= $keywords.", "; }
			if(!empty($publisher_n)) { $keyw .= $publisher_n; }
			
			$stmt = mysqli_query($conn, "SELECT isbn FROM bookdetails WHERE isbn='$isbn'");
			$row_count = mysqli_num_rows($stmt);
			
			$sql_ct = mysqli_query($conn, "SELECT search_id FROM bookdetails WHERE search_id='$search_id'");
			$row_ct = mysqli_num_rows($sql_ct);
		
			if ($row_ct == 0) {
				if ($row_count == 0) {
					if(isset($_FILES["file_name1"]["name"])) {
						$img1 = strtolower(htmlspecialchars(strip_tags(trim($_FILES["file_name1"]["name"])), ENT_QUOTES, 'UTF-8'));
					} else {
						$img1 = '';
					}

					if (empty($img1)) {
						$sql = "INSERT INTO bookdetails SET name='$name', eng_name='$eng_name', price='$price', isbn='$isbn', publisher='$publisher', description='$descrip', key_words='$keyw', new_arrivals='$new_pro', create_date=now(), item_code='$item_code', width='$width', height='$height', weight='$weight', discount='$discount', stock_out='$stock_out', featured_pro='$feature_pro', search_id='$search_id', best_seller=$best_sell, kids_book=$kids_book, tags='$keywords'";
						$stmt_log = mysqli_query($conn, $sql);
						
						if ($stmt_log === false) {
							echo 'error';

						} else {
							$sql_bk = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id FROM bookdetails WHERE search_id='$search_id'"));
							$Book_ID = $sql_bk['id'];
							
							foreach($main_cat as $catID) {
								if(!empty($catID) && !empty($Book_ID)) {
									$sqlb = "INSERT INTO category_map (Book_ID, Cat_ID) VALUES ($Book_ID, $catID)";
									mysqli_query( $conn, $sqlb);
								}
							}
							
							foreach($authID_arr as $authID) {
								if(!empty($authID) && !empty($Book_ID)) {
									$sqlb = "INSERT INTO author_map (Book_ID, Auth_ID) VALUES ($Book_ID, $authID)";
									mysqli_query( $conn, $sqlb);
								}
							}
							echo 'success';
						}
						
					} else {
						if(isset($_FILES["file_name2"]["name"])) {
							$img2 = strtolower(htmlspecialchars(strip_tags(trim($_FILES["file_name2"]["name"])), ENT_QUOTES, 'UTF-8'));
						
						} else {
							$img2 = '';
						}
						
						if (empty($img2)) {
							$tmp1 = $_FILES["file_name1"]["tmp_name"];
							$imgtype = $_FILES["file_name1"]["type"];
							$ext1 = GetImageExtension($imgtype);
							
							if($ext1) {
								$front_image = strtolower(str_replace(" ","-",$item_name2)).'-fcover-sri-lanka'.$ext1;
								$target_path1 = "../../image/books/".$front_image;
								//resizer($tmp1);

								if(move_uploaded_file($tmp1, $target_path1)) {
									/*Image thumbnail resizer with resize class*/
									$resize = new ResizeImage($target_path1);
									/* $resize->resizeTo(100, 100, 'maxWidth');
									$resize->resizeTo(100, 100, 'maxHeight');
									$resize->resizeTo(100, 100);          */
									
									$resize->resizeTo(204, 306, 'exact');
									$r = $resize->saveImage('../../image/books/thumb/'.$front_image);
								
									if($r) {
										$sql = "INSERT INTO bookdetails SET name='$name', eng_name='$eng_name', price='$price', isbn='$isbn', publisher='$publisher', description='$descrip', key_words='$keyw', new_arrivals='$new_pro', create_date=now(), item_code='$item_code', front_image='$front_image', width='$width', height='$height', weight='$weight', discount='$discount', stock_out='$stock_out', featured_pro='$feature_pro', search_id='$search_id', best_seller=$best_sell, kids_book=$kids_book, tags='$keywords'";
										$stmt_log = mysqli_query($conn, $sql);
										
										if($stmt_log === false) {
											echo 'error';
										
										} else {
											$sql_bk = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id FROM bookdetails WHERE search_id='$search_id'"));
											$Book_ID = $sql_bk['id'];
											
											foreach($main_cat as $catID) {
												if(!empty($catID) && !empty($catID)) {
													$sqlb = "INSERT INTO category_map (Book_ID, Cat_ID) VALUES ($Book_ID, $catID)";
													mysqli_query( $conn, $sqlb);
												}
											}
											foreach($authID_arr as $authID) {
												if(!empty($authID) && !empty($Book_ID)) {
													$sqlb = "INSERT INTO author_map (Book_ID, Auth_ID) VALUES ($Book_ID, $authID)";
													mysqli_query( $conn, $sqlb);
												}
											}
											echo 'success';
										}
									
									} else {
										echo 'error2'; // Uploading Error
									}
								
								} else {
									echo 'error2'; // Uploading Error
								}
							
							} else {
								echo 'error3'; // Invaild File
							}
							
						} else {
							$tmp1 = $_FILES["file_name1"]["tmp_name"];
							$imgtype1 = $_FILES["file_name1"]["type"];
							$ext1 = GetImageExtension($imgtype1);
							
							$tmp2 = $_FILES["file_name2"]["tmp_name"];
							$imgtype2 = $_FILES["file_name2"]["type"];
							$ext2 = GetImageExtension($imgtype2);
							
							if($ext1 && $ext2) {
								$front_image = strtolower(str_replace(" ","-",$item_name2)).'-fcover-sri-lanka'.$ext1;
								$target_path1 = "../../image/books/".$front_image;
								//resizer($tmp1);
								
								$back_image = strtolower(str_replace(" ","-",$item_name2)).'-bcover-sri-lanka'.$ext2;
								$target_path2 = "../../image/books/".$back_image;
								//resizer($tmp2);

								if(move_uploaded_file($tmp1, $target_path1) && move_uploaded_file($tmp2, $target_path2)){
									/*Image thumbnail resizer with resize class*/
									$resize1 = new ResizeImage($target_path1);
									$resize1->resizeTo(204, 306, 'exact');
									$r1 = $resize1->saveImage('../../image/books/thumb/'.$front_image);
									
									/*Image thumbnail resizer with resize class*/
									$resize2 = new ResizeImage($target_path2);
									$resize2->resizeTo(204, 306, 'exact');
									$r2 = $resize2->saveImage('../../image/books/thumb/'.$back_image);
								
									if($r1 && $r2) {
										$sql = "INSERT INTO bookdetails SET name='$name', eng_name='$eng_name', price='$price', isbn='$isbn', publisher='$publisher', description='$descrip', key_words='$keyw', new_arrivals='$new_pro', create_date=now(), item_code='$item_code', front_image='$front_image', back_image='$back_image', width='$width', height='$height', weight='$weight', discount='$discount', stock_out='$stock_out', featured_pro='$feature_pro', search_id='$search_id', best_seller=$best_sell, kids_book=$kids_book, tags='$keywords'";
										$stmt_log = mysqli_query($conn, $sql);
										
										if($stmt_log === false) {
											echo 'error';
										
										} else {
											$sql_bk = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id FROM bookdetails WHERE search_id='$search_id'"));
											$Book_ID = $sql_bk['id'];
											
											foreach($main_cat as $catID) {
												if(!empty($catID) && !empty($catID)) {
													$sqlb = "INSERT INTO category_map (Book_ID, Cat_ID) VALUES ($Book_ID, $catID)";
													mysqli_query( $conn, $sqlb);
												}
											}
											foreach($authID_arr as $authID) {
												if(!empty($authID) && !empty($Book_ID)) {
													$sqlb = "INSERT INTO author_map (Book_ID, Auth_ID) VALUES ($Book_ID, $authID)";
													mysqli_query( $conn, $sqlb);
												}
											}
											echo 'success';
										}
									
									} else {
										echo 'error2'; // Uploading Error
									}
								
								} else {
									echo 'error2'; // Uploading Error
								}
							
							} else {
								echo 'error3'; // Invaild File
							}
						}
					}
				
				} else {
					echo 'data exist';
				}
			
			} else {
				echo 'data exist1';
			}
		}
		
		/************************ Load Form Data ************************/
	    
		if (array_key_exists('get_dataset', $_POST)) {
			$id = htmlspecialchars(strip_tags(trim($_POST['id'])), ENT_QUOTES, 'UTF-8');
			$data = array(); 
			
			$sql = mysqli_query($conn, "SELECT * FROM bookdetails WHERE id=$id"); 
			$row = mysqli_fetch_assoc($sql);
			
			$sql_pub = mysqli_fetch_assoc(mysqli_query($conn, "SELECT name FROM publisher WHERE id=".$row['publisher']));

			array_push($data, $row);
			array_push($data, array('publishern'=> $sql_pub['name']));
			
			echo json_encode($data);
	    }
		
		/*************************** Update ***************************/
		
		if(isset($_POST['id_up'])) {
			$id_up = htmlspecialchars(strip_tags(trim($_POST['id_up'])), ENT_QUOTES, 'UTF-8');
			$name = htmlspecialchars(strip_tags(trim($_POST['name'])), ENT_QUOTES, 'UTF-8');
			$price = htmlspecialchars(strip_tags(trim($_POST['price'])), ENT_QUOTES, 'UTF-8');
			$isbn = htmlspecialchars(strip_tags(trim($_POST['isbn'])), ENT_QUOTES, 'UTF-8');
			$item_code = htmlspecialchars(strip_tags(trim($_POST['item_code'])), ENT_QUOTES, 'UTF-8');
			$descrip = htmlspecialchars(strip_tags(trim($_POST['descrip'])), ENT_QUOTES, 'UTF-8');
			$keywords = htmlspecialchars(strip_tags(trim($_POST['keywords'])), ENT_QUOTES, 'UTF-8');
			$width = htmlspecialchars(strip_tags(trim($_POST['width'])), ENT_QUOTES, 'UTF-8');
			$height = htmlspecialchars(strip_tags(trim($_POST['height'])), ENT_QUOTES, 'UTF-8');
			$weight = htmlspecialchars(strip_tags(trim($_POST['weight'])), ENT_QUOTES, 'UTF-8');
			$discount = htmlspecialchars(strip_tags(trim($_POST['discount'])), ENT_QUOTES, 'UTF-8');
			$eng_name = htmlspecialchars(strip_tags(trim($_POST['eng_name'])), ENT_QUOTES, 'UTF-8');
			
			$publisher_n = htmlspecialchars(strip_tags(trim($_POST['publisher'])), ENT_QUOTES, 'UTF-8');
			$publisher = 0;
			if(!empty($publisher_n)) {
				$tbl_name = 'publisher';
				$publisher = insert_new_option($conn, $tbl_name, $publisher_n);
			}

			$item_name1 = str_replace(["-", "–"], '' ,$name);
			$item_name1 = preg_replace('/\s+/', ' ', $item_name1);
			$search_id = strtolower(str_replace(" ","-",$item_name1)).'-sri-lanka';
			
			$item_name2 = str_replace(["-", "–"], '' ,$eng_name);
			$item_name2 = preg_replace('/\s+/', ' ', $item_name2);
			
			if(isset($_POST['new_pro'])) {
				$new_pro = htmlspecialchars(strip_tags(trim($_POST['new_pro'])), ENT_QUOTES, 'UTF-8');
			} else {
				$new_pro = 0;
			}
			
			if(isset($_POST['feature_pro'])) {
				$feature_pro = htmlspecialchars(strip_tags(trim($_POST['feature_pro'])), ENT_QUOTES, 'UTF-8');
			} else {
				$feature_pro = 0;
			}
			
			if(isset($_POST['best_sell'])) {
				$best_sell = htmlspecialchars(strip_tags(trim($_POST['best_sell'])), ENT_QUOTES, 'UTF-8');
			} else {
				$best_sell = 0;
			}
			
			if(isset($_POST['kids_book'])) {
				$kids_book = htmlspecialchars(strip_tags(trim($_POST['kids_book'])), ENT_QUOTES, 'UTF-8');
			} else {
				$kids_book = 0;
			}
			
			if(isset($_POST['stock_out'])) {
				$stock_out = htmlspecialchars(strip_tags(trim($_POST['stock_out'])), ENT_QUOTES, 'UTF-8');
			} else {
				$stock_out = 0;
			}
			
			$cat_name = $author_n = '';
			$sql_cat = mysqli_query($conn, "SELECT category FROM category WHERE id IN (SELECT Cat_ID FROM category_map WHERE Book_ID=$id_up)");
			while($row_cat = mysqli_fetch_array($sql_cat)) {
				$cat_name .= $row_cat['category'].', ';
			}
			
			$sql_au = mysqli_query($conn, "SELECT name FROM author WHERE id IN (SELECT Auth_ID FROM author_map WHERE Book_ID=$id_up)");
			while($row_au = mysqli_fetch_array($sql_au)) {
				$author_n .= $row_au['name'].', ';
			}

			$keyw = '';
			if(!empty($cat_name)) { $keyw .= $cat_name; }
			if(!empty($name)) { $keyw .= $name.", "; }
			if(!empty($isbn)) { $keyw .= $isbn.", "; }
			if(!empty($author_n)) { $keyw .= $author_n.", "; }
			if(!empty($descrip)) { $keyw .= $descrip.", "; }
			if(!empty($keywords)) { $keyw .= $keywords.", "; }
			if(!empty($publisher_n)) { $keyw .= $publisher_n; }
			
			$stmt = mysqli_query($conn, "SELECT isbn FROM bookdetails WHERE isbn='$isbn' AND id!=$id_up");
			$row_count = mysqli_num_rows($stmt);
			
			$sql_ct = mysqli_query($conn, "SELECT search_id FROM bookdetails WHERE search_id='$search_id' AND id!=$id_up");
			$row_ct = mysqli_num_rows($sql_ct);
		
			if($row_ct == 0) {
				if($row_count == 0) {
					$updt = true;
					
					if(isset($_FILES["file_name1"]["name"])) {
						$img1 = strtolower(htmlspecialchars(strip_tags(trim($_FILES["file_name1"]["name"])), ENT_QUOTES, 'UTF-8'));
					
					} else {
						$img1 = '';
					}
					
					if(isset($_FILES["file_name2"]["name"])) {
						$img2 = strtolower(htmlspecialchars(strip_tags(trim($_FILES["file_name2"]["name"])), ENT_QUOTES, 'UTF-8'));
					
					} else {
						$img2 = '';
					}

					$sql = "UPDATE bookdetails SET name='$name', eng_name='$eng_name', price='$price', isbn='$isbn', publisher='$publisher', description='$descrip', key_words='$keyw', new_arrivals='$new_pro', item_code='$item_code', width='$width', height='$height', weight='$weight', discount='$discount', featured_pro='$feature_pro', stock_out='$stock_out', search_id='$search_id', best_seller=$best_sell, kids_book=$kids_book, tags='$keywords' WHERE id=$id_up";
					$stmt_log = mysqli_query($conn, $sql);
					
					if($stmt_log === false) {
						$updt = false;
					
					} else {
						$updt = true;
					}
					
					if(!empty($img1)) {
						$tmp = $_FILES["file_name1"]["tmp_name"];
						$imgtype = $_FILES["file_name1"]["type"];
						$ext = GetImageExtension($imgtype);
						
						if($ext) {
							$front_image = strtolower(str_replace(" ","-",$item_name2)).'-fcover-sri-lanka'.$ext;
							$target_path = "../../image/books/".$front_image;
							//resizer($tmp);

							if(move_uploaded_file($tmp, $target_path)){
								/*Image thumbnail resizer with resize class*/
								$resize = new ResizeImage($target_path);
								$resize->resizeTo(204, 306, 'exact');
								$r = $resize->saveImage('../../image/books/thumb/'.$front_image);
							
								if($r) {
									$sql = "UPDATE bookdetails SET front_image='$front_image' WHERE id=$id_up";
									$stmt_log = mysqli_query($conn, $sql);
									
									if($stmt_log === false) {
										$updt = false;
									
									} else {
										$updt = true;
									}
								
								} else {
									echo 'error2'; // Uploading Error
								}
							
							} else {
								echo 'error2'; // Uploading Error
							}
						
						} else {
							echo 'error3'; // Invaild File
						}
					}
					
					if(!empty($img2)) {
						$tmp = $_FILES["file_name2"]["tmp_name"];
						$imgtype = $_FILES["file_name2"]["type"];
						$ext = GetImageExtension($imgtype);
						
						if($ext) {
							$back_image = strtolower(str_replace(" ","-",$item_name2)).'-bcover-sri-lanka'.$ext;
							$target_path = "../../image/books/".$back_image;
							//resizer($tmp);

							if(move_uploaded_file($tmp, $target_path)){
								/*Image thumbnail resizer with resize class*/
								$resize = new ResizeImage($target_path);
								$resize->resizeTo(204, 306, 'exact');
								$r = $resize->saveImage('../../image/books/thumb/'.$back_image);
							
								if($r) {
									$sql = "UPDATE bookdetails SET back_image='$back_image' WHERE id=$id_up";
									$stmt_log = mysqli_query($conn, $sql);
									
									if($stmt_log === false) {
										$updt = false;
									
									} else {
										$updt = true;
									}
								
								} else {
									echo 'error2'; // Uploading Error
								}
							
							} else {
								echo 'error2'; // Uploading Error
							}
						
						} else {
							echo 'error3'; // Invaild File
						}
					}
					
					if($updt) {
						echo 'success';
					
					} else {
						echo 'error';
					}
				
				} else {
					echo 'data exist';
				}
			
			} else {
				echo 'data exist1';
			}
		}
		
		/***************************** Remove ***************************/
		
	    if (array_key_exists('remove_data', $_POST)) {
			$id = htmlspecialchars(strip_tags(trim($_POST['id'])), ENT_QUOTES, 'UTF-8');
			
			$sql_nw = "INSERT INTO bookdetails_del SELECT *, now() AS del_date, $uid AS uid, NULL AS id FROM bookdetails WHERE id=$id";
			$sql_log = mysqli_query($conn, $sql_nw);
			
			if( $sql_log === false ) {
				echo json_encode(array("msgType" => 2, "msg" => "error"));
			
			} else {
				$sql = "DELETE FROM bookdetails WHERE id=$id";
				$stmt_log = mysqli_query($conn, $sql);
				
				if( $stmt_log === false ) {
					echo json_encode(array("msgType" => 2, "msg" => "Sorry ! not deleted"));
				
				} else {
					echo json_encode(array("msgType" => 1, "msg" => "Successfully Removed"));
				}
			}
	    }
		
		/***************************** Edit Category ***************************/
		
		if(isset($_POST['cat_id_up'])) {
			$id_up_cat = htmlspecialchars(strip_tags(trim($_POST['id_up_cat'])), ENT_QUOTES, 'UTF-8');
			$sql_bk = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM bookdetails WHERE id=$id_up_cat"));
			
			$main_cat = $_POST['cat_id_up'];
			if(count($main_cat) == 0 || empty($id_up_cat)) {
				echo 'empty';
			
			} else {
				$cat_name = $author_n = '';
				foreach($main_cat as $catID) {
					if(!empty($catID)) {
						$sql_cat = mysqli_fetch_assoc(mysqli_query($conn, "SELECT category FROM category WHERE id=$catID"));
						$cat_name .= $sql_cat['category'].', ';
					}
				}
				
				$sql_au = mysqli_query($conn, "SELECT name FROM author WHERE id IN (SELECT Auth_ID FROM author_map WHERE Book_ID=$id_up_cat)");
				while($row_au = mysqli_fetch_array($sql_au)) {
					$author_n .= $row_au['name'].', ';
				}

				$keyw = '';
				if(!empty($cat_name)) { $keyw .= $cat_name; }
				if(!empty($sql_bk['name'])) { $keyw .= $sql_bk['name'].", "; }
				if(!empty($sql_bk['isbn'])) { $keyw .= $sql_bk['isbn'].", "; }
				if(!empty($author_n)) { $keyw .= $author_n.", "; }
				if(!empty($sql_bk['description'])) { $keyw .= $sql_bk['description'].", "; }
				if(!empty($sql_bk['tags'])) { $keyw .= $sql_bk['tags'].", "; }
				if(!empty($sql_bk['publisher'])) { 
					$sql_pub = mysqli_fetch_assoc(mysqli_query($conn, "SELECT name FROM publisher WHERE id=".$sql_bk['publisher']));
					$pub_name = $sql_pub['name'];
					if(!empty($pub_name)) {
						$keyw .= $pub_name; 
					}
				}
				
				$sql_up = "UPDATE bookdetails SET key_words='$keyw' WHERE id=$id_up_cat";
				$stmt_log = mysqli_query($conn, $sql_up);
				
				if($stmt_log === false) {
					echo 'error';
				
				} else {
					echo 'success';
			
					$sql_delc = mysqli_query($conn, "DELETE FROM category_map WHERE Book_ID=$id_up_cat");
					if($sql_delc) {
						foreach($main_cat as $catID) {
							if(!empty($catID) && !empty($id_up_cat)) {
								$sqlb = "INSERT INTO category_map (Book_ID, Cat_ID) VALUES ($id_up_cat, $catID)";
								mysqli_query( $conn, $sqlb);
							}
						}
					}
				}
			}
		}
		
		/***************************** Edit Author ***************************/
		
		if(isset($_POST['id_up_auth'])) {
			$id_up_auth = htmlspecialchars(strip_tags(trim($_POST['id_up_auth'])), ENT_QUOTES, 'UTF-8');
			$author_n = htmlspecialchars(strip_tags(trim($_POST['author_up'])), ENT_QUOTES, 'UTF-8');
			
			$sql_bk = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM bookdetails WHERE id=$id_up_auth"));

			if(empty($author_n) || empty($id_up_auth)) {
				echo 'empty';
			
			} else {
				$cat_name = '';
				$author = 0;
				$authID_arr = array();
				
				if(!empty($author_n)) {
					$auth_arr = explode(',', $author_n);
					$tbl_name = 'author';
					foreach($auth_arr as $auth) {
						if(!empty($auth)) {
							$author = insert_new_option($conn, $tbl_name, trim($auth));
							array_push($authID_arr, $author);
						}
					}
				}
				
				$sql_ct = mysqli_query($conn, "SELECT category FROM category WHERE id IN (SELECT Cat_ID FROM category_map WHERE Book_ID=$id_up_auth)");
				while($row_ct = mysqli_fetch_array($sql_ct)) {
					$cat_name .= $row_ct['category'].', ';
				}

				$keyw = '';
				if(!empty($cat_name)) { $keyw .= $cat_name; }
				if(!empty($sql_bk['name'])) { $keyw .= $sql_bk['name'].", "; }
				if(!empty($sql_bk['isbn'])) { $keyw .= $sql_bk['isbn'].", "; }
				if(!empty($author_n)) { $keyw .= $author_n.", "; }
				if(!empty($sql_bk['description'])) { $keyw .= $sql_bk['description'].", "; }
				if(!empty($sql_bk['tags'])) { $keyw .= $sql_bk['tags'].", "; }
				if(!empty($sql_bk['publisher'])) { 
					$sql_pub = mysqli_fetch_assoc(mysqli_query($conn, "SELECT name FROM publisher WHERE id=".$sql_bk['publisher']));
					$pub_name = $sql_pub['name'];
					if(!empty($pub_name)) {
						$keyw .= $pub_name; 
					}
				}
				
				$sql_up = "UPDATE bookdetails SET key_words='$keyw' WHERE id=$id_up_auth";
				$stmt_log = mysqli_query($conn, $sql_up);
				
				if($stmt_log === false) {
					echo 'error';
				
				} else {
					echo 'success';
			
					$sql_delc = mysqli_query($conn, "DELETE FROM author_map WHERE Book_ID=$id_up_auth");
					if($sql_delc) {
						foreach($authID_arr as $authID) {
							if(!empty($authID) && !empty($id_up_auth)) {
								$sqlb = "INSERT INTO author_map (Book_ID, Auth_ID) VALUES ($id_up_auth, $authID)";
								mysqli_query( $conn, $sqlb);
							}
						}
					}
				}
			}
		}
		
		/*******************************************************/
		
	} else {
		$redirectUrl = "../";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUrl'";
		echo "</script>";
	}
}
?>