<?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 S.city_id_fk='.$_GET['id']:'';
			
			$cond2 = isset($_GET['zid'])? ' AND S.zone_id_fk="'.$_GET['zid'].'"':'';
			$cond3 = isset($_GET['tid'])? ' AND S.team_leader_id_fk="'.$_GET['tid'].'"':'';

			$cond = $cond1 . " " . $cond2 . " " . $cond3;
			$table  =  '(
				SELECT
					saleman_id,
					
					saleman_full_name,
					saleman_phone,
					saleman_phone2,
					saleman_address,
					saleman_job_title,
					S.profile_img,
					city_name,
					zone_name,
					team_leader_full_name,
					team_leader_id_fk,
					S.city_id_fk,
					zone_id_fk
					
					
				FROM
					saleman S
					LEFT JOIN city C ON (S.city_id_fk = C.city_id)
					LEFT JOIN zone Z ON (S.zone_id_fk = Z.zone_id)
					LEFT JOIN team_leader T ON (S.team_leader_id_fk = T.team_leader_id)
					
					
				WHERE
					( S.is_deleted = 0  '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'saleman_id';
			$columns = 	array(
						    array( 'db' => 'saleman_id', 'dt' => 0 ),
						    array( 'db' => 'saleman_full_name', 'dt' => 1 ),

						    array( 'db' => 'saleman_phone', 'dt' => 2 ),
						    array( 'db' => 'saleman_address', 'dt' => 3 ),
						    array( 'db' => 'saleman_job_title', 'dt' => 4 ),
						    array( 'db' => 'city_name', 'dt' => 5 ),
						    array( 'db' => 'zone_name', 'dt' => 6 ),
						    array( 'db' => 'team_leader_full_name', 'dt' => 7 ),
						    array( 'db' => 'profile_img', 'dt' => 8 ),
						    array( 'db' => 'saleman_phone2', 'dt' => 9 ),	
						    array( 'db' => 'city_id_fk', 'dt' => 10 ),	
						    array( 'db' => 'zone_id_fk', 'dt' => 11 ),	
						    array( 'db' => 'team_leader_id_fk', 'dt' => 12 ),	
				
				
			);
			// 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") {


			$res = $db->query("SELECT 	saleman_id,
										saleman_full_name,
										saleman_phone ,
										saleman_address,
										saleman_job_title,
										city_name,
										zone_name,
										team_leader_full_name

									FROM saleman S
									LEFT JOIN city C ON (S.city_id_fk = C.city_id)
									LEFT JOIN zone Z ON (S.zone_id_fk = Z.zone_id)
									LEFT JOIN team_leader T ON (S.team_leader_id_fk = T.team_leader_id)
					 
								WHERE S.is_deleted = 0 ");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result['saleman_id']  			= $row['saleman_id'];
						$result['saleman_full_name']  	= $row['saleman_full_name'];
						$result['saleman_phone']  		= $row['saleman_phone'];
						$result['saleman_address']  	= $row['saleman_address'];
						$result['saleman_job_title']  	= $row['saleman_job_title'];
						$result['city_name']  			= $row['city_name'];
						$result['zone_name']  			= $row['zone_name'];
						$result['team_leader_full_name']= $row['team_leader_full_name'];
						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 
									saleman_id,
				
									saleman_full_name,
									saleman_email,
									saleman_phone,
									saleman_phone2,
									saleman_address,
									saleman_job_title,
									team_leader_id_fk,
									city_id_fk,
									zone_id_fk
				 				FROM saleman S  WHERE S.is_deleted = 0 AND saleman_id = '$id'");
			if ($res) {
				
				
				while ($row = $res->fetch_assoc()) {
				   
						$result['saleman_id']  			= $row['saleman_id'];
						$result['saleman_full_name']  	= $row['saleman_full_name'];
						$result['saleman_email']  		= $row['saleman_email'];
						$result['saleman_phone']  		= $row['saleman_phone'];
						$result['saleman_phone2']  		= $row['saleman_phone2'];
						$result['saleman_address']  	= $row['saleman_address'];
						$result['saleman_job_title']  	= $row['saleman_job_title'];
						$result['team_leader_id_fk']  	= $row['team_leader_id_fk'];
						$result['city_id_fk']  			= $row['city_id_fk'];
						$result['zone_id_fk']  			= $row['zone_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_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 saleman SET 	profile_img = '',
	  												last_action='$lastaction',
	  												last_action_by='".$_SESSION['user_id']."' 
	  								WHERE saleman_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'];

			$saleman_full_name			=addslashes($_POST["edit_saleman_full_name"]);
			$saleman_email				=addslashes($_POST["edit_saleman_email"]);
			$saleman_phone				=addslashes($_POST["edit_saleman_phone"]);
			$saleman_phone2				=addslashes($_POST["edit_saleman_phone2"]);			
			$saleman_address			=addslashes($_POST["edit_saleman_address"]);
			$saleman_job_title			=addslashes($_POST["edit_saleman_job_title"]);
			$team_leader_id_fk			=addslashes($_POST["edit_team_leader_id_fk"]);
			$zone_id_fk					=addslashes($_POST["edit_zone_id_fk"]);
			$city_id_fk					=addslashes($_POST["edit_city_id_fk"]);
			

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

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

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

							


			$lastaction = "Update Saleman";
			$update_qry = "UPDATE saleman SET  
									saleman_full_name 	= '$saleman_full_name',
									saleman_email 		='$saleman_email',
									saleman_phone 		='$saleman_phone',
									saleman_phone2 		='$saleman_phone2',
									saleman_address 	='$saleman_address',
									saleman_job_title 	='$saleman_job_title',
									
									team_leader_id_fk 	='$team_leader_id_fk',
									zone_id_fk 			='$zone_id_fk',
									city_id_fk 			='$city_id_fk',
									updated_at			='$reg_date',
									last_action			='$lastaction',
									last_action_by		='".$_SESSION['user_id']."' 
							WHERE   saleman_id = $id";


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

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

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

				
				if($_FILES['edit_profile_img']['size'] > 0 ){
					
					$ext11  = pathinfo(basename($_FILES['edit_profile_img']['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_profile_img"]["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_profile_img"]["tmp_name"], $target_file)){

							$image_path  = 'profile_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 = "profile_img = '$image_path'";

		        }

		       
		        // echo $update_file;
		        if($update_file !=''){
		        	$sql ="UPDATE  saleman SET $update_file WHERE saleman_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 Saleman";

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

			$res = $db->query("SELECT * FROM report WHERE is_deleted=0 AND saleman_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 plan_saleman WHERE is_deleted=0 AND saleman_id_fk = '$id'");
			if (mysqli_num_rows($res)>0) {
				$op['is_success'] = false;
				$op['data'] 	  = "لا يمكن حذف هذه المادة فقد تم وضعها في احدى الخطط";
				echo json_encode($op);
				exit;
			}

			

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

      		$saleman_full_name			=addslashes($_POST["saleman_full_name"]);
			$saleman_email				=addslashes($_POST["saleman_email"]);
			$saleman_phone				=addslashes($_POST["saleman_phone"]);
			$saleman_phone2				=addslashes($_POST["saleman_phone2"]);			
			$saleman_address			=addslashes($_POST["saleman_address"]);
			$saleman_job_title			=addslashes($_POST["saleman_job_title"]);
			$team_leader_id_fk			=addslashes($_POST["team_leader_id_fk"]);
			$zone_id_fk					=addslashes($_POST["zone_id_fk"]);
			$city_id_fk					=addslashes($_POST["city_id_fk"]);
			
			
			

			$res = $db->query("SELECT * FROM saleman WHERE is_deleted=0 AND saleman_full_name = '$saleman_full_name' AND city_id_fk =$city_id_fk");
			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 Saleman";

			$sql ="INSERT INTO saleman (
										saleman_full_name,
										saleman_email,
										saleman_phone,
										saleman_phone2,
										saleman_address,
										saleman_job_title,
										team_leader_id_fk,
										zone_id_fk,
										city_id_fk,
										created_by,
										last_action,
										last_action_by,
										created_at,
										updated_at)
								VALUES( '$saleman_full_name',
										
										'$saleman_email',
										'$saleman_phone',
										'$saleman_phone2',
										'$saleman_address',
										'$saleman_job_title',
										'$team_leader_id_fk',
										'$zone_id_fk',
										'$city_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 = '../saleman_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['profile_img']['size'] > 0 ){
						
						$ext11  = pathinfo(basename($_FILES['profile_img']['name']),PATHINFO_EXTENSION);
						
						$image_file = $last_inserted_id."_".rand(100000,10000000) ."_.".$ext11;
										
						// $image_file = rand(10000000,1000000000) . "-" .$_FILES['attach_bill']['name'];
						
						$target_file 		= $target_dir .'/'. basename($image_file);
						
						$uploadOk = 1;
						$imageFileType  = pathinfo($target_file,PATHINFO_EXTENSION);
											
						$State1=true;
						// Check file size
						if ($_FILES["profile_img"]["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["profile_img"]["tmp_name"], $target_file)){

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

							} else {
									$error1= " Sorry, there was an error uploading your file. ";
									$State1=false;
							}
						}
					}		
	                
	                $tmp 			='';
			        
			        $sql ="UPDATE  saleman SET profile_img = '$image_path' WHERE saleman_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'] 	  = $msgg;
					echo json_encode($op);
					exit;
				}
				else{
					$op['is_success'] = false;
					$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
					echo json_encode($op);
					exit;
				}
			

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