<?php
ini_set('display_errors', 'On');
error_reporting(E_ERROR);
include 'set_factors.php';
include 'send_gcm.php';
include 'update_timestamp.php';
include 'insert_into_sync_table.php';

/*App uses log_data_v2. This is used by website*/
/*The following code will add/upd/del data in LOG_TABLE. Insert data into SYNC_TABLE. And notify partner phones*/

// array for JSON response (default to failure)
$response = array();
$response["success"] = 0;
$response["message"] = "Failed";

// check for required fields
if (isset($_POST['email']) && isset($_POST['type']) && isset($_POST['source'])) {	
	
	// include db config class
	require_once __DIR__ . '/db_config.php';
	
	// connecting to db
    $mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
    mysqli_set_charset($mysqli, "utf8");
    	
    //get email and android id and source
	$email = $_POST['email'];
	$androidId = $_POST['androidId'];
	$source = $_POST['source'];
	
	//check that android id is not in sync table
	if($stmt = $mysqli->prepare("SELECT * FROM SYNC_TABLE WHERE ANDROID_ID = ?")){
		$stmt->bind_param("s", $androidId);
		$stmt->execute(); 
		$stmt->store_result();
    		$num_rows = $stmt->num_rows;
    		
    		//proceed only if android id does not exist
    		if($num_rows == 0){
    			$type = $_POST['type'];
			$id = $_POST['_id'];
			$vid = $_POST['vehid'];
			$date = $_POST['date'];
			$odo = $_POST['odo'];
			$qty = $_POST['qty'];
			$pfill = $_POST['pfill'];
			$mfill = $_POST['mfill'];
			$cost =	$_POST['cost'];
			$dist =	$_POST['dist'];
			$cons =	$_POST['cons'];
			$octane = $_POST['octane'];
			$fuelBrand = $_POST['fuelBrand'];
			$fillStation = $_POST['fillStation'];
			$notes = $_POST['notes'];
			$day = $_POST['day'];
			$month = $_POST['month'];
			$year =	$_POST['year'];
			$receipt = $_POST['receipt'];
			$rec_type = $_POST['rec_type'];
			$serviceType = $_POST['serviceType'];	

			//get user id
			if($stmt = $mysqli->prepare("SELECT USER_ID FROM USER_ID WHERE EMAIL = ?")){			
				$stmt->bind_param("s", $email);	
				$stmt->execute();
				$stmt->bind_result($temp_user_id);
				while($stmt->fetch()){
		    			$user_id = $temp_user_id;
		    		}
		    		
		    		//check if image has arrived
				if(!empty($receipt)){
					//change receipt to only name and append email id
					$receipt = str_replace(" ", "_", $receipt);					
					
					//append email if it does not contain it already
					if(strpos($receipt, $email) !== false){										
						$receipt = basename($receipt);
					}
					//else append email
					else{
						$receipt = $email . "." . basename($receipt);
					}

					//set save path of file and change append email id to image name
					$file_path = "../FBReceiptsTemp/";
					$file_path = $file_path . $receipt; 
					
					move_uploaded_file($_FILES['img_file']['tmp_name'], $file_path);
				}
		    		
		    		//add data into table
		    		if(strcmp($type, "add") == 0){
		    			//get max id in case of data being entered from the web
		    			if(strcmp($source, "web") == 0){
		    				$id = getMaxID($mysqli, $user_id);
		    			}
		    			
		    			if($stmt = $mysqli->prepare("INSERT INTO LOG_TABLE(USER_ID, _ID, VEHID, DATE, ODO, QTY, PARTIAL_FILL, MISSED_FILL, COST, DIST, CONSUMPTION, OCTANE, FUEL_BRAND, FILLING_STATION, NOTES, DAY, MONTH, YEAR, RECEIPT, TYPE, SERVICE_TYPE) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")){	
		    				$stmt->bind_param("iisiddiiddddsssiiisis", $user_id, $id, $vid, $date, $odo, $qty, $pfill, $mfill, $cost, $dist, $cons, $octane, $fuelBrand, $fillStation, $notes, $day, $month, $year, $receipt, $rec_type, $serviceType);
		    				$result = $stmt->execute(); 		    				
	
		    				// successfully inserted into database
		    				if ($result) {
		    					//update sync table		    		
		    					if(insertIntoSyncTable($mysqli, $id, $type, $user_id, "LOG_TABLE", $androidId)){
		    						//get other reg ids of the same email
		    						$reg_id = getOtherRegIds($mysqli, $user_id, $androidId);		    						
		    						
		    						//send message to other phones belonging to same email
		    						sendGCMMessage($reg_id, "pull");
		    					}
		    					
		    					//if data is not for last record or it is from the web, then update dist and eff
		    					if(strcmp($source, "web")==0 || $odo != getMaxOdo($mysqli, $user_id, $vid)){
		    						//update dist
		    						updateDist($mysqli, $user_id, $vid);
		    						
		    						//update eff
		    						updateEff($mysqli, $user_id, $vid);		    								    						
		    					}
		    					//else data is from the phone and the last record, check if penultimate record is PF
		    					else if(checkPreviousRecIfPF($mysqli, $user_id, $vid)){
		    						//if yes, then update eff the long way
		    						updateEff($mysqli, $user_id, $vid);
		    					}
		    					
		    					//for services and expenses, we need to update reminders (SERVICES_TABLE)
		    					if($rec_type==1 || $rec_type==2){
		    						updateReminders($mysqli, $user_id, $vid, $serviceType);
		    					}
		    					
		    					//update timestamp in Profile
		    					updateTimestamp($user_id);
		    					
		    					$response["success"] = 1;
							$response["message"] = "Success";
				
							// echoing JSON response
							echo json_encode($response);
		    				}
		    				//if failure due to unique constraint then move on
						else if($mysqli->errno===1062){
							$response["success"] = 1;
							$response["message"] = "Success";
				
							// echoing JSON response
							echo json_encode($response);
						}										    			    					    	
		    			}			    		
		    		}
		    		//update log rec		    		
				else if(strcmp($type, "edit") == 0){
					//get pic for receipt deletion before updating
					if($stmt = $mysqli->prepare("SELECT RECEIPT FROM LOG_TABLE WHERE USER_ID=? and _ID=?")){
						$stmt->bind_param("ii", $user_id, $id);
						$stmt->execute();
						$stmt->bind_result($temp_old_receipt);
						while($stmt->fetch()){
							$old_receipt = $temp_old_receipt;
						}
					}
					
					//if update is from web, and receipt is empty, that means user has not updated the pic
					//becuase pic cannot be deleted from the web, and if no new pic is attached then web send empty receipt
					if(strcmp($source, "web")==0 && empty($receipt)){
						$receipt = $old_receipt;
					}				
					
					if($stmt = $mysqli->prepare("UPDATE LOG_TABLE SET VEHID=?, DATE=?, ODO=?, QTY=?, PARTIAL_FILL=?, MISSED_FILL=?, COST=?, DIST=?, CONSUMPTION=?, OCTANE=?, FUEL_BRAND=?, FILLING_STATION=?, NOTES=?, DAY=?, MONTH=?, YEAR=?, RECEIPT=?, TYPE=?, SERVICE_TYPE=? WHERE USER_ID=? and _ID=?")){
						$stmt->bind_param("siddiiddddsssiiisisii", $vid, $date, $odo, $qty, $pfill, $mfill, $cost, $dist, $cons, $octane, $fuelBrand, $fillStation, $notes, $day, $month, $year, $receipt, $rec_type, $serviceType, $user_id, $id);
						$result = $stmt->execute();
						
						// rec has been updated succesfully
		    				if($result){
		    					//if old pic is not empty and is different from new, then delete the old pic from folder
							if(isset($old_pic) && !empty($old_pic) && strcmp($old_pic, $receipt)!=0){
								$file_path = "../FBReceiptsTemp/";
								$file_path = $file_path . $old_pic;
								unlink($file_path);
							}
					
		    					//update sync table		    		
		    					if(insertIntoSyncTable($mysqli, $id, $type, $user_id, "LOG_TABLE", $androidId)){
		    						//get other reg ids of the same email
		    						$reg_id = getOtherRegIds($mysqli, $user_id, $androidId);	    						
		    						
		    						//send message to other phones belonging to same email
		    						sendGCMMessage($reg_id, "pull");
		    					}	    
		    					
		    					//if data is not for last record or from the web, then update dist and eff
		    					if(strcmp($source, "web")==0 || $odo != getMaxOdo($mysqli, $user_id, $vid)){
		    						//update dist
		    						updateDist($mysqli, $user_id, $vid);
		    						
		    						//update eff
		    						updateEff($mysqli, $user_id, $vid);		    						
		    					}	
		    					//else data is from the phone and the last record, check if penultimate record is PF
		    					else if(checkPreviousRecIfPF($mysqli, $user_id, $vid)){
		    						//if yes, then update eff the long way
		    						updateEff($mysqli, $user_id, $vid);
		    					}	
		    					
		    					//for services and expenses, we need to update reminders (SERVICES_TABLE)
		    					if($rec_type==1 || $rec_type==2){
		    						updateReminders($mysqli, $user_id, $vid, $serviceType);
		    					}
		    					
		    					//update timestamp in Profile
		    					updateTimestamp($user_id);
		    						    					
		    					$response["success"] = 1;
							$response["message"] = "Success";
				
							// echoing JSON response
							echo json_encode($response);
		    				}			
					}
				}
				//delete log rec
				else if(strcmp($type, "del") == 0){			
					$pic = "";
				
					//get veh id for updateDist and updateEff , pic for receipt deletion, type & service_type for reminder update before deleting
					if($stmt = $mysqli->prepare("SELECT VEHID, RECEIPT, TYPE, SERVICE_TYPE FROM LOG_TABLE WHERE USER_ID=? and _ID=?")){
						$stmt->bind_param("ii", $user_id, $id);
						$stmt->execute();
						$stmt->bind_result($temp_vid, $temp_pic, $temp_rec_type, $temp_service_type);
						while($stmt->fetch()){
							$vid = $temp_vid;
							$pic = $temp_pic;
							$rec_type = $temp_rec_type;
							$serviceType = $temp_service_type;
						}
					
						//delete record
						$stmt = $mysqli->prepare("DELETE FROM LOG_TABLE WHERE USER_ID=? and _ID=?");
						$stmt->bind_param("ii", $user_id, $id);
						$result = $stmt->execute();

						// rec has been deleted succesfully
		    				if($result){
		    					//if image exists, delete it from the folder
		    					if(!empty($pic)){
		    						$file_path = "../FBReceiptsTemp/";
								$file_path = $file_path . $pic;
								unlink($file_path); 
		    					}
		    					
		    					//update sync table		    		
		    					if(insertIntoSyncTable($mysqli, $id, $type, $user_id, "LOG_TABLE", $androidId)){
		    						//get other reg ids of the same email
		    						$reg_id = getOtherRegIds($mysqli, $user_id, $androidId);		    						
		    						
		    						//send message to other phones belonging to same email
		    						sendGCMMessage($reg_id, "pull");
		    					}
		    							    				
		    					//update dist
		    					updateDist($mysqli, $user_id, $vid);
		    						
		    					//update eff
		    					updateEff($mysqli, $user_id, $vid);	
		    					
		    					//for services and expenses, we need to update reminders (SERVICES_TABLE)
		    					if($rec_type==1 || $rec_type==2){
		    						updateReminders($mysqli, $user_id, $vid, $serviceType);
		    					}	
		    					
		    					//update timestamp in Profile
		    					updateTimestamp($user_id);    					
		    							    		
		    					$response["success"] = 1;
							$response["message"] = "Success";
				
							// echoing JSON response
							echo json_encode($response);
		    				}	
		    			}				
				}
			}	
    		}
    		//else user's android id exists in the Sync table, inform him that data on his phone is out of sync				 			
		else{		
			//get reg_id
			if($stmt = $mysqli->prepare("SELECT REG_ID FROM PROFILE WHERE ANDROID_ID=?")){
				$stmt->bind_param("s", $androidId);	
				$stmt->execute();
				$stmt->bind_result($temp_reg_id);
				while($stmt->fetch()){
					$reg_id[] = $temp_reg_id;
				}
				
				//send message to user
				sendGCMMessage($reg_id, "out of sync");
			}
		}
		
		// Close the prepared statement.
    		if($stmt != null){
			$stmt->close(); 
	    	} 
	}
	
	//else send generic failure message
	if($response["success"] == 0){
		$response["success"] = 0;
		$response["message"] = "Failed";
								 
		// echoing JSON response
		echo json_encode($response);
	}
	
	mysqli_close($mysqli);
}
else{
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing JSON response
    echo json_encode($response);
}

