<?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
					model_id,
					
					model_name,
					model_code,
					model_type,
					model_sell_price,
					model_note,
					image_path,
					model_color,
					is_disabled
					
					
					
					
				FROM
					model M
					
				WHERE
					( M.is_deleted = 0 AND M.model_id > 1 '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'model_id';
			$columns = array(
			    array( 'db' => 'model_id', 'dt' => 0 ),
			    array( 'db' => 'model_name', 'dt' => 1 ),

			    array( 'db' => 'model_code', 'dt' => 2 ),
			    array( 'db' => 'model_type', 'dt' => 3 ),
			    array( 'db' => 'model_sell_price', 'dt' => 4 ),
			    array( 'db' => 'model_note', 'dt' => 5 ),
			    array( 'db' => 'image_path', 'dt' => 6 ),
			    array( 'db' => 'is_disabled', 'dt' => 7 ),
			    array( 'db' => 'model_color', 'dt' => 8 ),
			    
				
			);
			// 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 model_id,model_name,model_code,model_type, model_sell_price, model_note  FROM model M WHERE M.is_deleted = 0 AND is_disabled = 0");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['model_id'];
						$result[1]  = $row['model_name'];
						$result[2]  = $row['model_code'];
						$result[3]  = $row['model_type'];
						$result[4]  = $row['model_sell_price'];
						$result[5]  = $row['model_note'];
						
						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
									model_id,
									
									model_name,
									model_code,
									model_type,
									model_sell_price,
									model_note,
									model_color
										

									FROM
										model M
										
									WHERE
										( M.is_deleted = 0 AND M.model_id = '.$id.') 

								');
			if ($res) {
				
				
				while ($row = $res->fetch_assoc()) {
				   
						$result['model_id']  				= $row['model_id'];
						$result['model_name']  				= $row['model_name'];
						$result['model_code']  				= $row['model_code'];
						$result['model_note']  				= $row['model_note'];
						$result['model_type']  				= $row['model_type'];
						$result['model_sell_price']  		= $row['model_sell_price'];
						$result['model_color']  			= $row['model_color'];
						
						
						
						array_push($op['data'],$result);
				}
				$op['is_success'] = true;
				echo json_encode($op);
				exit;
			}else{
				$op['is_success'] = false;
				$op['data'] 	  = $db->error;
				echo json_encode($op);

				exit;
			}
		}



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

			
			$cond = "";
			

			$res = $db->query('

								SELECT
										model_id,
										
										model_name,
										model_code,
										model_note
										

									FROM
										model M
										
									WHERE
										( M.is_deleted = 0 '.$cond.') 

								');
			if ($res) {
				
				$op  = array('invoice'=>array(),'details'=>array());
				while ($row = $res->fetch_assoc()) {
				   
					$result['model_id']  				= $row['model_id'];
					$result['model_name']  				= $row['model_name'];
					$result['model_code']  				= $row['model_code'];
					$result['model_note']  				= $row['model_note'];
					
					
					
					array_push($op['invoice'],$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 model SET image_path = '',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE model_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'] == "update") {

			$id 					= $_POST['edit_objid'];
			$model_name				=addslashes($_POST["edit_model_name"]);
			$model_code				=addslashes($_POST["edit_model_code"]);
			$model_note				=addslashes($_POST["edit_model_note"]);
			$model_type				=addslashes($_POST["edit_model_type"]);
			$model_sell_price		=addslashes($_POST["edit_model_sell_price"]);
			$model_color			=addslashes($_POST["edit_model_color"]);


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

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

			// $res = $db->query("SELECT * FROM model WHERE is_deleted=0 AND model_name = '$model_name' AND model_id != '$id'");
			// if (mysqli_num_rows($res)>0) {
			// 		$op['is_success'] = false;
			// 		$op['data'] 	  = "خطأ اسم Model مكرر";
			// 		echo json_encode($op);
			// 		exit;
			// }

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


			// we should check maybe change the type of model

			$res = $db->query("SELECT * FROM model WHERE  model_id = '$id'");
			
			$row = $res->fetch_assoc();

			$model_type_old = $row['model_type'];

			if($model_type != $model_type_old){ // now we should check invoice if nothing were sold ok we can change

				$res = $db->query("SELECT * FROM sell_item WHERE is_deleted=0 AND model_id_fk = '$id'");
			
				if (mysqli_num_rows($res)>0) {
						$op['is_success'] = false;
						$op['data'] 	  = "خطأ لا يمكنك تغيير نوع الموديل لان هناك مبيعات وطلبات مرتبطه به وستغير حالة الحسابات";
						echo json_encode($op);
						exit;
				}

			}

	


			$lastaction = "Update Model";
			$update_qry = "UPDATE model SET  
									model_name = '$model_name',
									model_code='$model_code',
									model_note='$model_note',
									model_type='$model_type',
									model_sell_price='$model_sell_price',
									model_color  = '$model_color',
									updated_at='$reg_date',
									last_action='$lastaction',
									last_action_by='".$_SESSION['user_id']."' 
									WHERE model_id = $id";


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


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

					$image_path		='';
	                $manual_path 	='';
	                $State 			=true;
	                $State1			=true;
	                $error 			= '';			
	                $error1			= '';
	                $msgg			= "تمت عملية التحديث بنجاح";

					
					if($_FILES['edit_image_path']['size'] > 0 ){
										
						$image_file = rand(10000000,1000000000) . "-" .$_FILES['edit_image_path']['name'];
						
						$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($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
							$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  = 'model_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  model SET $update_file WHERE model_id ='$id'";
								
						$query = $db->query($sql);
			        }
			        

					$op['is_success'] 	= $State;
					$op['data'] 	 	= $msgg;
					$op['image'] 	  	= $error;
					echo json_encode($op);
					exit;

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


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

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

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

			
			

			

	  		$res = $db->query("UPDATE model SET is_disabled = 1 ,
	  											deleted_at = '$reg_date',
	  											updated_at='$reg_date',
	  											last_action='$lastaction',
	  											last_action_by='".$_SESSION['user_id']."' 
	  											WHERE model_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']=="enable_items") {

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

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

			
			

			

	  		$res = $db->query("UPDATE model SET is_disabled = 0 ,
	  											deleted_at = '$reg_date',
	  											updated_at='$reg_date',
	  											last_action='$lastaction',
	  											last_action_by='".$_SESSION['user_id']."' 
	  											WHERE model_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']=="delete") {

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

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

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

			

			

	  		$res = $db->query("UPDATE model SET is_deleted = 1 ,
	  											deleted_at = '$reg_date',
	  											updated_at='$reg_date',
	  											last_action='$lastaction',
	  											last_action_by='".$_SESSION['user_id']."' 
	  											WHERE model_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") {

      		$model_name				=addslashes($_POST["model_name"]);
			$model_code				=addslashes($_POST["model_code"]);
			$model_note				=addslashes($_POST["model_note"]);
			$model_type				=addslashes($_POST["model_type"]);
			$model_sell_price		=addslashes($_POST["model_sell_price"]);
			$model_color			=addslashes($_POST["model_color"]);
			
					

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

			// $res = $db->query("SELECT * FROM model WHERE is_deleted=0 AND model_code = '$model_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 Model";

			$sql ="INSERT INTO model (
										model_name,
										model_code,
										model_note,
										model_type,
										model_sell_price,
										model_color,
										image_path,
										created_by,
										last_action,
										last_action_by,
										created_at,
										updated_at)
								VALUES( '$model_name',
										'$model_code',
										'$model_note',
										'$model_type',
										'$model_sell_price',
										'$model_color',
										'',
										'".$_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 = '../model_img/'.$last_inserted_id;
					if(! file_exists($target_dir)){
						mkdir($target_dir);
					}
					

					$count 			=0;

					$image_path		='';
	                $manual_path 	='';
	                $State 			=true;
	                $State1			=true;
	                $error 			= '';			
	                $error1			= '';


					
					if($_FILES['image_path']['size'] > 0 ){
										
						$image_file = rand(10000000,1000000000) . "-" .$_FILES['image_path']['name'];
						
						$target_file 		= $target_dir .'/'. basename($image_file);
						
						$uploadOk = 1;
						$imageFileType  = pathinfo($target_file,PATHINFO_EXTENSION);
											
						$State1=true;
						// Check file size
						if ($_FILES["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" ) {
							$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  = 'model_img/'.$last_inserted_id .'/'.$image_file;
								$State1=true;											  

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

					}else{
						$msgg= 'تمت عملية الاضافة بنجاح';
						$State=true;
					}		   


					$op['is_success'] = true;
					$op['data'] 	  = $msgg;
					$op['image'] 	  = $error;
					echo json_encode($op);
					exit;


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

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