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



date_default_timezone_set($_SESSION['SYSTimezone']);

		$Validator = array('is_success'=>false, 'data'=>array());
		// date_default_timezone_set('Asia/Baghdad');
		$LogTime = date('Y-m-d H:i:s');

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

		if( isset($_GET['type']) && ($_GET['type'] == "load")){
			// DB table to use
			$table = 'staff';

			$table  =  '(
				SELECT
					S.staff_id,
					
					S.username,
					S.full_name,
					S.email,
					S.phone_number,
					S.profile_type,
					S.is_view,
					S.login_count,
					S.created_at,
					S.is_deleted,
					S.team_leader_id_fk,
					S.city_id_fk,
					S.zone_id_fk,
					city_name,
					zone_name,
					sub_zone_name,
					quarter_name,
					street_name,
					T.full_name as team_leader_full_name,
					TT.full_name as supervisor_name

				FROM
					 staff 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 sub_zone SZ ON (S.sub_zone_id_fk = SZ.sub_zone_id)
					LEFT JOIN quarter Q ON (S.quarter_id_fk = Q.quarter_id)
					LEFT JOIN street ST ON (S.street_id_fk = ST.street_id)
					LEFT JOIN staff T ON (S.team_leader_id_fk = T.staff_id)
					LEFT JOIN staff TT ON (S.supervisor_id_fk = TT.staff_id)
					
					
				WHERE
					( S.is_deleted < 2 AND S.profile_type=2) 
			) AS ALLTBL';
			// Table's primary key
			$primaryKey = 'staff_id';
			$columns =  array(
				  				array( 'db' => 'staff_id', 'dt' => 0 ),
			    				array( 'db' => 'username', 'dt' => 1 ),
			    				array( 'db' => 'full_name',  'dt' => 2 ),
								array( 'db' => 'phone_number',   'dt' => 3 ),
								array( 'db' => 'profile_type',   'dt' => 4 ),
								array( 'db' => 'street_name',   'dt' => 5 ),
								array( 'db' => 'quarter_name', 'dt' => 6),
								array( 'db' => 'sub_zone_name', 'dt' => 7),
								array( 'db' => 'zone_name', 'dt' => 8),
								array( 'db' => 'city_name',   'dt' => 9 ),
								// array( 'db' => 'team_leader_full_name',   'dt' => 8 ),
								array( 'db' => 'supervisor_name',   'dt' => 10 ),
								
								array( 'db' => 'is_deleted',   'dt' => 11 ),
			);
			// 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_edit") {

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

			$res = $db->query("SELECT 
										S.staff_id,
										
										S.username,
										S.full_name,
										S.email,
										S.phone_number,
										S.profile_type,
										S.is_view,
										S.login_count,
										S.created_at,
										S.is_deleted,
										S.team_leader_id_fk,
										S.supervisor_id_fk,
										S.city_id_fk,
										S.zone_id_fk,
										S.sub_zone_id_fk,
										S.quarter_id_fk,
										S.street_id_fk
										

									FROM
										 staff S
				 					WHERE S.is_deleted = 0 AND S.staff_id = '$id'");
			if ($res) {
				
				
				while ($row = $res->fetch_assoc()) {
				   
						$result['staff_id']  			= $row['staff_id'];
						$result['username']  			= $row['username'];
						$result['full_name']  			= $row['full_name'];
						$result['email']  				= $row['email'];
						$result['phone_number']  		= $row['phone_number'];
						$result['profile_type']  		= $row['profile_type'];
						$result['supervisor_id_fk']  	= $row['supervisor_id_fk'];
						$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'];
						$result['sub_zone_id_fk']  		= $row['sub_zone_id_fk'];
						$result['quarter_id_fk']  		= $row['quarter_id_fk'];
						$result['street_id_fk']  		= $row['street_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_saleman") {


			$res = $db->query("SELECT 	staff_id,
										username,
										full_name ,
										phone_number,
										profile_type,
										city_name,
										zone_name

									FROM staff 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)
					 
								WHERE S.is_deleted = 0 AND S.profile_type=1");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
					$result['staff_id']  			= $row['staff_id'];
					$result['username']  	= $row['username'];
					$result['full_name']  		= $row['full_name'];
					$result['phone_number']  	= $row['phone_number'];
					$result['profile_type']  	= $row['profile_type'];
					$result['city_name']  			= $row['city_name'];
					$result['zone_name']  			= $row['zone_name'];
					array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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


			$res = $db->query("SELECT 	staff_id,
										username,
										full_name ,
										phone_number,
										profile_type,
										city_name,
										zone_name

									FROM staff 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)
					 
								WHERE S.is_deleted = 0 AND S.profile_type=2");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
					$result['staff_id']  	= $row['staff_id'];
					$result['username']  	= $row['username'];
					$result['full_name']  	= $row['full_name'];
					$result['phone_number'] = $row['phone_number'];
					$result['profile_type'] = $row['profile_type'];
					$result['city_name']  	= $row['city_name'];
					$result['zone_name']  	= $row['zone_name'];
					array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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


			$res = $db->query("SELECT 	staff_id,
										username,
										full_name ,
										phone_number,
										profile_type,
										city_name,
										zone_name

									FROM staff 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)
					 
								WHERE S.is_deleted = 0 AND S.profile_type=3");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
					$result['staff_id']  	= $row['staff_id'];
					$result['username']  	= $row['username'];
					$result['full_name']  	= $row['full_name'];
					$result['phone_number'] = $row['phone_number'];
					$result['profile_type'] = $row['profile_type'];
					$result['city_name']  	= $row['city_name'];
					$result['zone_name']  	= $row['zone_name'];
					array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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

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

			$res = $db->query("SELECT * FROM role WHERE is_deleted = 0 AND action =''");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['role_id'];
						$result[1] = $row['role'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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

			$id = $_POST['obj_id'];

			$res = $db->query("SELECT * FROM staff_role WHERE is_deleted = 0 AND staff_id_fk =$id");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['staff_role_id'];
						$result[1] = $row['staff_id_fk'];
						$result[2] = $row['role_id_fk'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 'Not';
				exit;
			}
		}

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

			$id 				= $_POST['obj_id'];
			$username			=addslashes($_POST["username"]);
			$full_name			=addslashes($_POST["full_name"]);
			$email				=addslashes($_POST["email"]);
			$phone_number		=addslashes($_POST["phone_number"]);



	        $city_id_fk 		=		addslashes($_POST["city_id_fk"]);
	        $zone_id_fk 		=		addslashes($_POST["zone_id_fk"]);
	        $sub_zone_id_fk 	=		addslashes($_POST["sub_zone_id_fk"]);
	        $quarter_id_fk 		=		addslashes($_POST["quarter_id_fk"]);
	        $street_id_fk 		=		addslashes($_POST["street_id_fk"]);
	        $team_leader_id_fk 	=		addslashes($_POST["team_leader_id_fk"]);
	        $supervisor_id_fk 	=		addslashes($_POST["supervisor_id_fk"]);
	        


			$res = $db->query("SELECT * FROM staff WHERE is_deleted=0 AND username = '$username' AND staff_id != '$id'");
			if (mysqli_num_rows($res)>0) {
						$error= "User Name is Taken";
						$State=false;
						$Validator['is_success'] = $State;
						$Validator['data'] = $error;
						echo json_encode($Validator);
						exit;
			}

			$res = $db->query("SELECT * FROM staff WHERE is_deleted=0 AND phone_number = '$phone_number' AND staff_id != '$id'");
			if (mysqli_num_rows($res)>0) {
						$error= "Phone Number is Taken";
						$State=false;
						$Validator['is_success'] = $State;
						$Validator['data'] = $error;
						echo json_encode($Validator);
						exit();
			}
				
			$res = $db->query("SELECT * FROM staff WHERE is_deleted=0 AND email = '$email' AND staff_id != '$id'");
			if (mysqli_num_rows($res)>0) {
						$error= "E-mail is Taken";
						$State=false;
						$Validator['is_success'] = $State;
						$Validator['data'] = $error;
						echo json_encode($Validator);
						exit();
			}		

			$lastaction = "Update User information";

			$res = $db->query("UPDATE staff SET username 		= '$username' ,
												full_name 		= '$full_name',
												email			='$email',
												phone_number	='$phone_number',
												supervisor_id_fk	='$supervisor_id_fk',
												team_leader_id_fk	='$team_leader_id_fk',
												city_id_fk	='$city_id_fk',
												zone_id_fk	='$zone_id_fk',
												street_id_fk 		='$street_id_fk',
												quarter_id_fk 		='$quarter_id_fk',
												sub_zone_id_fk 		='$sub_zone_id_fk',
												last_action		='$lastaction',
												last_action_by	='".$_SESSION['user_id']."' 
										WHERE staff_id=$id");

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


		if ($_POST['type']=="delete") {
			$id=addslashes($_POST["obj_id"]);
			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Delete User";

			if($_SESSION['profile_type'] != 5 && $_SESSION['profile_type'] != 4){
				$Validator['is_success'] = false;
				$Validator['data'] = "You Are Not Allowed To perform this Action";
				echo json_encode($Validator);
				exit;
			}

			$res = $db->query("SELECT * FROM staff WHERE is_deleted=0 AND staff_id = '$id'");
			
			$row = $res->fetch_assoc(); 
			
			if ($row['profile_type']==5) {

				// check if there is another super admain ok delete it else dont delete it

				$res1 = $db->query("SELECT * FROM staff WHERE is_deleted=0 AND profile_type = 5 AND staff_id != '$id'");

				if (mysqli_num_rows($res1)==0) {
						$error= "Super Admin Can Not be Deleted! it Should be at least one Super Admin";
						
						$Validator['is_success'] = false;
						$Validator['data'] = $error;
						echo json_encode($Validator);
						exit;
				}
			}

						
				


			

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



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

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

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

			if($_SESSION['profile_type'] != 5 && $_SESSION['profile_type'] != 4){
				$Validator['is_success'] = false;
				$Validator['data'] = "You Are Not Allowed To perform this Action";
				echo json_encode($Validator);
				exit;
			}

			$db->autocommit(FALSE);

      		$res = $db->query("UPDATE staff_role SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE staff_id_fk=$id");
	     	if ($res){

	     		$check_all_inserted = false;

	     		for($i=0; $i<count($roles);$i++){
	     				
	     				$sql ="INSERT INTO staff_role ( staff_id_fk, 
	     												role_id_fk, 
	     												created_by,
	     												last_action, 
	     												last_action_by)
	     										VALUES( '$id',
	     												'$roles[$i]',
	     												'".$_SESSION['user_id']."',
	     												'$lastaction',
	     												'".$_SESSION['user_id']."')";

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

							if ($res) {
								$check_all_inserted = true;
							}else{
								$check_all_inserted = false;
								$db->rollback();
								$error= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
								$State=false;
								$Validator['is_success'] = $State;
								$Validator['data'] = $error;
								echo json_encode($Validator);
								exit;
							}
	     		} // for i

	     		if($check_all_inserted == true){
								$db->commit();
								$error= 'Successfully Update User Roles';
								$State=true;
								$Validator['is_success'] = $State;
								$Validator['data'] = $error;
								echo json_encode($Validator);
								exit;
					}else{
								$db->rollback();
								$error= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
								$State=false;
								$Validator['is_success'] = $State;
								$Validator['data'] = $error;
								echo json_encode($Validator);
								exit;
					}
	     		
	     	}else{
	      						$db->rollback();
								$error= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
								$State=false;
								$Validator['is_success'] = $State;
								$Validator['data'] = $error;
								echo json_encode($Validator);
								exit;
	     	}
		}



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

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

			if($_SESSION['profile_type'] != 5 && $_SESSION['profile_type'] != 4){
				$Validator['is_success'] = false;
				$Validator['data'] = "You Are Not Allowed To perform this Action";
				echo json_encode($Validator);
				exit;
			}

			$res = $db->query("SELECT * FROM staff WHERE is_deleted=0 AND staff_id = '$id'");
			
			$row = $res->fetch_assoc(); 
			
			if ($row['profile_type']==5) {

				// check if there is another super admain ok delete it else dont delete it

				$res1 = $db->query("SELECT * FROM staff WHERE is_deleted=0 AND profile_type = 5 AND staff_id != '$id'");

				if (mysqli_num_rows($res1)==0) {
						$error= "Super Admin Can Not be Deleted! it Should be at least one Super Admin";
						
						$Validator['is_success'] = false;
						$Validator['data'] = $error;
						echo json_encode($Validator);
						exit;
				}
			}

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




		if ($_POST['type']=="active") {
			$id=addslashes($_POST["obj_id"]);
			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Activated User";

			if($_SESSION['profile_type'] != 5 && $_SESSION['profile_type'] != 4){
				$Validator['is_success'] = false;
				$Validator['data'] = "You Are Not Allowed To perform this Action";
				echo json_encode($Validator);
				exit;
			}

	      	$res = $db->query("UPDATE staff SET is_deleted = 0 ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE staff_id=$id");
	     	if ($res){
	     		$Validator['is_success'] = true;
				$Validator['data'] = "User has been Activated.";
				echo json_encode($Validator);
				exit;
	     	}
	      	else{
	      		$Validator['is_success'] = false;
				$Validator['data'] = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
				echo json_encode($Validator);
				exit;
	     	}
		}



		if ($_POST['type']=="change_profile_type") {
			
			$id 					= addslashes($_POST["obj_id"]);
			$profile_type 			= addslashes($_POST["profile_type"]);
			$is_view 				= addslashes($_POST["is_view"]);
			
			$reg_date 				= date("Y-m-d h:i:s", time());
			$lastaction 			= "Change User Profile Type";

			if($_SESSION['profile_type'] == 5){

					$res = $db->query("UPDATE staff SET profile_type = '$profile_type' ,
										is_view = '$is_view' ,
										last_action='$lastaction',
										last_action_by='".$_SESSION['user_id']."' 
										WHERE staff_id=$id");
		     	if ($res){
		     			$error= "Profile Type Successfully Changed";
						$State=true;
						$Validator['is_success'] = $State;
						$Validator['data'] = $error;
						echo json_encode($Validator);
						exit();
		     	}
		      else{
		      			$error= "Some thing Went Wrong";
						$State=false;
						$Validator['is_success'] = $State;
						$Validator['data'] = $error;
						echo json_encode($Validator);
						exit();
		     	}

			}else{

					$error= "You Are Not Allowed To perform this Action";
					$State=false;
					$Validator['is_success'] = $State;
					$Validator['data'] = $error;
					echo json_encode($Validator);
					exit();

			}

      
		}

		if ($_POST['type']=="change_password") {
			$id 			=		addslashes($_POST["obj_id"]);
			$password 		=		addslashes($_POST["password"]);
      		$repassword 	=		addslashes($_POST["repassword"]);

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

			if($_SESSION['profile_type'] != 5 && $_SESSION['profile_type'] != 4){
				$Validator['is_success'] = false;
				$Validator['data'] = "You Are Not Allowed To perform this Action";
				echo json_encode($Validator);
				exit;
			}

			if($repassword != $password){
					$error= "Passwords does not match";
					$State=false;
					$Validator['is_success'] = $State;
					$Validator['data'] = $error;
					echo json_encode($Validator);
					exit();
			}

				$password=hash('sha256',$password);
				$password= stripslashes($password);
				$password=mysqli_real_escape_string($db,$password);


		      $res = $db->query("UPDATE staff SET password = '$password' ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE staff_id=$id");
		     	if ($res){
		     				$error= "Passwords Successfully Changed";
							$State=true;
							$Validator['is_success'] = $State;
							$Validator['data'] = $error;
							echo json_encode($Validator);
							exit();
		     	}
		      else{
		      				$error= "Some Thing Went Wrong";
							$State=false;
							$Validator['is_success'] = $State;
							$Validator['data'] = $error;
							echo json_encode($Validator);
							exit();
		     	}
		}

		if ($_POST['type'] == "create") {
		        $username			=		addslashes($_POST["username"]);
		        $full_name			=		addslashes($_POST["full_name"]);
		        $email				=		addslashes($_POST["email"]);
		        $password 			=		addslashes($_POST["password"]);
		        $repassword 		=		addslashes($_POST["repassword"]);
		        $city_id_fk 		=		addslashes($_POST["city_id_fk"]);
		        $zone_id_fk 		=		addslashes($_POST["zone_id_fk"]);

		        $sub_zone_id_fk 	=		addslashes($_POST["sub_zone_id_fk"]);
	        	$quarter_id_fk 		=		addslashes($_POST["quarter_id_fk"]);
	        	$street_id_fk 		=		addslashes($_POST["street_id_fk"]);

		        $team_leader_id_fk 	=		addslashes($_POST["team_leader_id_fk"]);
		        $supervisor_id_fk 	=		addslashes($_POST["supervisor_id_fk"]);
		        
		        $phone_number		=		addslashes($_POST["phone_number"]);
		        $role_id 			=		addslashes($_POST["role_id"]);
		        $reg_date 			= 		date("Y-m-d H:i:s", time());
				$lastaction 		= 		"Create New Staff";

				$res = $db->query("SELECT * FROM staff WHERE is_deleted=0 AND username = '$username'");
				if (mysqli_num_rows($res)>0) {
							$error= "User Name is Taken";
							$State=false;
							$Validator['is_success'] = $State;
							$Validator['data'] = $error;
							echo json_encode($Validator);
							exit;
				}

				$res = $db->query("SELECT * FROM staff WHERE is_deleted=0 AND phone_number = '$phone_number'");
				if (mysqli_num_rows($res)>0) {
							$error= "Phone Number is Taken";
							$State=false;
							$Validator['is_success'] = $State;
							$Validator['data'] = $error;
							echo json_encode($Validator);
							exit();
				}
				
				$res = $db->query("SELECT * FROM staff WHERE is_deleted=0 AND email = '$email'");
				if (mysqli_num_rows($res)>0) {
							$error= "E-mail is Taken";
							$State=false;
							$Validator['is_success'] = $State;
							$Validator['data'] = $error;
							echo json_encode($Validator);
							exit();
				}			
							
				if($repassword != $password){
					$error= "Passwords does not match";
					$State=false;
					$Validator['is_success'] = $State;
					$Validator['data'] = $error;
					echo json_encode($Validator);
					exit();
				}

				$password=hash('sha256',$password);
				$password= stripslashes($password);
				$password=mysqli_real_escape_string($db,$password);


				$sql ="INSERT INTO staff(	username,
											password,
											full_name,
											email,
											phone_number,
											profile_type,
											supervisor_id_fk,
											team_leader_id_fk,
											city_id_fk,
											zone_id_fk,
											street_id_fk,
											quarter_id_fk,
											sub_zone_id_fk,
											created_by,
											last_action,
											last_action_by)
									VALUES( '$username',
											'$password',
											'$full_name',
											'$email',
											'$phone_number',
											'2',
											'$supervisor_id_fk',
											'$team_leader_id_fk',
											'$city_id_fk',
											'$zone_id_fk',
											'$street_id_fk',
											'$quarter_id_fk',
											'$sub_zone_id_fk',
											'".$_SESSION['user_id']."',
											'$lastaction',
											'".$_SESSION['user_id']."')";
				$res = $db->query($sql);
					if ($res) {
						$error= "Successfully Added New User";
						$State=true;
						$Validator['is_success'] = $State;
						$Validator['data'] = $error;
						echo json_encode($Validator);
						exit();
					}
					else{
						$error= "Some Thing Went Wrong";
						$State=false;
						$Validator['is_success'] = $State;
						$Validator['data'] = $error;
						echo json_encode($Validator);
						exit();
					}
				

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


		

		//require_once "db_connect.php";

		if(isset($_GET['type']) AND $_GET['type']=='load'){
						$sql = "SELECT * FROM staff WHERE staff_id = '" . $_SESSION['user_id'] ."'  AND is_deleted=0 ";

						$query = $connect->query($sql);

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

						}else{
									$Records = $query->fetch_assoc();


									$LogTime = date('Y-m-d H:i:s');


									// $Records = mysqli_fetch_array($Rows);

									if($Records){
										$_SESSION['user_id'] 				= $Records['staff_id'];
										$_SESSION['user_role'] 			= $Records['role_id_fk'];
										$_SESSION['username'] 			= $Records['username'];
										$_SESSION['full_name'] 			= $Records['full_name'];
										$_SESSION['email'] 					= $Records['email'];
										$_SESSION['profile_image'] 	= $Records['profile_img'];
										$_SESSION['cover_image'] 		= $Records['cover_img'];
										$_SESSION['phone_number'] 	= $Records['phone_number'];
										$_SESSION['updated_at'] 		= $Records['updated_at'];
										$_SESSION['image_path'] 		= 'image/profile/';

										$error= " Retrieve Successfully";
										$State= true;

									}
									else{
												$error= " User Name or Password Invalid ";
												$State=false;
									} // if records

						}

						$Validator['success'] = $State;
						$Validator['data'] = $error;
						echo json_encode($Validator);
						exit();
		}

		if($_POST['type']=='update_profile_image'){
					$LogTime = date('Y-m-d H:i:s');
					$target_dir = "../image/profile/";
					$fileBook = rand(1000,100000) . "-" . $_FILES['profile_image']['name'];
					$target_file = $target_dir . basename($fileBook);
					$uploadOk = 1;
					$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
					// Check if image file is a actual image or fake image

					$check = getimagesize($_FILES["profile_image"]["tmp_name"]);
					if($check == false) {
							$error= " File is not an image. ";
							$State=false;
					}else {
						$State=true;
					}


					// Check file size
					if ($_FILES["profile_image"]["size"] > 1500000) {
							$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 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 {

							if (move_uploaded_file($_FILES["profile_image"]["tmp_name"], $target_file)) {

								$sql = "UPDATE staff SET last_action='Update Profile Image', updated_at='$LogTime',profile_img='$fileBook'   WHERE staff_id = '".$_SESSION['user_id']."'";

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

								}else{
										$error= " Profile Picture Successfully updated ";
										$State=true;
								}

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

					$Validator['success'] = $State;
					$Validator['data'] = $error;

		}



		if($_POST['type']=='update_profile_cover_image'){
					$LogTime = date('Y-m-d H:i:s');
					$target_dir = "../image/profile/";
					$fileBook = rand(1000,100000) . "-" . $_FILES['cover_image']['name'];
					$target_file = $target_dir . basename($fileBook);
					$uploadOk = 1;
					$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
					// Check if image file is a actual image or fake image

					$check = getimagesize($_FILES["cover_image"]["tmp_name"]);
					if($check == false) {
							$error= " File is not an image. ";
							$State=false;
					}else {
						$State=true;
					}


					// Check file size
					if ($_FILES["cover_image"]["size"] > 1500000) {
							$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 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 {

							if (move_uploaded_file($_FILES["cover_image"]["tmp_name"], $target_file)) {

								$sql = "UPDATE staff SET last_action='Update Profile Image', updated_at='$LogTime',cover_img='$fileBook'   WHERE staff_id = '".$_SESSION['user_id']."'";

								$query = $connect->query($sql);
								if (!$query) {
											$error= "Some Thing Went Wrong";
											$State=false;

								}else{
										$error= " Cover Picture Successfully updated ";
										$State=true;
								}

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

					$Validator['success'] = $State;
					$Validator['data'] = $error;

		}

		if($_POST['type']=='update_profile'){

			$LastLoging 	= $LogTime;
			$full_name 		= $_POST['full_name'];
			$phone_number = $_POST['phone_number'];
			$email 				= $_POST['email'];

			$sql = "UPDATE staff SET last_action='Update Profile', updated_at='$LastLoging',full_name='$full_name' ,phone_number='$phone_number',email='$email'  WHERE staff_id = '".$_SESSION['user_id']."'";

			$query = $connect->query($sql);
			if (!$query) {
						$error= "Some Thing Went Wrong";
						$State=false;

			}else{
						$error= "Successfully Update Your Profile";
						$State=true;
			}
			$Validator['success'] = $State;
			$Validator['data'] = $error;
		}

		if($_POST['type']=='update_password'){
			$LastLoging = $LogTime;
			$password 	= $_POST['password'];
			$repassword = $_POST['repassword'];

			if($repassword == $password){
				$password=hash('sha256',$password);
				$password= stripslashes($password);
				$password=mysqli_real_escape_string($connect,$password);

				$sql = "UPDATE staff SET last_action='Update Profile', updated_at='$LastLoging',password='$password' WHERE staff_id = '".$_SESSION['user_id']."'";

				$query = $connect->query($sql);
				if (!$query) {
							$error= "Some Thing Went Wrong";
							$State=false;

				}else{
							$error= "Successfully Update Your Password";
							$State=true;
				}

			}else{
				$error= "Passwords does not match";
				$State=false;
			}


			$Validator['success'] = $State;
			$Validator['data'] = $error;
		}

		//echo json_encode($Validator);



?>
