<?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,
					S.sub_zone_id_fk,
					S.quarter_id_fk,
					S.street_id_fk,
					COALESCE(GROUP_CONCAT(DISTINCT C.city_name ORDER BY C.city_id),"") city_name,
					COALESCE(GROUP_CONCAT(DISTINCT Z.zone_name ORDER BY Z.zone_id),"")  zone_name,
					
					T.full_name as team_leader_full_name,
					TT.full_name as supervisor_name

				FROM
					 staff S

					LEFT JOIN city C ON FIND_IN_SET(C.city_id, S.city_id_fk )>0
					LEFT JOIN zone Z ON FIND_IN_SET(Z.zone_id, S.zone_id_fk) >0
					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 ) GROUP BY S.staff_id
			) 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' => 'login_count',   'dt' => 5 ),
								array( 'db' => 'is_view', 'dt' => 6),
								array( 'db' => 'is_deleted',   'dt' => 7 ),
								array( 'db' => 'city_name',   'dt' => 8 ),
								array( 'db' => 'zone_name',   'dt' => 9 ),
								array( 'db' => 'team_leader_full_name',   'dt' => 10 ),
								array( 'db' => 'supervisor_name',   'dt' => 11 ),
								array( 'db' => 'city_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_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']  			= explode(',', $row['city_id_fk']);
						$result['zone_id_fk']  			= explode(',', $row['zone_id_fk']);
						$result['sub_zone_id_fk']  		= explode(',', $row['sub_zone_id_fk']);
						$result['quarter_id_fk']  		= explode(',', $row['quarter_id_fk']);
						$result['street_id_fk']  		= explode(',', $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']=="get_user_sub_roles") {

			$id = $_POST['obj_id'];

			$res = $db->query("SELECT * FROM staff_sub_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_sub_role_id'];
						$result[1] = $row['staff_id_fk'];
						$result[2] = $row['role_id_fk'];
						$result[3] = $row['sub_role_id_fk'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				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 		=		$_POST["city_id_fk"];
	        @$zone_id_fk 		=		$_POST["zone_id_fk"];
	        @$sub_zone_id_fk 	=		$_POST["sub_zone_id_fk"];
	        @$quarter_id_fk 	=		$_POST["quarter_id_fk"];
	        @$street_id_fk 		=		$_POST["street_id_fk"];

	        @$city_id_fk 		= 		implode(',', $city_id_fk);
			@$zone_id_fk 		= 		implode(',', $zone_id_fk);
			@$sub_zone_id_fk 	= 		implode(',', $sub_zone_id_fk);
			@$quarter_id_fk 	= 		implode(',', $quarter_id_fk);
			@$street_id_fk 		= 		implode(',', $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',
												sub_zone_id_fk		='$sub_zone_id_fk',
												quarter_id_fk		='$quarter_id_fk',
												street_id_fk		='$street_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']=="change_user_sub_role") {

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

			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Update User Sub 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_sub_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_sub_role ( staff_id_fk, 
	     												role_id_fk, 
	     												sub_role_id_fk, 
	     												created_by,
	     												last_action, 
	     												last_action_by)
	     										VALUES( '$id',
	     												'3',
	     												'$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 		=		$_POST["city_id_fk"];
		        $zone_id_fk 		=		$_POST["zone_id_fk"];

		        $sub_zone_id_fk 	=		$_POST["sub_zone_id_fk"];
	        	$quarter_id_fk 		=		$_POST["quarter_id_fk"];
	        	$street_id_fk 		=		$_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";

				@$city_id_fk 		= 		implode(',', $city_id_fk);
				@$zone_id_fk 		= 		implode(',', $zone_id_fk);
				@$sub_zone_id_fk 	= 		implode(',', $sub_zone_id_fk);
				@$quarter_id_fk 	= 		implode(',', $quarter_id_fk);
				@$street_id_fk 		= 		implode(',', $street_id_fk);

				$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,
											supervisor_id_fk,
											team_leader_id_fk,
											city_id_fk,
											zone_id_fk,
											sub_zone_id_fk,
											quarter_id_fk,
											street_id_fk,
											created_by,
											last_action,
											last_action_by)
									VALUES( '$username',
											'$password',
											'$full_name',
											'$email',
											'$phone_number',
											'$supervisor_id_fk',
											'$team_leader_id_fk',
											'$city_id_fk',
											'$zone_id_fk',
											'$sub_zone_id_fk',
											'$quarter_id_fk',
											'$street_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;
	}


		



?>