//function to get other reg ids
function getOtherRegIds($mysqli, $userID, $androidIDToIgnore){
	$sql = "";

	//if android id to ignore is null (called from web) then return all android_ids for that user id
	if(empty($androidIDToIgnore)){
		$sql = 	"SELECT REG_ID FROM PROFILE WHERE USER_ID = ?";
	}
	//else get android IDs for the same email id except the one from which this request has come
	else{
		$sql = "SELECT REG_ID FROM PROFILE WHERE USER_ID = ? AND ANDROID_ID!=?";
	}

	if($stmt = $mysqli->prepare($sql)){
		if(empty($androidIDToIgnore)){
			$stmt->bind_param("i", $userID);	
		}
		else{
			$stmt->bind_param("is", $userID, $androidIDToIgnore);	
		}
		$stmt->execute();
		$stmt->bind_result($temp_reg_ids);
		while($stmt->fetch()){
			$reg_id[] = $temp_reg_ids;
		}
		
		// Close the prepared statement.
    		if($stmt != null){
			$stmt->close(); 
	    	} 

		return $reg_id;
	}
}

//function to get max _id in case of web add in
function getMaxID($mysqli, $user_id){
	if($stmt = $mysqli->prepare("SELECT MAX(_ID) FROM LOG_TABLE WHERE USER_ID=?")){
		$stmt->bind_param("i", $user_id);
		$stmt->execute();
		$stmt->bind_result($temp_id);
		while($stmt->fetch()){
			$id = $temp_id;
		}
		
		// Close the prepared statement.
		if($stmt != null){
			$stmt->close(); 
	    	}
		
		return ++$id;		  		
	}
}

