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

/*The following code pulls data for the sent Android ID and sends the data back*/

// 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['androidId'])){
	// 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
	$androidId = $jsonArr['androidId'];

	//get data from sync table
	if($stmt = $mysqli->prepare("SELECT TABLE_NAME, ROW_ID, TYPE, USER_ID FROM SYNC_TABLE WHERE ANDROID_ID = ? ORDER BY COUNTER")){
		$sync_data = array();
		$stmt->bind_param("s", $androidId);
		$stmt->execute(); 
		//storing result since we are running another query
		$stmt->store_result();
		
		$stmt->bind_result($temp_table, $temp_row_id, $temp_type, $temp_user_id);		
		while($stmt->fetch()){		
			$table = $temp_table;
			$row_id = $temp_row_id;
			$type = $temp_type;
			$user_id = $temp_user_id;

			//get row from table if table is not Settings or Alarm
			if(strcmp($table, "SETTINGS")!=0 && strcmp($table, "ALARM")!=0){
				if($result = $mysqli->query("SELECT * FROM " . $table . " WHERE USER_ID = " . $user_id . " AND _ID = " . $row_id)){
					$row = array();
					$row["table"] = $table;
					$row["type"] = $type;
					$row["_ID"] = $row_id;
							
					$i = 0;
					while ($temp_row = $result->fetch_row()){
						while ($finfo = mysqli_fetch_field($result)) {
							//add all columns to row[] except _ID (since we have added it already) and USER_ID (since not needed)
							if(strcmp($finfo->name, "_ID")!=0 && strcmp($finfo->name, "USER_ID")!=0){
								$row[$finfo->name] = $temp_row[$i];
							}
								
							++$i;
						}
					}
					
					//if vehicle has image then send that as well
					if(strcmp($table, "VEH_TABLE")==0){
						$pic = $row["PICTURE"];

						if(!empty($pic)){
							$file_path = "../FBImagesTemp/";
							$file_path = $file_path . $pic; 
							$row["PIC"] = base64_encode(file_get_contents($file_path));
						}
						else{
							$row["PIC"] = "";
						}
					}
					
					//if receipt then need to send image as well
					if(strcmp($table, "LOG_TABLE")==0){
						//check if receipt should be attached
						$pic = $row["RECEIPT"];

						if(!empty($pic)){
                            if (strpos($pic,":::")){
						    $receiptarray=(explode(":::",$pic));
                            $receipt= array_filter($receiptarray);
                            $rimagearray=array();
						    foreach ($receipt as $singlepicpath) {
						        $file_path = "../FBReceiptsTemp/";
							    $file_path = $file_path . $singlepicpath; 
						    	$rimage= base64_encode(file_get_contents($file_path));
                                array_push($rimagearray,$rimage);
                                }
                            $row["PIC"]=$rimagearray;
                            foreach($rimagearray as $testreceipt)
                            {
                                error_log("\n receipt  :- ".$testreceipt, 3, "my-errors.log");
                            }
                            }
                            else{
                                $file_path = "../FBReceiptsTemp/";
							    $file_path = $file_path . $pic; 
							    $row["PIC"] = base64_encode(file_get_contents($file_path));    
                            }
                            
							//if image is not empty then push out immedietly due to out of memory issue (once it is pushed script will end)
							if(!empty($row["PIC"])){
								array_push($sync_data, $row);	
								
								if($result != null){
									$result->close();
								}
								
								//push out response with a to_be_continued flag
								$response["success"] = 1;
								$response["message"] = "Success";
								$response["to_be_continued"] = "Yes";
								$response["sync_data"] = $sync_data;
								
								// echoing JSON response
								echo json_encode($response);
								
								// Close the prepared statement.
								if($stmt != null){
							    		$stmt->close(); 
							    	}
							    	
							    	//exit the script
							    	exit; 
						    	}
						}
						else{
							$row["PIC"] = "";
						}							
					}
					
					//safety check to send data only if type is delete or row has more than 3 items
					//prevents sending data when row is not found found for add or update
					if(strcmp($type, "del")==0 || count($row)>3){
						array_push($sync_data, $row);											
					}																
						
					if($result != null){
						$result->close();
					}														
				}
			}
			//else table is Settings
			else if(strcmp($table, "SETTINGS")==0){
				if($result = $mysqli->query("SELECT * FROM SETTINGS WHERE USER_ID = " . $user_id)){
					$row = array();
					$row["table"] = $table;
					$row["type"] = $type;
					$row["_ID"] = $row_id;
					
					$i = 0;
					while ($temp_row = $result->fetch_row()){
						while ($finfo = mysqli_fetch_field($result)) {
							//add all columns to row[] except USER_ID (since not needed)
							if(strcmp($finfo->name, "USER_ID")!=0){
								$row[$finfo->name] = $temp_row[$i];
							}
								
							++$i;
						}
					}
					
					//safety check to send data only if row has more than 3 items
					//prevents sending data when row is not found
					if(count($row)>3){
						array_push($sync_data, $row);
					}
						
					if($result != null){
						$result->close();
					}
				}
			}
			else if(strcmp($table, "TRIP_DETAILS")==0){
			    
				if($result = $mysqli->query("SELECT * FROM TRIP_DETAILS WHERE USER_ID = ". $user_id . " AND _ID = " . $row_id)){
				       
					$row = array();
					$row["table"] = $table;
					$row["type"] = $type;
					$row["_ID"] = $row_id;
					
					$i = 0;
					while ($temp_row = $result->fetch_row()){
						while ($finfo = mysqli_fetch_field($result)) {
							//add all columns to row[] except USER_ID (since not needed)
							if(strcmp($finfo->name, "USER_ID")!=0){
								$row[$finfo->name] = $temp_row[$i];
							}
								
							++$i;
						}
					}
					
					//safety check to send data only if row has more than 3 items
					//prevents sending data when row is not found
					if(count($row)>3){
						array_push($sync_data, $row);
					}
						
					if($result != null){
						$result->close();
					}
				}
			}
			//else table is ALARM
			else{
				$row = array();
				$row["table"] = $table;
				$row["type"] = $type;
				$row["_ID"] = $row_id;
				
				array_push($sync_data, $row);
			}				
		}
	
		$response["success"] = 1;
		$response["message"] = "Success";
		$response["sync_data"] = $sync_data;
		
		// 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();
}
else{
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing JSON response
    echo json_encode($response);
}

?>