<?php
/*
* date last modified 03-10-2017
* Edited by PI-Digi Logical Solutions
* HTML Files - manage_staff.html.php
* Mysql Tables - tbl_admin, tbl_purchase_partner, tbl_admin_type
*/
require_once('./classes/class.noseo_pagination.php'); # pagination class
require_once('./includes/functions.php'); # general functions

$debug = true;
$showExtraTechs = FALSE;

if(isset($_REQUEST['p']) && $_REQUEST['p']!=''){
	$p = trim($_REQUEST['p']);
} else {
	$p = 1;
}

$pageVars = '';

function distance($lat1, $lon1, $lat2, $lon2, $unit) {
  $theta = $lon1 - $lon2;
  $lat1 = floatval($lat1);
  $lat2 = floatval($lat2);
  $lon1 = floatval($lon1);
  $lon2 = floatval($lon2);
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

function cmp($a, $b) {
			    if ($a == $b) {
			        return 0;
			    }
			    return ($a < $b) ? -1 : 1;
}

function getTechEnabledSlots($con, $techId, $date){
	//get task day and get enabled slots
	$taskDay = '';
	$days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday','Friday', 'Saturday');
	$taskWeekDay = date('w', strtotime($date));
	if(isset($days[$taskWeekDay]) && $days[$taskWeekDay]!=''){
		$taskDay = strtolower($days[$taskWeekDay]);
	}
	$hourArray = array();	 
	$hourRs = mysqli_query($con, "SELECT HOUR(start_time) AS start_hour FROM tbl_technician_availability WHERE technician_id = '".$techId."' AND day = '".$taskDay."' AND status = 'on'");
	if(mysqli_num_rows($hourRs)>0){
		while($hourRec = mysqli_fetch_array($hourRs)){			
			$hoursArray[] = $hourRec['start_hour'];			
		}
	} 
	return $hoursArray;
}


function getTechBusySlots($con, $techId, $date){
	$slotsArray = array();
	//echo "SELECT task_date, task_time, HOUR(admin_slot) AS admin_slot, HOUR(admin_slot_to) AS admin_slot_to FROM tbl_job WHERE technician_id = '".$techId."' AND task_date = '".$date."' AND status NOT IN ('New','cancelled')"; 
	$taskRs = mysqli_query($con, "SELECT task_date, task_time, HOUR(admin_slot) AS admin_slot, HOUR(admin_slot_to) AS admin_slot_to FROM tbl_job WHERE technician_id = '".$techId."' AND task_date = '".$date."' AND status NOT IN ('New','cancelled','paid','user_paid','completed')");
	if(mysqli_num_rows($taskRs)>0){
		while($taskRec = mysqli_fetch_array($taskRs)){
			$taskTime = $taskRec['task_time'];
			$adminSlot = $taskRec['admin_slot'];
			$adminSlotTo = $taskRec['admin_slot_to'];			
			//if($adminSlotTo!='00'){
				$taskHr = $adminSlot;
			/*} else {
				$taskTimeArr = explode(':', $taskTime);
				$taskHr = $taskTimeArr[0];				
			}*/	
			//echo $taskHr;
			$slotsArray[] = $taskHr;			
		}
	} 
	return $slotsArray;
}


if(isset($_POST['submit'])){
	print_r($_POST);
}




//we have to find tech near to user
if(isset($_REQUEST['task_id']) && $_REQUEST['task_id']!='') {
	$taskId = trim($_REQUEST['task_id']);
	$where = $techIdString = '';
	$techArray = array();
	//we have to select technicians near to this user
	$taskRec = mysqli_fetch_array(mysqli_query($con, "SELECT technician_id, user_id, category_id, address_id, latitude, longitude, fixed_rate, task_date, task_time FROM tbl_job WHERE id = '".$taskId."'"));
	$assignedTechId = $taskRec['technician_id'];
	$userId = $taskRec['user_id'];
	$catId = $taskRec['category_id'];
	$addressId = $taskRec['address_id'];
	$userLat = $taskRec['latitude'];
	$userLong = $taskRec['longitude'];
	$taskDate = $taskRec['task_date'];
	$taskTime = $taskRec['task_time'];

	$startHourArr = explode(':', $taskTime);
	$startHour = $startHourArr[0];
	if($startHour == '00'){
		$startHour = 0;
	} else if($startHour%2 == 0){
		
	} else {
		$startHour=$startHour-1;	
	}

	//check if old date. if so get today as task date
	if(strtotime($taskDate) < strtotime(date('Y-m-d'))){
		$taskDate = date('Y-m-d');
		$taskTime = date('H:i:s');
	} else if(strtotime($taskDate) == strtotime(date('Y-m-d'))){
		//check if past time
		$taskDateTime = $taskDate.' '.$taskTime;
		if(strtotime($taskDateTime) < strtotime(date('Y-m-d H:i:s'))){
			$taskDate = date('Y-m-d');
			$taskTime = date('H:i:s');
			$taskTimeArr1 = explode(':', $taskTime);
			if($startHour<$taskTimeArr1[0]){
				$startHour=$taskTimeArr1[0];
				if($startHour%2 == 0){
					//ok
				} else {
					$startHour=$startHour+1;	
				}
			}
		}
	}

	//get task day and check if tech available on the day
	$taskDay = '';
	$days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday','Friday', 'Saturday');
	$taskWeekDay = date('w', strtotime($taskDate));
	if(isset($days[$taskWeekDay]) && $days[$taskWeekDay]!=''){
		$taskDay = strtolower($days[$taskWeekDay]);
	}
	
	//get unavailability param - if yes, also show technicians who has off status
	if(isset($_REQUEST['unavailable']) && $_REQUEST['unavailable']=='yes'){
		$availabilityWhere = " ";
	} else {
		$availabilityWhere = " AND tbl_technician.availability = 'on' ";
	}
		
	
	//get technicians with this category	
	if(isset($_REQUEST['extra']) && $_REQUEST['extra']=='yes'){
		//check if any tech added as extra. if so remove them		
		if($taskDay!=''){
			$techRs = mysqli_query($con, "SELECT technician_id FROM `tbl_technician_category`, tbl_technician WHERE tbl_technician.`status` = 'Active' ".$availabilityWhere." AND tbl_technician.id IN(SELECT DISTINCT `technician_id` FROM `tbl_technician_availability` WHERE `day` = '".$taskDay."' AND HOUR(end_time) > '".$startHour."' AND `status` = 'on') AND tbl_technician.id = tbl_technician_category.technician_id AND 
		tbl_technician_category.`category_id` = '".$catId."' AND tbl_technician_category.verified = 'yes' AND technician_id NOT IN (SELECT technician_id FROM tbl_job_extra_tech WHERE job_id = '".$taskId."') LIMIT 30");		
		} else {
			$techRs = mysqli_query($con, "SELECT technician_id FROM `tbl_technician_category`, tbl_technician WHERE tbl_technician.`status` = 'Active' ".$availabilityWhere." AND tbl_technician.id IN(SELECT DISTINCT `technician_id` FROM `tbl_technician_availability` WHERE `day` = '".$taskDay."' AND HOUR(end_time) > '".$startHour."' AND `status` = 'on') AND tbl_technician.id = tbl_technician_category.technician_id AND 
		tbl_technician_category.`category_id` = '".$catId."' AND tbl_technician_category.verified = 'yes' AND technician_id NOT IN (SELECT technician_id FROM tbl_job_extra_tech WHERE job_id = '".$taskId."') LIMIT 30");		
		}
	} else {		
		if($taskDay!=''){
			/*echo("SELECT technician_id FROM `tbl_technician_category`, tbl_technician WHERE tbl_technician.`status` = 'Active' ".$availabilityWhere." AND tbl_technician.id IN(SELECT DISTINCT `technician_id` FROM `tbl_technician_availability` WHERE `day` = '".$taskDay."' AND HOUR(end_time) > '".$startHour."' AND `status` = 'on') AND (tbl_technician.id = tbl_technician_category.technician_id) AND 
			tbl_technician_category.`category_id` = '".$catId."' AND tbl_technician_category.verified = 'yes' LIMIT 30");*/
			
			$techRs = mysqli_query($con, "SELECT technician_id FROM `tbl_technician_category`, tbl_technician WHERE tbl_technician.`status` = 'Active' ".$availabilityWhere." AND tbl_technician.id IN(SELECT DISTINCT `technician_id` FROM `tbl_technician_availability` WHERE `day` = '".$taskDay."' AND HOUR(end_time) > '".$startHour."' AND `status` = 'on') AND (tbl_technician.id = tbl_technician_category.technician_id) AND 
			tbl_technician_category.`category_id` = '".$catId."' AND tbl_technician_category.verified = 'yes' LIMIT 30");						
		} else {
			$techRs = mysqli_query($con, "SELECT technician_id FROM `tbl_technician_category`, tbl_technician WHERE tbl_technician.`status` = 'Active' ".$availabilityWhere." AND tbl_technician.id IN(SELECT DISTINCT `technician_id` FROM `tbl_technician_availability` WHERE `day` = '".$taskDay."' AND `status` = 'on') AND tbl_technician.id IN(SELECT DISTINCT `technician_id` FROM `tbl_technician_availability` WHERE `day` = '".$taskDay."' 
			AND `status` = 'on') AND (tbl_technician.id = tbl_technician_category.technician_id) AND tbl_technician_category.`category_id` = '".$catId."' AND tbl_technician_category.verified = 'yes' LIMIT 30");			
		}
	}	
	if(mysqli_num_rows($techRs)>0){
		while($techRec = mysqli_fetch_array($techRs)){
			$techArray[] = $techRec['technician_id'];
		}
	}
	
	$techArray = array_unique($techArray);
	
	//check if adding extra technician to the task. if so remove the assigned technicin from the list
	if(isset($_REQUEST['extra'])){		
		if (($key = array_search($assignedTechId, $techArray)) !== false) {
		    unset($techArray[$key]);
		}	
		
		if($taskRec['fixed_rate']>0){
			//check if any extra tech already added 
			$chkAddedExtraRs = mysqli_query($con, "SELECT id FROM tbl_job_extra_tech WHERE job_id = '".$taskId."'");
			if(mysqli_num_rows($chkAddedExtraRs)>0){
				$showExtraTechs = TRUE;
			}
		}	
	}	
	
	//print_r($techArray);
	if(count($techArray)>0){
		$techArray2 = $techArray;
		$techIdString = implode(',', $techArray);
		//echo 'User loc: '.$userLat.','.$userLong;
		$curDateTime = date('Y-m-d H:i:s');
		//SELECT latitude, longitude FROM `tbl_update_location` WHERE `technician_id` IN(84,87) AND time >= DATE_SUB('2018-09-14 12:28:10',INTERVAL 1 HOUR)
		if($userLat!='' && $userLong!=''){
			
			//if($_SERVER['REMOTE_ADDR']=='202.88.237.77'){
			$techDistArray = array();
			foreach ($techArray2 as $techIdVal) {
				//check if tech's last updated location entry in last 1 hour
				$lastLocRs = mysqli_query($con, "SELECT latitude, longitude FROM `tbl_update_location` WHERE `technician_id` = '".$techIdVal."' AND time >= DATE_SUB('".$curDateTime."',INTERVAL 1 HOUR)");		
				if(mysqli_num_rows($lastLocRs)>0){
					$lastLocRec = mysqli_fetch_array($lastLocRs);
					//$techDistArray[$techIdVal]['latitude'] = $lastLocRec['latitude'];
					//$techDistArray[$techIdVal]['longitude'] = $lastLocRec['longitude'];
					//find distance from task location
					$distanceToLoc = distance($userLat, $userLong, $lastLocRec['latitude'], $lastLocRec['longitude'], "K");
					$distanceToLoc = round($distanceToLoc,2);
					if(is_nan($distanceToLoc)){ //this can be because of same location for tech and task
						$distanceToLoc = 0;
					}
					$techDistArray[$techIdVal] = $distanceToLoc;					
				} else {
					//get location from tech availability
					//echo "SELECT latitude, longitude FROM `tbl_technician_location` WHERE `technician_id` = '".$techIdVal."' ORDER BY id DESC LIMIT 1";
					$availLocRs = mysqli_query($con, "SELECT latitude, longitude FROM `tbl_technician_location` WHERE `technician_id` = '".$techIdVal."' ORDER BY id DESC LIMIT 1");		
					if(mysqli_num_rows($availLocRs)>0){
						$availLocRec = mysqli_fetch_array($availLocRs);
						//$techDistArray[$techIdVal]['latitude'] = $availLocRec['latitude'];
						//$techDistArray[$techIdVal]['longitude'] = $availLocRec['longitude'];
						$distanceToLoc = distance($userLat, $userLong, $availLocRec['latitude'], $availLocRec['longitude'], "K");
						$distanceToLoc = round($distanceToLoc,2);
						if(is_nan($distanceToLoc)){ //this can be because of same location for tech and task
							$distanceToLoc = 0;
						}
						$techDistArray[$techIdVal] = $distanceToLoc;
					}
					
				}			
			}
			//sort($techDistArray);			
			uasort($techDistArray, 'cmp');
			//print_r($techDistArray);
			/*if($_SERVER['REMOTE_ADDR']=='202.88.237.77'){
				print_r($techDistArray);
			}*/
		} 
		
		
	} else {
		$error = 'No technicians found';
	}
	
} else {
	$error = 'Something went wrong';
}


?>