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


/*This table deletes all data for a user_id, and then does a full upload on the server */

// 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);
foreach($jsonArr as $dat)
{
    foreach($dat as $dt)
    {
error_log("\n data".$dt ,3,"my-errors.log");

    }
    }
// check for required fields
if (count($jsonArr)>0){
	// 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 android id
    $android_id = $jsonArr[0]['androidId'];
    	
    //get user id
    $stmt = $mysqli->prepare("SELECT USER_ID FROM PROFILE WHERE ANDROID_ID = ?");
    $stmt->bind_param("s", $android_id);	
	$stmt->execute();
	$stmt->bind_result($temp_user_id);
	while($stmt->fetch()){
		$user_id = $temp_user_id;
	}
    	
    //proceed only if user_id is valid
    if(!empty($user_id)){
       
	    //get table name
	    $table_name = $jsonArr[1]['tableName'];
	    
	    //go through all rows
	    for($i=2; $i<count($jsonArr); $i++){
            $row = $jsonArr[$i];   
	    
	    	//if table is settings 		
	    	if(strcmp($table_name, "SETTINGS")==0){
    	    	//first delete all data for the user_id (this has to be done in Settings since its the first call)
    	    	deleteAllData($mysqli, $user_id);
    
    	    	//get dist
    	    	if(strcmp($row['dist'], "Kilometers")==0){
    			    $dist = "km";
    			}
    			else{
    			    $dist = "mi";
    			}
    
    			//get vol
    			if(strcmp($row['vol'], "Litre")==0){
    			    $vol = "Ltr";
    			}
    			else if(strcmp($row['vol'], "Gallon(US)")==0){
    			    $vol = "gal(US)";
    			}	
    			else{
    			    $vol = "gal(UK)";
    			}
    				
    		    //get cons and curr
    		    $cons = $row['cons'];
    		    $curr = $row['curr'];
    
    		    //insert into settings table
    		    $stmt = $mysqli->prepare("INSERT INTO SETTINGS VALUES (?, ?, ?, ?, ?)");
    		    $stmt->bind_param("issss", $user_id, $dist, $vol, $cons, $curr);
    			$result = $stmt->execute();

               
    			//settings will always have only one row, so no worry about loop
    			if($result){
    			    $response["success"] = 1;	
    		    }
    	    }
	    	//else if table is vehicles
	    	else if(strcmp($table_name, "VEH_TABLE")==0){
	    	    
	    	    $id = $row['id'];
			    $mk = $row['make'];
			    $md = $row['model'];
				$vid = $row['vehid'];
				$year = $row['year'];
				$lc = $row['lic'];
				$vin = $row['vin'];
				$insNo = $row['insuranceNo'];
				$notes = $row['notes'];
				$picPath = $row['picture'];
				$customSpecs = $row['customSpecifications'];
				
				//change picPath to only name and append email id
				if(!empty($picPath)){
					//get email
					$email = getEmail($mysqli, $user_id);
					
					$picPath = str_replace(" ", "_", $picPath);
					$picPath = $email . "." . basename($picPath);
					
				}
				
						
						
				$stmt = $mysqli->prepare("INSERT INTO VEH_TABLE(USER_ID, _ID, MAKE, MODEL, LIC, VEHID, YEAR, VIN, INSURANCE_NO, NOTES, PICTURE, CUSTOM_SPECIFICATIONS) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
				$stmt->bind_param("iissssssssss", $user_id, $id, $mk, $md, $lc, $vid, $year, $vin, $insNo, $notes, $picPath, $customSpecs);
		    		$result = $stmt->execute(); 
		    		 
		    		if($result){
					//set response to 1 and continue loop
					$response["success"] = 1;	
		    		}
		    		else{
		    			//set response to 0 and break loop to exit script
		    			$response["success"] = 0;
		    			
		    			break;
		    		}
	    		}
	    		//else if table is loc
	    		else if(strcmp($table_name, "LOC_TABLE")==0){
	    			$id = $row['id'];
	    			$address = $row['address'];
    				$brand = $row['brand'];
    				$lat = $row['lat'];
    				$longi = $row['long'];
    				
    			
    				 
                
    				$stmt = $mysqli->prepare("INSERT INTO LOC_TABLE VALUES(?, ?, ?, ?, ?, ?)");
    				$stmt->bind_param("iissdd", $user_id, $id, $address, $brand, $lat, $longi);
		    		$stmt->execute();
		    		 
		    		//return success regardless of result since we will be proceding anyway
		    		$response["success"] = 1;
		    		
	    		}
	    		//else if table is service_table
	    		else if(strcmp($table_name, "SERVICE_TABLE")==0){
	    			$id = $row['id'];
	    			$vid = $row['vehid'];
    				$type = $row['type'];
    				$serviceName = $row['serviceName'];
    				$recurring = $row['recurring'];
    				$dueMiles = $row['dueMiles'];
    				$dueDays = $row['dueDays'];
    				$lastOdo = $row['lastOdo'];
    				$lastDate = $row['lastDate'];
    				
				
    				$stmt = $mysqli->prepare("INSERT INTO SERVICE_TABLE(USER_ID, _ID, VEHID, TYPE, SERVICE_NAME, RECURRING, DUE_MILES, DUE_DAYS, LAST_ODO, LAST_DATE) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    				$stmt->bind_param("iisisididi", $user_id, $id, $vid, $type, $serviceName, $recurring, $dueMiles, $dueDays, $lastOdo, $lastDate);
		    		$result = $stmt->execute();

				    //return success regardless of result since we will be proceding anyway
		    		$response["success"] = 1;		    		
	    		}
	    		//else if table is log
	    		else if(strcmp($table_name, "LOG_TABLE")==0){
    				$id = $row['id'];
    				$vid = $row['vehid'];
    				$date = $row['date'];
    				$odo = $row['odo'];
    				$qty = $row['qty'];
    				$pfill = $row['pfill'];
    				$mfill = $row['mfill'];
    				$cost =	$row['cost'];
    				$dist =	$row['dist'];
    				$cons =	$row['cons'];
    				$octane = $row['ocatne']; //we know spelling is wrong
    				$fuelBrand = $row['fuelBrand'];
    				$fillStation = $row['fillStation'];
    				$notes = $row['notes'];
    				$day = $row['day'];
    				$month = $row['month'];
    				$year =	$row['year'];
    				$receipt = $row['receipt'];
    				$type = $row['type'];
    				$serviceType = $row['serviceType'];
				 
    			//change receipt name to only name and append email id
    			$finalreceipt="";
    			
    			if(!empty($receipt)){
    		    	$email = getEmail($mysqli, $user_id);
    		    	
                    //check if receipt has three colons
			        if (strpos($receipt,":::")){
			            //explode receipt string into array 
				        $receiptarray=(explode(":::",$receipt));
					    $receipt= array_filter($receiptarray);
				    	$finalreceipt="";

					    foreach ($receipt as $value) {
                            if(strpos($value, $email) !== false){
       				 	        $tempreceipt=basename($value);
       				 	        
       			   		        if($finalreceipt=="")
							    {
								    $finalreceipt=$tempreceipt;
					            }
							    else
							    {
								    $finalreceipt=$finalreceipt.":::".$tempreceipt; 
							    }
					    	}
					        else{
      				            //if image name doesnot contains email then attach email with file name
							    $tempreceipt = $email . "." . basename($value);
                                if($finalreceipt=="")
							    {
								    $finalreceipt=$tempreceipt;
							    }
							    else
							    {
							    	$finalreceipt=$finalreceipt.":::".$tempreceipt; 
						    	}
					            
					        }
					    }
					    
				        $finalreceipt=$finalreceipt.":::";
			        }
			        else{
        			    //if receipt does not contains ::: then add receipt name and email directly
                        $receipt = str_replace(" ", "_",$receipt);			
                
        				if(strpos($receipt, $email) !== false){										
        				    $finalreceipt = basename($receipt);
        				 }
                    	else{
        				    $finalreceipt = $email . "." . basename($receipt);
        				}
                    }
        }
    				
    				$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, $finalreceipt, $type, $serviceType);
    		    	$result = $stmt->execute();
                 
                  
    		    	if($result){
    		    	   
    				    //set response to 1 and continue loop
    					$response["success"] = 1;	
    		    	}
    		    	else{
    		    		//set response to 0 and break loop to exit script
    		    		$response["success"] = 0;
    		    			
    		    		break;
    		    	}		
	    		}
	    	
	    	
	    	// full uploaad  trip details code 
	    	else if(strcmp($table_name, "TRIP_DETAILS")==0){
	    	      
    				$id = $row['id'];
    				$trip_id=$row['trip_id'];
    				$avg_speed=$row['avg_speed'];
    		
    				$stmt = $mysqli->prepare("INSERT INTO TRIP_DETAILS(USER_ID, _ID,TRIP_ID ,AVG_SPEED) VALUES(?, ?, ?, ?)");
    		    	$stmt->bind_param("iiid", $user_id, $id, $trip_id, $avg_speed);
    		    	$result = $stmt->execute();
                  
                  
    		    	if($result){
    		    	   
    				    //set response to 1 and continue loop
    					$response["success"] = 1;	
    		    	}
    		    	else{
    		    		//set response to 0 and break loop to exit script
    		    		$response["success"] = 0;
    		    			
    		    		break;
    		    	}		
	    		}
	    	}
	    	
	    	//if table is endUpload
	    	if(strcmp($table_name, "endUpload")==0){
	    	    
	    		//get other android ids the full upload needs to be sent to
	    		$a_ids = getOtherAndroidIds($mysqli, $user_id, $android_id);
	    		
	    		$aid_cnt = count($a_ids);

	    		if($aid_cnt>0){
	    			//call full_download.php with these android_ids
	    			for($i=0; $i<$aid_cnt; $i++){
	    				$url = 'http://www.fuelbuddy-app.com/DatabaseScriptsTemp/full_download_v2.php';
	    				$fields = array(
	    				'androidId' => $a_ids[$i],
	    				'full_pull_type' => 'full_pull_silent',
	    				'sent_from' => 'php');
	    				
    					$json = json_encode($fields);
    					
    					//open connection
    					$ch = curl_init();
    					
    					//set the url, number of POST vars, POST data
    					curl_setopt($ch,CURLOPT_URL, $url);
    					curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
    					curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    					
    					//execute post
    					$result = curl_exec($ch);
    					
    					//close connection
    					curl_close($ch);
	    			}	    			
	    		}
	    		
	    		//update timestamp in Profile
		    	updateTimestamp($user_id);
		    		
	    		//return success
		    	$response["success"] = 1;
	    	}
    	}

    	//else send generic failure message
	if($response["success"] == 0){
	   
		$response["success"] = 0;
		$response["message"] = "Failed";
								 
		// echoing JSON response
		echo json_encode($response);
	}
	//else response is a success, return success
	else{
		$response["success"] = 1;
		$response["message"] = "Success";
								 
		// echoing JSON response
		echo json_encode($response);
	}
	
	// Close the prepared statement.
    	if($stmt != null){
		$stmt->close(); 
	} 
	
	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 return partner android ids
function getOtherAndroidIds($mysqli, $userID, $androidIDToIgnore){
	$stmt = $mysqli->prepare("SELECT ANDROID_ID FROM PROFILE WHERE USER_ID = ? AND ANDROID_ID!=?");
	$stmt->bind_param("is", $userID, $androidIDToIgnore);	
	$stmt->execute();
	$stmt->bind_result($temp_android_ids);
	while($stmt->fetch()){		
		$a_ids[] = $temp_android_ids;
	}	
	
	// Close the prepared statement.
    	if($stmt != null){
		$stmt->close(); 
	} 

	return $a_ids;
}

//function to get email from user_id
function getEmail($mysqli, $user_id){
	$stmt = $mysqli->prepare("SELECT EMAIL FROM USER_ID WHERE USER_ID = ?");
	$stmt->bind_param("i", $user_id);	
	$stmt->execute();
	$stmt->bind_result($temp_email);
	while($stmt->fetch()){
		$email = $temp_email;
	}
	
	// Close the prepared statement.
    	if($stmt != null){
		$stmt->close(); 
	}
	
	return $email;
}

//function to delete all existing data for a user_id
function deleteAllData($mysqli, $user_id){
    
	//delete data from VEH_TABLE (will also delete from LOG_TABLE)
	$stmt = $mysqli->prepare("DELETE FROM VEH_TABLE WHERE USER_ID=?");
	$stmt->bind_param("i", $user_id);	
	$stmt->execute();
	
	//delete data from SERVICE_TABLE
	$stmt = $mysqli->prepare("DELETE FROM SERVICE_TABLE WHERE USER_ID=?");
	$stmt->bind_param("i", $user_id);	
	$stmt->execute();
	
	//delete data from LOC_TABLE
	$stmt = $mysqli->prepare("DELETE FROM LOC_TABLE WHERE USER_ID=?");
	$stmt->bind_param("i", $user_id);	
	$stmt->execute();
	
	//delete data from SETTINGS
	$stmt = $mysqli->prepare("DELETE FROM SETTINGS WHERE USER_ID=?");
	$stmt->bind_param("i", $user_id);	
	$stmt->execute();
	
	//delete data from SYNC_TABLE (delete for all android_ids of the user_id, since we will be doing full_download to other user_ids anyway)
	$stmt = $mysqli->prepare("DELETE FROM SYNC_TABLE WHERE USER_ID=?");
	$stmt->bind_param("i", $user_id);	
	$stmt->execute();
	
	//delete all images for the user as well
	$email = getEmail($mysqli, $user_id);
	$file_path = "../FBReceiptsTemp/".$email.'*';
	foreach(glob($file_path) as $file){
		if(is_file($file)){
			unlink($file);
		}
	}
	
	$file_path = "../FBImagesTemp/".$email.'*';
	foreach(glob($file_path) as $file){
		if(is_file($file)){
			unlink($file);
		}
	}
	
	// Close the prepared statement.
    	if($stmt != null){
		$stmt->close(); 
	}
}

?>