<?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
			$cond1 = isset($_GET['id'])? ' AND P.category_id_fk='.$_GET['id']:'';
			
			$cond2 = isset($_GET['tp'])? ' AND P.product_type="'.$_GET['tp'].'"':'';

			$cond = $cond1 . " " . $cond2;
			$table  =  '(
				SELECT
					product_id,
					
					product_name,
					product_code,
					P.barcode,
					made_in,
					image_path,
					product_type,
					product_note,
					P.sell_price,
					category_id_fk,
					
					category
					
				FROM
					product P
					LEFT JOIN category C ON (P.category_id_fk = C.category_id)
					
					
				WHERE
					( P.is_deleted = 0  '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'product_id';
			$columns = array(
			    array( 'db' => 'product_id', 'dt' => 0 ),
			    array( 'db' => 'product_name', 'dt' => 1 ),

			    // array( 'db' => 'serials', 'dt' => 2 ),
			    array( 'db' => 'sell_price', 'dt' => 2 ),
			    array( 'db' => 'product_note', 'dt' => 3 ),
			    array( 'db' => 'category', 'dt' => 4 ),
			    array( 'db' => 'image_path', 'dt' => 5 ),	
			    array( 'db' => 'category_id_fk', 'dt' => 6 ),	
				
				
			);
			// 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,
										product_name,
										product_code ,
										product_type,
										barcode,
										sell_price 
									FROM product P 
								WHERE P.is_deleted = 0 ");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_id'];
						$result[1]  = $row['product_name'];
						$result[2]  = $row['product_code'];
						$result[3]  = $row['barcode'];
						$result[4]  = $row['product_type'];
						$result[5]  = $row['sell_price'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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

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

			$res = $db->query("SELECT product_id,
									  product_name,
									  product_code,
									  sell_price,
									  barcode,
									  (SELECT cost_price FROM purchase_item PI WHERE PI.is_deleted=0 AND P.product_id = PI.product_id_fk ORDER BY purchase_item_id DESC LIMIT 1 ) AS buy_price
								FROM product P  WHERE P.is_deleted = 0 ");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result['product_id']  		= $row['product_id'];
						$result['product_name']  	= $row['product_name'];
						$result['product_code'] 	= $row['product_code'];
						$result['barcode']  		= $row['barcode'];
						$result['sell_price']  		= $row['sell_price'];
						$result['buy_price']  		= $row['buy_price'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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

			$id = $_POST['id'];

			$res = $db->query("SELECT product_serial_id,serial_no FROM product_serials P WHERE P.is_deleted = 0 AND P.product_id_fk ='$id'");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_serial_id'];
						$result[1]  = $row['serial_no'];
						
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


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

			$id = $_POST['obj_id'];
			$op  = array('is_success'=>false, 'data' => array());

			$res = $db->query("SELECT 
									product_id,
				
									product_name,
									product_code,
									company_code,
									sell_price,

									product_note,
									
									category_id_fk
				 				FROM product P  WHERE P.is_deleted = 0 AND product_id = '$id'");
			if ($res) {
				
				
				while ($row = $res->fetch_assoc()) {
				   
						$result['product_id']  		= $row['product_id'];
						$result['product_name']  	= $row['product_name'];
						$result['product_code']  	= $row['product_code'];
						$result['company_code']  	= $row['company_code'];
						$result['sell_price']  		= $row['sell_price'];
						$result['product_note']  	= $row['product_note'];
						$result['category_id_fk']  	= $row['category_id_fk'];
						
						array_push($op['data'],$result);
				}
				$op['is_success'] = true;
				echo json_encode($op);
				exit;
			}else{
				$op['is_success'] = false;
				$op['data'] 	  = "No Data";
				echo json_encode($op);

				exit;
			}
		}

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

			$productName = $_POST['p_val'];

			$res = $db->query("SELECT product_id,erbil_code,turkish_code 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'];
						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 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'];
						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 SET image_path = '',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE product_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']=="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['image_path'];
						array_push($op,$result);
				}

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


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

			$id = $_POST['category_id'];
			$cond = "";
			
			if($id !='' AND $id !=NULL AND $id > 0){
				$cond = " AND P.category_id_fk='$id' ";
			}


			$res = $db->query('

								SELECT
										product_id,
										
										product_name,
										product_code,
										barcode,
										made_in,
										image_path,
										color,

										total_length,
										total_area,
										width,
										height,
										thickness,
										liter,

										product_type,
										product_sequence,
										product_note,
										product_min_notification,
										
										category_id_fk,
										category
									FROM
										product P
										LEFT JOIN category C ON (P.category_id_fk = C.category_id)
										
									WHERE
										( P.is_deleted = 0 '.$cond.') 

								');
			if ($res) {
				
				$op  = array('invoice'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {
				   
					$result['product_id']  					= $row['product_id'];
					$result['product_name']  				= $row['product_name'];
					$result['product_code']  				= $row['product_code'];
					$result['barcode']  					= $row['barcode'];
					$result['made_in'] 						= $row['made_in'];
					$result['image_path']  					= $row['image_path'];
					$result['color']  						= $row['color'];
					$result['product_type']  				= $row['product_type'];
					$result['product_sequence']  			= $row['product_sequence'];
					$result['product_note']  				= $row['product_note'];
					$result['product_min_notification']  	= $row['product_min_notification'];
					$result['category']						= $row['category'];
					$result['category_id_fk']  				= $row['category_id_fk'];

					$result['total_length']  				= $row['total_length'];
					$result['total_area']  					= $row['total_area'];
					$result['width']  						= $row['width'];
					$result['height']  						= $row['height'];
					$result['thickness']  					= $row['thickness'];
					$result['liter']  						= $row['liter'];
					
					array_push($op['invoice'],$result);
			
				}		
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

	


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

			$id 						= $_POST['edit_objid'];
			$category_id_fk				=addslashes($_POST["edit_category_id_fk"]);
			
			$product_name				=addslashes($_POST["edit_product_name"]);
			$product_note				=addslashes($_POST["edit_product_note"]);
			$sell_price					=addslashes($_POST["edit_sell_price"]);			
			

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

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

			$res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND product_name = '$product_name' 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  
									product_name 	= '$product_name',
									sell_price 		='$sell_price',
									product_note 	='$product_note',
									
									category_id_fk 	='$category_id_fk',
									updated_at		='$reg_date',
									last_action		='$lastaction',
									last_action_by	='".$_SESSION['user_id']."' 
							WHERE   product_id = $id";


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

					$target_dir = '../product_img/'.$id;
					if(! file_exists($target_dir)){
						mkdir($target_dir);
					}

					
					
					if($_FILES['edit_image_path']['size'] > 0 ){
						
						$ext11  = pathinfo(basename($_FILES['edit_image_path']['name']),PATHINFO_EXTENSION);
						
						$image_file = $id ."_". rand(100000,10000000) ."_.".$ext11;
						
						$target_file 		= $target_dir .'/'. basename($image_file);
						
						$uploadOk = 1;
						$imageFileType  = pathinfo($target_file,PATHINFO_EXTENSION);
											
						$State1=true;
						// Check file size
						if ($_FILES["edit_image_path"]["size"] > 4000000) {
								$error1= " Sorry, your Image is too large. ";
								$State1=false;
						}

						
						// Allow certain file formats
						if(strtolower($imageFileType) != "jpg" && strtolower($imageFileType) != "png" && strtolower($imageFileType) != "jpeg" && strtolower($imageFileType) != "gif" && strtolower($imageFileType) != "bmp" && strtolower($imageFileType) != "pdf" ) {
							$error1= " Sorry, only JPG, JPEG, PNG & GIF & PDF files are allowed. ";
							$State1=false;
						}

						// Check if $uploadOk is set to 0 by an error
						if ($State1 == true) {
						
							if (move_uploaded_file($_FILES["edit_image_path"]["tmp_name"], $target_file)){

								$image_path  = 'product_img/'.$id .'/'.$image_file;
								$State1=true;											  

							} else {
								$error1= " Sorry, there was an error uploading your file. ";
								$State1=false;
							}
						}
					}		
	                
	                $tmp 			='';
			        $update_file 	= '';
			        
			        if($image_path !=''){
			        	$update_file = "image_path = '$image_path'";

			        }

			       
			        // echo $update_file;
			        if($update_file !=''){
			        	$sql ="UPDATE  product SET $update_file WHERE product_id ='$id'";
								
						$query = $db->query($sql);
			        }
			        
					



					$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']=="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 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") {

      		$category_id_fk				=addslashes($_POST["category_id_fk"]);
			
			$product_name				=addslashes($_POST["product_name"]);
			$sell_price					=addslashes($_POST["sell_price"]);
			// $product_code				=addslashes($_POST["product_code"]);
			// $barcode					=addslashes($_POST["barcode"]);
			// $made_in					=addslashes($_POST["made_in"]);
			$product_note				=addslashes($_POST["product_note"]);			
			// $color						=addslashes($_POST["color"]);			
			// $company_code				=addslashes($_POST["company_code"]);			
			// // $product_min_notification	=addslashes($_POST["product_min_notification"]);
			
			if($category_id_fk ==''){
				$category_id_fk = 0;
			}

			$res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND product_name = '$product_name'");
			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 (
										product_name,
										product_note,
										sell_price,
										category_id_fk,
										created_by,
										last_action,
										last_action_by,
										created_at,
										updated_at)
								VALUES( '$product_name',
										
										'$product_note',
										'$sell_price',
										'$category_id_fk',
										'".$_SESSION['user_id']."',
										'$lastaction',
										'".$_SESSION['user_id']."',
										'$reg_date',
										'$reg_date')";

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

					


					
					if($_FILES['image_path']['size'] > 0 ){
						
						$ext11  = pathinfo(basename($_FILES['image_path']['name']),PATHINFO_EXTENSION);
						
						$image_file = $last_inserted_id."_".rand(100000,10000000) ."_.".$ext11;
										
						
						$target_file 		= $target_dir .'/'. basename($image_file);
						
						$imageFileType  = pathinfo($target_file,PATHINFO_EXTENSION);
											
						$State1=true;
						// Check file size
						if ($_FILES["image_path"]["size"] > 4000000) {
								$error1= " Sorry, your file is too large. ";
								$State1=false;
						}

						
						// Allow certain file formats
						if(strtolower($imageFileType) != "jpg" && strtolower($imageFileType) != "png" && strtolower($imageFileType) != "jpeg" && strtolower($imageFileType) != "gif" && strtolower($imageFileType) != "bmp" && strtolower($imageFileType) != "pdf" ) {
							$error1= " Sorry, only JPG, JPEG, PNG & GIF & PDF files are allowed. ";
							$State1=false;
						}

						// Check if $uploadOk is set to 0 by an error
						if ($State1 == true) {
						
							if (move_uploaded_file($_FILES["image_path"]["tmp_name"], $target_file)){

								$image_path  = 'product_img/'.$last_inserted_id .'/'.$image_file;
								$State1=true;											  

							} else {
								$error1= " Sorry, there was an error uploading your file. ";
								$State1=false;
							}
						}
					}		
	                
	                $tmp 			='';
			        
			        $sql ="UPDATE  product SET image_path = '$image_path' WHERE product_id ='$last_inserted_id'";
								
					$query = $db->query($sql);
					if (!$query) {
						$msgg= "Image Not Uploaded";
						$State=false;

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



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

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