<?php
if(!isset($_SESSION)) 
{ 
session_start(); 
} 
if(!isset($_SESSION['is_login']) ){
header("location: login.php");
?>
<script>
window.location="login.php";
</script>
<?php
}

// $permission  = explode(',',$_SESSION['permission_id']);
// if(!in_array(19,$permission) && !in_array(1,$permission)  ){

// $op['is_success'] = false;
// $op['data'] 	  = "عذرا انت غير مخول للوصل الى هذه الصفحة";
// echo json_encode($op);
// exit;

// }

date_default_timezone_set($_SESSION['SYSTimezone']);

if (isset($_POST['type']) || isset($_GET['type'])){
		require("db_connect.php");

		if( isset($_GET['type']) && ($_GET['type'] == "load")){
			// DB table to use
			// show All products for specific category
			$cond = isset($_GET['id'])? ' AND P.category_id_fk='.$_GET['id']:'';
			$cond = isset($_GET['it'])? ' AND P.item_type_id_fk='.$_GET['it']:'';
			$table  =  '(
				SELECT
					product_id,
					
					product_name,
					erbil_code,
					turkish_code,
					barcode,
					product_note,
					product_min_notification,
					category_id_fk,
					item_type_id_fk,
					is_hidden,
					item_name,
					image_path
				FROM
					product P
					LEFT JOIN product_image PI ON (PI.product_id_fk = P.product_id AND PI.is_deleted=0)
					, item_type IT
				WHERE
					( P.item_type_id_fk = IT.item_type_id AND P.is_deleted = 0 '.$cond.') GROUP BY P.product_id
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'product_id';
			$columns = array(
			    array( 'db' => 'product_id', 'dt' => 0 ),

			    array( 'db' => 'item_name', 'dt' => 1 ),
			    array( 'db' => 'erbil_code', 'dt' => 2 ),
			    array( 'db' => 'turkish_code', 'dt' => 3 ),
			    array( 'db' => 'barcode', 'dt' => 4 ),
			    array( 'db' => 'product_note', 'dt' => 5 ),
			    // array( 'db' => 'category', 'dt' => 6 ),
					
				array( 'db' => 'is_hidden', 'dt' => 6 ),
				array( 'db' => 'image_path', 'dt' => 7 ),
				array( 'db' => 'category_id_fk', 'dt' => 8 ),
				array( 'db' => 'item_type_id_fk', 'dt' => 9 ),
				array( 'db' => 'product_min_notification', 'dt' => 10 ),


			);
			// SQL server connection information
			$sql_details = array(
			    'user' => $mysql_user,
			    'pass' => $mysql_password,
			    'db'   => $mysql_db,
			    'host' => $mysql_server
			);
			require( 'ssp.php' );
			echo json_encode(
			    SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns ,null, '' )
			);
			exit;
		}

		if ($_POST['type']=="get") {

			//$user_id = $_POST['cusid'];

			$res = $db->query("SELECT 	product_id,
										erbil_code,
										turkish_code,
										barcode
								FROM product P,  item_type IT  
								WHERE P.is_deleted = 0 AND P.is_hidden=0 AND P.item_type_id_fk = IT.item_type_id AND IT.is_have_purchase =0");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_id'];
						$result[1]  = $row['erbil_code'];
						$result[2]  = $row['turkish_code'];
						$result[3]  = $row['barcode'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		if ($_POST['type']=="get_one_product") {

			$productName = $_POST['p_val'];

			$res = $db->query("SELECT 	product_id,
										erbil_code,
										turkish_code,
										barcode
								FROM product P,  item_type IT  
								WHERE P.is_deleted = 0 AND P.item_type_id_fk = IT.item_type_id AND IT.is_have_purchase =0 AND P.erbil_code ='$productName' LIMIT 1");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_id'];
						$result[1]  = $row['erbil_code'];
						$result[2]  = $row['turkish_code'];
						$result[3]  = $row['barcode'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


		if ($_POST['type']=="get_one_product_sell") {

			$productName = $_POST['p_val'];

			$res = $db->query("SELECT 	product_id,
										erbil_code,
										turkish_code,
										item_type_id,
										barcode
								FROM product P,  item_type IT  
								WHERE P.is_deleted = 0 AND P.item_type_id_fk = IT.item_type_id  AND P.erbil_code ='$productName' LIMIT 1");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_id'];
						$result[1]  = $row['erbil_code'];
						$result[2]  = $row['turkish_code'];
						$result[3]  = $row['item_type_id'];
						$result[4]  = $row['barcode'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


		if ($_POST['type']=="get_product_sell") {

			// $productName = $_POST['p_val'];

			$res = $db->query("SELECT 	product_id,
										erbil_code,
										turkish_code,
										item_type_id,
										barcode
								FROM product P,  item_type IT  
								WHERE P.is_deleted = 0 AND P.is_hidden=0  AND P.item_type_id_fk = IT.item_type_id ");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_id'];
						$result[1]  = $row['erbil_code'];
						$result[2]  = $row['turkish_code'];
						$result[3]  = $row['item_type_id'];
						$result[4]  = $row['barcode'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


		if ($_POST['type']=="check_item_type") {

			$p_id = $_POST['p_id'];

			$res = $db->query("SELECT 	product_id,
										erbil_code,
										item_type_id,
										item_name,
										is_have_purchase,
										is_other,
										is_have_curtain,
										barcode
								FROM product P,  item_type IT  
								WHERE P.is_deleted = 0 AND P.item_type_id_fk = IT.item_type_id AND IT.is_deleted =0 AND P.product_id ='$p_id' ");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_id'];
						$result[1]  = $row['erbil_code'];
						$result[2]  = $row['item_type_id'];
						$result[3]  = $row['item_name'];
						$result[4]  = $row['is_have_purchase'];
						$result[5]  = $row['is_other'];
						$result[6]  = $row['is_have_curtain'];
						$result[7]  = $row['barcode'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		if ($_POST['type']=="show_files") {

			$user_id = $_POST['obj_id'];

			$res = $db->query("SELECT * FROM product_image WHERE is_deleted=0 AND product_id_fk = '$user_id'");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['product_image_id'];
						$result[1] = $row['image_path'];
						array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		if ($_POST['type']=="remove_image") {

			$id 		=addslashes($_POST["obj_id"]);
			$img_path 	=addslashes($_POST["img_path"]);

			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Delete Image";

			$op  = array('is_success'=>false, 'data' => '');

			

			

	  		$res = $db->query("UPDATE product_image SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE product_image_id=$id");
	    	if ($res){
	        $op['is_success'] = true;
	        		if(unlink('../'.$img_path)){

    					$op['data'] 	  = "تمت عملية الحذف بنجاح";
						echo json_encode($op);
						exit;
	        		}
					
	     	}else{
	      			$op['is_success'] = false;
					$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
					echo json_encode($op);
					exit;
	     	}
		}

		if ($_POST['type']=="get_income") {

			//$user_id = $_POST['cusid'];

			$res = $db->query("SELECT P.*,C.category,C.category_type,
				(SELECT sum(purchase_quantity) from purchase where purchase.product_id_fk = P.product_id AND purchase.is_deleted=0) as total_quantity,
				(SELECT sum(sell_quantity) from sell_item where sell_item.product_id_fk = P.product_id AND sell_item.is_deleted=0) as sold_quantity,
				(COALESCE((SELECT sum(COALESCE(purchase_quantity, 0)) from purchase where purchase.product_id_fk = P.product_id AND purchase.is_deleted=0),0)  -
					COALESCE((SELECT sum(COALESCE(sell_quantity, 0)) from sell_item where sell_item.product_id_fk = P.product_id AND sell_item.is_deleted=0),0) )  AS Remianed_quantity
				FROM product P, category C WHERE P.category_id_fk=C.category_id AND P.is_deleted = 0 AND C.category_type=0");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_id'];
						$result[1]  = $row['product'];
						$result[2]  = $row['part_number'];
						$result[3]  = $row['made_in'];
						$result[4]  = $row['sell_price'];
						$result[5]  = $row['sell_price_percentage'];
						$result[6]  = $row['average_price'];
						$result[7]  = $row['category_id_fk'];
						$result[8]  = $row['is_deleted'];
						$result[9]  = $row['created_at'];
						$result[10] = $row['updated_at'];
						$result[11] = $row['deleted_at'];
						$result[12] = $row['created_by'];
						$result[13] = $row['last_action'];
						$result[14] = $row['last_action_by'];
						$result[15] = $row['category'];
						$result[16] = $row['category_type'];
						$result[17] = $row['total_quantity'];
						$result[18] = $row['sold_quantity'];
						$result[19] = $row['Remianed_quantity'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		if ($_POST['type'] == "hide_show_itm") {

			$id 		= $_POST['id'];
			
			$vals		=addslashes($_POST["vals"]);

			$op  = array('is_success'=>false, 'data' => '');

					


			$lastaction = "Update Product";
			$update_qry = "UPDATE product SET  is_hidden='$vals',
											   last_action='$lastaction',
											   last_action_by='".$_SESSION['user_id']."' 
									WHERE product_id = $id";


			$res = $db->query($update_qry);
			if ($res) {

				$op['is_success'] = true;
				$op['data'] 	 	  = "تمت العملية بنجاح";
				echo json_encode($op);
				exit;
			}else{
				$op['is_success'] = false;
				$op['data'] 	  	= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
				echo json_encode($op);
				exit;
			}
		}


		if ($_POST['type'] == "update") {

			$id 							= $_POST['itemid'];
			$item_type_id					=addslashes($_POST["edit_item_type_id"]);
			$category_id					=0;
			// $category_id					=addslashes($_POST["category_id"]);
			$erbil_code						=addslashes($_POST["edit_erbil_code"]);
			$turkish_code					=addslashes($_POST["edit_turkish_code"]);
			$barcode						=addslashes($_POST["edit_barcode"]);
			$product_min_notification		=addslashes($_POST["edit_product_min_notification"]);
			$product_note					=addslashes($_POST["edit_product_note"]);

			$op  = array('is_success'=>false, 'data' => '');

			

			// $res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND product_name = '$name' AND product_id != '$id'");
			// if (mysqli_num_rows($res)>0) {
			// 		$op['is_success'] = false;
			// 		$op['data'] 	  = "خطأ اسم المادة مكررة";
			// 		echo json_encode($op);
			// 		exit;
			// }

			$res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND erbil_code = '$erbil_code' AND product_id != '$id'");
			
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطأ الرمز المحلي مكرر";
					echo json_encode($op);
					exit;
			}

			$res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND turkish_code = '$turkish_code' AND product_id != '$id'");
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطأ الرمز الاجنبي مكرر";
					echo json_encode($op);
					exit;
			}


			

					


			$lastaction = "Update Product";
			$update_qry = "UPDATE product SET  item_type_id_fk = '$item_type_id', erbil_code='$erbil_code',turkish_code='$turkish_code',	barcode='$barcode',product_note='$product_note',product_min_notification='$product_min_notification',category_id_fk='$category_id',
										last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE product_id = $id";


			$res = $db->query($update_qry);
			if ($res) {

				$last_inserted_id = $id;

				/// for file upload
				$target_dir = '../product_img/'.$last_inserted_id;
				if(! file_exists($target_dir)){
					mkdir($target_dir);
				}
				// $target_dir = "../image/sys/";

				$count=0;

	            foreach ($_FILES['edit_files_upload']['name'] as $filename){
											
					$fileBook = rand(1000,100000) . "-" .$_FILES['edit_files_upload']['name'][$count];

			          
					$target_file = $target_dir .'/'. basename($fileBook);

					$uploadOk = 1;
					$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

											
					$State=true;
					// Check file size
					if ($_FILES["edit_files_upload"]["size"][$count] > 3500000) {
							$error= " Sorry, your file is too large. ";
							$State=false;
					}
					// Allow certain file formats
					if($imageFileType != "jpg" && $imageFileType != "JPG" && $imageFileType != "png" && $imageFileType != "PNG" && $imageFileType != "jpeg" && $imageFileType != "JPEG" && $imageFileType != "gif" && $imageFileType != "GIF" && $imageFileType != "bmp" && $imageFileType != "BMP") {
							$error= " Sorry, only JPG, JPEG, PNG & GIF & PDF files are allowed. ";
							$State=false;
					}

					// Check if $uploadOk is set to 0 by an error
					if ($State == false) {
						// $error= " Sorry, your file was not uploaded. ";
						// if everything is ok, try to upload file
					} else {
						//move_uploaded_file($tmp,$temp);
						if (move_uploaded_file($_FILES["edit_files_upload"]["tmp_name"][$count], $target_file)) {
							$filePath = 'product_img/'.$last_inserted_id .'/'.$fileBook;
							// $sql = "UPDATE system_settings SET SYSCompanyLogo='$filePath' WHERE SYSID = 1";

							$sql ="INSERT INTO product_image
												(product_id_fk,
												image_path,
												created_by,
												last_action,
												last_action_by)
									VALUES('$last_inserted_id',
											'$filePath',
											'".$_SESSION['user_id']."',
											'$lastaction',
											'".$_SESSION['user_id']."')";


							$query = $db->query($sql);
							if (!$query) {
								$error= "Error: " . $db->error;
								$State=false;

							}else{
								$error= " تمت عملية التحديث بنجاح ";
								$State=true;
							}

						} else {
								$error= " Sorry, there was an error uploading your file. ";
								$State=false;
						}
					}

					$count = $count +1;
	                $filePath='';
	                $tmp='';
	            }

				$op['is_success'] = true;
				$op['data'] 	 	  = $error;
				echo json_encode($op);
				exit;
			}else{
				$op['is_success'] = false;
				$op['data'] 	  	= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
				echo json_encode($op);
				exit;
			}
		}


		if ($_POST['type']=="delete") {

			$id=addslashes($_POST["obj_id"]);
			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Delete Product";

			$op  = array('is_success'=>false, 'data' => '');

			$res = $db->query("SELECT * FROM sell_item WHERE is_deleted=0 AND product_id_fk = '$id'");
			if (mysqli_num_rows($res)>0) {
				$op['is_success'] = false;
				$op['data'] 	  = "لا يمكن حذف هذه المادة فقد تم بيع البعض منها";
				echo json_encode($op);
				exit;
			}

			$res = $db->query("SELECT * FROM purchase_item_detail WHERE is_deleted=0 AND product_id_fk = '$id'");
			if (mysqli_num_rows($res)>0) {
				$op['is_success'] = false;
				$op['data'] 	  = "لا يمكن حذف هذه المادة فهي تحوي على قيم في جدول المشتريات";
				echo json_encode($op);
				exit;
			}

			

	  		$res = $db->query("UPDATE product SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE product_id=$id");
	    	if ($res){
	        $op['is_success'] = true;
					$op['data'] 	  = "تمت عملية الحذف بنجاح";
					echo json_encode($op);
					exit;
	     	}else{
	      			$op['is_success'] = false;
					$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
					echo json_encode($op);
					exit;
	     	}
		}

		if ($_POST['type'] == "create") {
      		$item_type_id					=addslashes($_POST["item_type_id"]);
			$category_id					=0;
			// $category_id					=addslashes($_POST["category_id"]);
			$erbil_code						=addslashes($_POST["erbil_code"]);
			$turkish_code					=addslashes($_POST["turkish_code"]);
			$barcode						=addslashes($_POST["barcode"]);
			$product_note					=addslashes($_POST["product_note"]);
			$product_min_notification		=addslashes($_POST["product_min_notification"]);

			// $res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND product_name = '$name'");
			// if (mysqli_num_rows($res)>0) {
			// 		$op['is_success'] = false;
			// 		$op['data'] 	  = "خطأ اسم المادة مكررة";
			// 		echo json_encode($op);
			// 		exit;
			// }

			$res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND erbil_code = '$erbil_code'");
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطأ الرمز المحلي مكرر";
					echo json_encode($op);
					exit;
			}

			$res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND turkish_code = '$turkish_code'");
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطأ الرمز الاجنبي مكرر";
					echo json_encode($op);
					exit;
			}

				$delete = 0;
				$reg_date = date("Y-m-d h:i:s", time());
				$lastaction = "Create New Product";

				$sql ="INSERT INTO product(item_type_id_fk,erbil_code,turkish_code,barcode,product_note,category_id_fk,created_by,last_action,last_action_by)
				VALUES('$item_type_id','$erbil_code','$turkish_code','$barcode','$product_note','$category_id','".$_SESSION['user_id']."','$lastaction','".$_SESSION['user_id']."')";

				$res = $db->query($sql);

					if ($res) {

						$last_inserted_id = $db->insert_id;

						/// for file upload
						$target_dir = '../product_img/'.$last_inserted_id;
						if(! file_exists($target_dir)){
							mkdir($target_dir);
						}
						// $target_dir = "../image/sys/";

						$count=0;

			            foreach ($_FILES['files_upload']['name'] as $filename)
			            {
											// print_r($_FILES);
			                // $tmp=$_FILES['files_upload']['tmp_name'][$count];
											$fileBook = rand(1000,100000) . "-" .$_FILES['files_upload']['name'][$count];

			                // $temp=$temp.basename($filename);
											$target_file = $target_dir .'/'. basename($fileBook);

											$uploadOk = 1;
											$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

											// $check = getimagesize($_FILES["files_upload"]["tmp_name"][$count]);
										  // if($check == false) {
											// 	 $error= " File is not an image. ";
											// 	 $State=false;
										  // }else {
											//  	 $State=true;
										  // }
											 $State=true;
											// Check file size
											if ($_FILES["files_upload"]["size"][$count] > 3500000) {
													$error= " Sorry, your file is too large. ";
													$State=false;
											}
											// Allow certain file formats
											if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
											&& $imageFileType != "gif" ) {
													$error= " Sorry, only JPG, JPEG, PNG & GIF & PDF files are allowed. ";
													$State=false;
											}

											// Check if $uploadOk is set to 0 by an error
											if ($State == false) {
													$error= " Sorry, your file was not uploaded. ";
											// if everything is ok, try to upload file
											} else {
													//move_uploaded_file($tmp,$temp);
													if (move_uploaded_file($_FILES["files_upload"]["tmp_name"][$count], $target_file)) {
														$filePath = 'product_img/'.$last_inserted_id .'/'.$fileBook;
														// $sql = "UPDATE system_settings SET SYSCompanyLogo='$filePath' WHERE SYSID = 1";

														$sql ="INSERT INTO product_image
																			(product_id_fk,
																			image_path,
																			created_by,
																			last_action,
																			last_action_by)
																VALUES('$last_inserted_id',
																		'$filePath',
																		'".$_SESSION['user_id']."',
																		'$lastaction',
																		'".$_SESSION['user_id']."')";


														$query = $db->query($sql);
														if (!$query) {
																	$error= "Error: " . $db->error;
																	$State=false;

														}else{
																$error= "  Successfully Added ";
																$State=true;
														}

													} else {
															$error= " Sorry, there was an error uploading your file. ";
															$State=false;
													}
											}

											$count = $count +1;
			                $filePath='';
			                $tmp='';
			            }


							$op['is_success'] = true;
							$op['data'] 	  = "تمت عملية الاضافة بنجاح";
							echo json_encode($op);
							exit;
					}
					else{
								$op['is_success'] = false;
								$op['data'] 	  = $db->error;
								echo json_encode($op);
								exit;
					}
			

		}
	}
	else{
		header("Location:../");
		exit;
	}
?>
