<?php

// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
 
// get posted data
$data = json_decode(file_get_contents("php://input"));

// make sure data is not empty
if(isset($data->totalExpenses) && !empty($data->totalExpenses) && $data->totalExpenses !== '' && isset($data->totalReturns) && !empty($data->totalReturns) && $data->totalReturns !== ''){
	// Get the contents of the JSON file 
    $strJsonFileContents = file_get_contents("./data/data.json");
    // Convert to array 
    $serverData = json_decode($strJsonFileContents, true);
    $serverDataArray = $serverData['data'];
	
	$newHunt = new stdClass();
    $newHunt->expenses = $data->expenses;
	$newHunt->returns = $data->returns;
	$newHunt->start = $data->start;
	$newHunt->end = $data->end;
	$newHunt->totalExpenses = $data->totalExpenses;
	$newHunt->totalReturns = $data->totalReturns;
	$newHunt->shrapnelPercentage = $data->shrapnelPercentage;
	$newHunt->mob = $data->mob;
	$newHunt->weapon = $data->weapon;
	$newHunt->notes = $data->notes;
	$newHunt->resultPercentage = $data->resultPercentage;
	$newHunt->resultValueDifference = $data->resultValueDifference;
	$newHunt->huntDuration = $data->huntDuration;
	$newHunt->date = $data->date;
	
	array_push($serverDataArray,$newHunt);
    $serverData['data'] = $serverDataArray;
	
	$fp = fopen('./data/data.json', 'w');
    fwrite($fp, json_encode($serverData,JSON_PRETTY_PRINT));
    fclose($fp);
	
	// set response code
    http_response_code(200);

    // tell the user
    echo "The hunt was saved.";
}
// tell the user data is incomplete
else{
 
    // set response code - 400 bad request
    http_response_code(400);
 
    // tell the user
    echo "Unable to save the URL. Data is not found in the request.";
}