<?php
/*
* date last modified 28-11-2017
* Edited by PI-Digi Logical Solutions
* HTML Files - add_user.html.php
* Mysql Tables - tbl_designation, tbl_user
*/
include('includes/imgFunctions.php');
include('includes/functions.php'); # general functions
include('includes/push_functions.php'); # general functions


$debug = false;
$isEdit = FALSE;

//get cities
$citiesRs = mysqli_query($con, "SELECT id, name FROM tbl_city ORDER BY name");


if(isset($_REQUEST['id']) && $_REQUEST['id']!=''){
	
	$isEdit = TRUE;
	$editId = mysqli_real_escape_string($con, trim($_REQUEST['id']));
	
	//delete image
	/*if(isset($_REQUEST['action']) && $_REQUEST['action']='del_image'){
		$recImg = mysqli_fetch_array(mysqli_query($con, "SELECT image FROM tbl_user WHERE id = '".$editId."'"));
		if(($recImg['image']!='') && file_exists(STAFF_IMG_FOLDER.$recImg['image'])){
			unlink(STAFF_IMG_FOLDER.$recImg['image']);
			unlink(STAFF_IMG_FOLDER.'thumb/'.$recImg['image']);
		}
		$update = mysqli_query($con, "UPDATE tbl_user SET image = '' WHERE id = '".$editId."'");
		$success = 'User image has been deleted';
	}*/	
	
	$editRs = mysqli_query($con, "SELECT * FROM tbl_user WHERE id = '".$editId."'");
	if(mysqli_num_rows($editRs)>0){
		$resEdit = mysqli_fetch_array($editRs);
	} else {
		$error = 'User does not exist!';
	}

} 

