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

/*The following code will add data in TRIPDETAIL 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";

//get json string
$json = file_get_contents('php://input');

//get json array
$jsonArr = json_decode($json, true);

// check for required fields
if ( isset($jsonArr['_id']) && isset($jsonArr['email']) && isset($jsonArr['type']) && isset($jsonArr['trip_id']) && isset($jsonArr['speed'])) { 
// 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
$email=$jsonArr['email'];
$trip_id=$jsonArr['trip_id'];
$avg_speed=$jsonArr['speed'];
$androidId = $jsonArr['androidId'];
$type = $jsonArr['type'];
$rec_type = $jsonArr['rec_type'];
$id=$jsonArr['_id'];

//for inserting new data into tripdetails table
if(strcmp($type, "add") == 0 ){
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;
        }
    }

insertRecInTripDetail($mysqli, $id, $user_id, $trip_id, $avg_speed, $androidId, $type);
//update timestamp in Profile
updateTimestamp($user_id);
$response["success"] = 1;
$response["message"] = "Success";
// echoing JSON response
echo json_encode($response);
         }
 }                         

// 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 insert data into TRIP_DETAILS Table
function insertRecInTripDetail($mysqli, $id, $user_id, $trip_id, $avg_speed, $androidId, $type){
  //insert new record
  if($stmt = $mysqli->prepare("INSERT INTO TRIP_DETAILS(_ID, USER_ID, TRIP_ID, AVG_SPEED) VALUES(?,?,?,?)")){
     // Bind the variables to the parameter as strings. 
     $stmt->bind_param("isss", $id, $user_id, $trip_id, $avg_speed);
     // Execute the statement.
     $result = $stmt->execute(); 
     
     // successfully inserted into database
     // successfully inserted into database

 if ($result) {
     
     //update sync table                 
     if(insertIntoSyncTable($mysqli, $id, $type, $user_id, "TRIP_DETAILS", $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");
      }
           
// Close the prepared statement.
if($stmt != null){
 $stmt->close(); 
       }       
      }       
   }
}

//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;
	}
}

?>