//function to get max odo for user/vehicle
function getMaxOdo($mysqli, $user_id, $vehid){
	$max_odo = 0;
	
	if($stmt = $mysqli->prepare("SELECT MAX(ODO) FROM LOG_TABLE WHERE USER_ID=? AND VEHID=?")){
		$stmt->bind_param("is", $user_id, $vehid);
		$stmt->execute();
		$stmt->bind_result($temp_odo);
		while($stmt->fetch()){
			$max_odo = $temp_odo;
		}
				
		if($stmt != null){
			$stmt->close(); 
	    	} 
		    		
		return $max_odo;		  
	}
}

//function to get max date for user/vehicle
function getMaxDate($mysqli, $user_id, $vehid){
	$max_date = 0;
	
	if($stmt = $mysqli->prepare("SELECT MAX(DATE) FROM LOG_TABLE WHERE USER_ID=? AND VEHID=?")){
		$stmt->bind_param("is", $user_id, $vehid);
		$stmt->execute();
		$stmt->bind_result($temp_date);
		while($stmt->fetch()){
			$max_date = $temp_date;
		}
		
		// Close the prepared statement.
		if($stmt != null){
			$stmt->close(); 
	    	} 
		    		
		return $max_date;		  
	}
}

//function to update distance for all columns of a user/vehid
function updateDist($mysqli, $user_id, $vehid){
	if($stmt = $mysqli->prepare("SELECT _ID, ODO FROM LOG_TABLE WHERE USER_ID=? AND VEHID=? AND TYPE=0 ORDER BY ODO ASC")){
		$stmt->bind_param("is", $user_id, $vehid);
		$stmt->execute();
		$stmt->bind_result($temp_id, $temp_odo);
		while($stmt->fetch()){
			$id[] = $temp_id;
			$odo[] = $temp_odo;						
		}

		if(count($id)>0){
			$curr_odo = 0;
			$prev_odo = 0;
			
			//update first record
			$curr_id = $id[0];
			$stmt = $mysqli->prepare("UPDATE LOG_TABLE SET DIST=0 WHERE USER_ID=? and _ID=?");
			$stmt->bind_param("ii", $user_id, $curr_id);
			$stmt->execute();
			
			//update remaining records
			if(count($id>1)){
				for($i=1; $i<count($id); $i++){
					$curr_id = $id[$i];
					$curr_odo = $odo[$i];
					$prev_odo = $odo[$i-1];
					$curr_dist = $curr_odo - $prev_odo;
					
					$stmt = $mysqli->prepare("UPDATE LOG_TABLE SET DIST=? WHERE USER_ID=? and _ID=?");
					$stmt->bind_param("dii", $curr_dist, $user_id, $curr_id);
					$stmt->execute();
				}
			}
		}
		
		// Close the prepared statement.
		if($stmt != null){
			$stmt->close(); 
	    	} 
	}
}