if(isset($_POST['add'])) {
	
	if(strlen(trim($_POST['city'])) > 0) {
		$city = trim($_POST['city']);
	} else {
		$city = '';
	}
	
	if(strlen(trim($_POST['pin'])) > 0) {
		$pin = trim($_POST['pin']);		
	} else {
		$error = 'Please enter PIN Code';
	}
	
	if(strlen(trim($_POST['longitude'])) > 0) {
		$longitude = trim($_POST['longitude']);		
	} else {
		$longitude = '';			
	}
	
	if(strlen(trim($_POST['latitude'])) > 0) {
		$latitude = trim($_POST['latitude']);		
	} else {
		$latitude = '';			
	}
	
	if(strlen(trim($_POST['place'])) > 0) {
		$place = trim($_POST['place']);		
		$placeArr = explode(',', $place);
		$place = $placeArr[0];
	} else {
		$error = 'Please enter Place';
	}
	
	if(strlen(trim($_POST['street'])) > 0) {
		$street = trim($_POST['street']);
	} else {
		$street = '';
	}
	
	if(strlen(trim($_POST['house_name'])) > 0) {
		$house_name = trim($_POST['house_name']);
	} else {
		$error = 'Please enter House Name';
	}	
			
	if(strlen(trim($_POST['phone'])) > 0) {
		$phone = trim($_POST['phone']);
		if(is_numeric($phone) && strlen($phone)>9 && strlen($phone)<15){
			// check 
			$checkPhone = mysqli_query($con,"SELECT id FROM tbl_user WHERE phone='".mysqli_real_escape_string($con,$phone)."' AND status != 'Deleted'");
			if(isset($checkPhone) && mysqli_num_rows($checkPhone)>0) {
				$error = 'A user with the same phone number exists';
			}
		} else {
			$error = 'Please enter phone number only digits with coutry code';
		}
	} else {
		$error = 'Please enter Phone Number';
	}

	if(strlen(trim($_POST['re_password'])) > 0) {
		$re_password = trim($_POST['re_password']);
		if(strlen(trim($_POST['password'])) > 0) {
			$password = trim($_POST['password']);
			if($password == $re_password){
				//ok
			} else {
				$error = 'Password mis-match error!';
			}
		}
	} else {
		$error = 'Please re-enter Password';
	}

	if(strlen(trim($_POST['password'])) > 0) {
		$password = trim($_POST['password']);
		if(strlen($password)>5){
			//ok
		} else {
			$error = 'Password should contain atleast 6 characters';
		}
	} else {
		$error = 'Please enter Password';
	}
	
	if(isset($_POST['email']) && strlen(trim($_POST['email'])) > 0) {
		$email = trim($_POST['email']);
		if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
			$error =  "E-mail is not valid";
		} else {
			// check Email
			$checkEmail = mysqli_query($con,"SELECT id FROM tbl_user WHERE email='".mysqli_real_escape_string($con,$email)."'  AND status != 'Deleted'");
			if(isset($checkEmail) && mysqli_num_rows($checkEmail)>0) {
				$error = 'Email Already Taken';
			}
		}
	} else {
		$error = 'Please enter Email';
	}
	
	if(isset($_POST['name']) && strlen($_POST['name'])>0) {
		$name = trim($_POST['name']);
	} else {
		$error = 'Please Enter User Name';
	}	
	
	
	
	if(empty($error)) {
		
		
		$mapPlace = $_POST['place'];		
		$latLong = getLatLong($mapPlace);
		//print_r($latLong);
		//exit;
		if($latitude!='' && $longitude!=''){
			//take the values
		} else if(is_array($latLong) && $latLong['latitude']!='' && $latLong['longitude']!=''){
			//ok
			$latitude = $latLong['latitude'];
			$longitude = $latLong['longitude'];
		} else {
			$error = 'Unable to find lat-long from the location - '.$mapPlace.'. Try again';
		}
		
		$randVal = generateRandom(6);
		
		if(empty($error)) {						
			/* Adding New User Details */		
			$insertQry = "INSERT INTO tbl_user(name, email, password, phone, house_name, street, place, pin, city, latitude, longitude, added_from, ref_val, date, status) VALUES (
			'".mysqli_real_escape_string($con, $name)."',
			 '".mysqli_real_escape_string($con, $email)."',
			 '".mysqli_real_escape_string($con, $password)."',
			 '".mysqli_real_escape_string($con, $phone)."',	
			 '".mysqli_real_escape_string($con, $house_name)."',
			 '".mysqli_real_escape_string($con, $street)."',
			 '".mysqli_real_escape_string($con, $place)."',
			 '".mysqli_real_escape_string($con, $pin)."',
			 '".mysqli_real_escape_string($con, $city)."',
			 '".mysqli_real_escape_string($con, $latitude)."',
			 '".mysqli_real_escape_string($con, $longitude)."',
			 'admin',
			 '".mysqli_real_escape_string($con, $randVal)."',					 
			 NOW(),
			 'Active')";
			
			$execInsert = mysqli_query($con,$insertQry);
			$insert_id = mysqli_insert_id($con);		
			
			if($execInsert) {						
				$success = 'User Added Successfully';
				header('Location:index.php?page=manage_user&success='.$success);
				exit();			
			} else {
				$error = 'Unable to add user';
			}		
		}		
	} 
}

if(isset($_POST['update'])) {
		
	if(strlen(trim($_POST['additional_numbers'])) > 0) {
		$additional_numbers = trim($_POST['additional_numbers']);
	} else {
		$additional_numbers = '';
	}	
		
	if(strlen(trim($_POST['city'])) > 0) {
		$city = trim($_POST['city']);
	} else {
		$city = '';
	}
	
	if(strlen(trim($_POST['pin'])) > 0) {
		$pin = trim($_POST['pin']);		
	} else {
		$error = 'Please enter PIN Code';
	}
	
	if(strlen(trim($_POST['longitude'])) > 0) {
		$longitude = trim($_POST['longitude']);		
	} else {
		$longitude = '';			
	}
	
	if(strlen(trim($_POST['latitude'])) > 0) {
		$latitude = trim($_POST['latitude']);		
	} else {
		$latitude = '';			
	}
	
	if(strlen(trim($_POST['place'])) > 0) {
		$place = trim($_POST['place']);	
		$placeArr = explode(',', $place);
		$place = $placeArr[0];	
	} else {
		$error = 'Please enter Place';
	}
	
	if(strlen(trim($_POST['street'])) > 0) {
		$street = trim($_POST['street']);
	} else {
		$street = '';
	}
	
	if(strlen(trim($_POST['house_name'])) > 0) {
		$house_name = trim($_POST['house_name']);
	} else {
		$error = 'Please enter House Name';
	}	
				
	if(strlen(trim($_POST['phone'])) > 0) {
		$phone = trim($_POST['phone']);
		if(is_numeric($phone) && strlen($phone)>9 && strlen($phone)<15){
			// check 
			$checkPhone = mysqli_query($con,"SELECT id FROM tbl_user WHERE phone='".mysqli_real_escape_string($con,$phone)."' AND status != 'Deleted' AND id != '".$editId."'");
			if(isset($checkPhone) && mysqli_num_rows($checkPhone)>0) {
				$error = 'A user with the same phone number exists';
			}
		} else {
			$error = 'Please enter phone number only digits with coutry code';
		}
	} else {
		$error = 'Please enter Phone Number';
	}

	/*if(strlen(trim($_POST['re_password'])) > 0) {
		$re_password = trim($_POST['re_password']);
		if(strlen(trim($_POST['password'])) > 0) {
			$password = trim($_POST['password']);
			if($password == $re_password){
				//ok
			} else {
				$error = 'Password mis-match error!';
			}
		}
	} else {
		$error = 'Please re-enter Password';
	}

	if(strlen(trim($_POST['password'])) > 0) {
		$password = trim($_POST['password']);
	} else {
		$error = 'Please enter Password';
	}*/
	
	if(isset($_POST['email']) && strlen(trim($_POST['email'])) > 0) {
		$email = trim($_POST['email']);
		if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
			$error =  "E-mail is not valid";
		} else {
			// check Email
			$checkEmail = mysqli_query($con,"SELECT id FROM tbl_user WHERE email='".mysqli_real_escape_string($con,$email)."' AND id != '".$editId."' AND status != 'Deleted'");
			if(isset($checkEmail) && mysqli_num_rows($checkEmail)>0) {
				$error = 'Email Already Taken';
			}
		}
	} else {
		$error = 'Please enter Email';
	}
	
	if(isset($_POST['name']) && strlen($_POST['name'])>0) {
		$name = trim($_POST['name']);
	} else {
		$error = 'Please enter Name of User';
	}
		
	if(empty($error)) {
		
		$mapPlace = $_POST['place'];		
		$latLong = getLatLong($mapPlace);
		//print_r($latLong);
		//exit;
		if($latitude!='' && $longitude!=''){
			//take the values
		} else if(is_array($latLong) && $latLong['latitude']!='' && $latLong['longitude']!=''){
			//ok
			$latitude = $latLong['latitude'];
			$longitude = $latLong['longitude'];
		} else {
			$error = 'Unable to find lat-long from the location - '.$mapPlace.'. Try again';
		}		
		
		if(empty($error)){
			
			$updateQry = "UPDATE tbl_user SET name = '".$name."', email = '".$email."', phone = '".$phone."', house_name = '".$house_name."', street = '".$street."', place = '".$place."', latitude = '".$latitude."', longitude = '".$longitude."', pin = '".$pin."', city = '".$city."', additional_numbers = '".$additional_numbers."' WHERE id = '".$editId."'";
			
			$execUpdate = mysqli_query($con,$updateQry);			
			
			if($execUpdate) {
				
				/*$exec_token = mysqli_query($con, 'SELECT fcm_token, device FROM tbl_fcm_tokens WHERE user_id='.$editId);
				if(isset($exec_token) && mysqli_num_rows($exec_token)>0) {
					while($res_token = mysqli_fetch_array($exec_token)) {	
						if($res_token['fcm_token']!='') {							
							$title = "LiiMR";
							$body = "Hi ".getUserName($editId).", your profile details have been updated";
							if($res_token['device']=='android') {
								sendGCM_user($title, $body, $res_token['fcm_token']);
							} else {
								sendIosUserPush($title, $body, $res_token['fcm_token']);
							}							
						}
					}
				}*/
				
				$success = 'User Updated Successfully';
				header('Location:index.php?page=view_user&id='.$editId.'&success='.$success);
				exit();			
			} else {
				$error = 'Unable to update user';
			}		
		}			
	} 
}

?>