//function to update eff for all columns of user id/vehid
function updateEff($mysqli, $user_id, $vehid){
	//get value from set factors
	$factors = getUnits($user_id);
	$dist_fact = $factors[0];
	$vol_fact = $factors[1];
	
	$curr_qty = 0;
	$curr_dist = 0;
	$curr_id = 0;
	$prev_qty = 0;
	$prev_dist = 0;
	$firstFullFillUp = FALSE;
	
	if($stmt = $mysqli->prepare("SELECT _ID, QTY, DIST, PARTIAL_FILL, MISSED_FILL FROM LOG_TABLE WHERE USER_ID=? AND VEHID=? and TYPE = 0 ORDER BY ODO ASC")){
		$stmt->bind_param("is", $user_id, $vehid);
		$stmt->execute();
		$stmt->bind_result($temp_id, $temp_qty, $temp_dist, $temp_pfill, $temp_mfill);
		while($stmt->fetch()){
			$id[] = $temp_id;
			$qty[] = $temp_qty;
			$dist[] = $temp_dist;
			$pfill[] = $temp_pfill;
			$mfill[] = $temp_mfill;							
		}
		
		if(count($id)>0){
			for($i=0; $i<count($id); $i++){
				$curr_id = $id[$i];
				
				//if partial record then update eff as -1000
				if($pfill[$i]==1){
					$curr_dist = $dist[$i];
					
					//to take care for first rec or missed fill up record in case OT=odo
					if($curr_dist==0 || $mfill[$i]==1){
						$stmt = $mysqli->prepare("UPDATE LOG_TABLE SET CONSUMPTION=NULL WHERE USER_ID=? and _ID=?");
						$stmt->bind_param("ii", $user_id, $curr_id);
						$stmt->execute();						
					}
					//else it is not the first record
					else{		
						$prev_qty = $prev_qty + $qty[$i];
						$prev_dist = $prev_dist + $dist[$i];
						
						$stmt = $mysqli->prepare("UPDATE LOG_TABLE SET CONSUMPTION=-1000 WHERE USER_ID=? and _ID=?");
						$stmt->bind_param("ii", $user_id, $curr_id);
						$stmt->execute();
					}
				}
				//else it is a normal record
				else{
					$curr_qty = $prev_qty + $qty[$i];			
					$curr_dist = $prev_dist + $dist[$i];
					$prev_qty = 0;
					$prev_dist = 0;
					
					//if rec is is a missed fill up then update cons with 0
					if($mfill[$i]==1){
						$stmt = $mysqli->prepare("UPDATE LOG_TABLE SET CONSUMPTION=0 WHERE USER_ID=? and _ID=?");
						$stmt->bind_param("ii", $user_id, $curr_id);
						$stmt->execute();

						//mark first full fill up as complete
						$firstFullFillUp = TRUE;
					}
					// if dist = 0 or this is the first full fill up (adding this since first fill up can be partial)
					else if($curr_dist==0 || !$firstFullFillUp){
						$stmt = $mysqli->prepare("UPDATE LOG_TABLE SET CONSUMPTION=NULL WHERE USER_ID=? and _ID=?");
						$stmt->bind_param("ii", $user_id, $curr_id);
						$stmt->execute();
						
						//mark first full fill up as complete
						$firstFullFillUp = TRUE;
					}
					else{
						$f = ($curr_dist*$dist_fact)/($curr_qty*$vol_fact);
						
						if(is_infinite($f) || is_nan($f)){
							$f = 0;				
						}								
						
						$stmt = $mysqli->prepare("UPDATE LOG_TABLE SET CONSUMPTION=? WHERE USER_ID=? AND _ID=?");
						$stmt->bind_param("dii", $f, $user_id, $curr_id);
						$stmt->execute();
					}
				}
			}
			
			//update -1000's to eff of above record
			if($stmt = $mysqli->prepare("SELECT _ID, CONSUMPTION, DIST FROM LOG_TABLE WHERE USER_ID=? AND VEHID=? and TYPE = 0 ORDER BY ODO DESC")){
				$stmt->bind_param("is", $user_id, $vehid);
				$stmt->execute();
				$stmt->bind_result($temp_id2, $temp_eff2, $temp_dist2);
				while($stmt->fetch()){
					$id2[] = $temp_id2;
					$eff2[] = $temp_eff2;
					$dist2[] = $temp_dist2;
				}
				
				$curr_eff = 0;
				$prev_eff = 0;
				$curr_id = 0;
				
				for($i=0; $i<count($id2); $i++){
					$curr_id = $id2[$i];
					$curr_eff = $eff2[$i];
					$curr_dist = $dist2[$i];
					
					//update eff from above eff only if dist is not 0 
					//(in case first rec is partial and OT is odo we do not want this updated)
					if($curr_eff==-1000){
						if($curr_dist==0){
							$stmt = $mysqli->prepare("UPDATE LOG_TABLE SET CONSUMPTION=NULL WHERE USER_ID=? AND _ID=?");
							$stmt->bind_param("ii", $user_id, $curr_id);
							$stmt->execute();
						}
						else{
							$stmt = $mysqli->prepare("UPDATE LOG_TABLE SET CONSUMPTION=? WHERE USER_ID=? AND _ID=?");
							$stmt->bind_param("dii", $prev_eff, $user_id, $curr_id);
							$stmt->execute();
						}
					}
					else{
						$prev_eff = $curr_eff;
					}
				}
			}
		}
		
		// Close the prepared statement.
		if($stmt != null){
			$stmt->close(); 
	    	} 
	}
}

//function to check if penultimate record is PF, then update Eff the long way
function checkPreviousRecIfPF($mysqli, $user_id, $vehid){
	if($stmt = $mysqli->prepare("SELECT PARTIAL_FILL FROM LOG_TABLE WHERE USER_ID=? AND VEHID=? and TYPE = 0 ORDER BY ODO DESC")){
		$stmt->bind_param("is", $user_id, $vehid);
		$stmt->execute();
		$stmt->bind_result($temp_pfill);
		while($stmt->fetch()){		
			$pfill[] = $temp_pfill;
		}
		
		//check if penultimate pfill is 1
		if(count($pfill)>=1){
			if($pfill[1]==1){
				return TRUE;
			}
			else{
				return FALSE;
			}
		}
		//there is no penultimate record
		else{
			return FALSE;
		}
	}
}

//function to update reminders in SERVICE_TABLE when servies/expenses are updated on the web
function updateReminders($mysqli, $user_id, $vehid, $tasks_performed){
	
	//get all records that have a reminder by odo or date
	if($stmt = $mysqli->prepare("SELECT SERVICE_NAME, _ID FROM SERVICE_TABLE WHERE USER_ID=? AND VEHID=? AND (DUE_MILES>0 OR DUE_DAYS>0)")){
		$stmt->bind_param("is", $user_id, $vehid);
		$stmt->execute();
		$stmt->bind_result($temp_service_name, $temp_id);
		while($stmt->fetch()){
			$service_name[] = $temp_service_name;
			$id[] = $temp_id;
		}
		
		if(count($service_name)>0){				
			//go thru each record with reminder
			for($i=0; $i<count($service_name); $i++){	
				//get id of record in SERVICE_TABLE
				$curr_id = $id[$i];
						
				//check if service name is the same as the one being updated
				$serviceName = $service_name[$i];				
				
				if(strpos($tasks_performed, $serviceName)!==false){
					//get max odo for that service/expense for the user id, vehid
					$stmt = $mysqli->prepare("SELECT ODO, DATE FROM LOG_TABLE WHERE USER_ID=? AND VEHID=? AND SERVICE_TYPE LIKE ? ORDER BY ODO DESC");
					$paramServiceName = "%".$serviceName."%";
					$stmt->bind_param("iss", $user_id, $vehid, $paramServiceName);
					$stmt->execute();
					$stmt->bind_result($temp_max_odo, $temp_max_date);
					while($stmt->fetch()){
						$max_service_odo[] = $temp_max_odo;
						$max_service_date[] = $temp_max_date;
					}					

					if(count($max_service_odo)>0){		
						//update the last odo in service table to the max odo found in the log table
						$stmt = $mysqli->prepare("UPDATE SERVICE_TABLE SET LAST_ODO=?, LAST_DATE=? WHERE USER_ID=? and _ID=?");
						$stmt->bind_param("diii", $max_service_odo[0], $max_service_date[0], $user_id, $curr_id);
						$stmt->execute();												
					}
					//else service not found (in case of deleting the one and only record)
					else{
						//get max odo for vehid
						$max_odo =  getMaxOdo($mysqli, $user_id, $vehid);
						
						//get max date for vehid
						$max_date = getMaxDate($mysqli, $user_id, $vehid);

						//update the last odo in service table to the max odo found in the log table
						$stmt = $mysqli->prepare("UPDATE SERVICE_TABLE SET LAST_ODO=?, LAST_DATE=? WHERE USER_ID=? and _ID=?");
						$stmt->bind_param("diii", $max_odo, $max_date, $user_id, $curr_id);
						$stmt->execute();						
					}
					
				}
			}
		}		
	}
}

?>