<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
	// Load the GeoJSON file
	$geojsonFile = 'points_default.geojson'; // Path to your GeoJSON file
	$geojsonData = file_get_contents($geojsonFile);

	// Decode the GeoJSON into a PHP array
	$geojson = json_decode($geojsonData, true); // True for associative array

	// Cast strings to numbers where needed
	$_POST['location_id'] = (int) $_POST['location_id'];
	$_POST['latitude'] = (double) $_POST['latitude'];
	$_POST['longitude'] = (double) $_POST['longitude'];
	$_POST['pop_2010'] = (int) $_POST['pop_2010'];
	$_POST['FEMA_REG'] = substr($_POST['FEMA_REG'], 4);

	// Search for the feature with the submitted ID
	$existingFeatureIndex = null;
	foreach ($geojson['features'] as $index => $feature) {
		if (isset($feature['properties']['location_id']) && $feature['properties']['location_id'] == $_POST['location_id']) {
		    $existingFeatureIndex = $index;
		    break;
		}
	}

	if ($existingFeatureIndex != null) {  // In this case, we're editing an existing point in the GeoJSON file
		// Assign the existing feature to $feature where we'll edit it
		$feature = $geojson['features'][$existingFeatureIndex];

	} else {  // In this case, we're adding a new point to the GeoJSON file
		// Create a new feature array
		$feature = [
		    "type" => "Feature",
		    "properties" => [],
		    "geometry" => [
		        "type" => "Point",
		        "coordinates" => [$_POST['longitude'], $_POST['latitude']]
		    ]
		];

		// Extract existing IDs into an array
		$existingIds = [0]; // Start with 0 so max() doesn't error on empty files
		foreach ($geojson['features'] as $existingFeature) {
			if (isset($existingFeature['properties']['location_id'])) {
				// Ensures that location IDs are cast to an int, properties is not cast as an int
				$existingIds[] = (int)$existingFeature['properties']['location_id'];
			}
		}

		// Set the new ID as the highest current ID + 1
		$feature['properties']['location_id'] = max($existingIds) +1;
	}

	// Write the values from these inputs into the point feature
	foreach ($_POST as $key => $value) {
		if (in_array($key, ['name', 'state', 'pop_2010', 'WFO', 'NWS_REG', 'FEMA_REG', 'RFC', 'CWSU']) || ($key == 'location_id' && $existingFeatureIndex != null)) {
			$feature['properties'][$key] = $value;
		}
	}

	// Write the coordinates to the feature
	$feature['geometry']['coordinates'] = [$_POST['longitude'], $_POST['latitude']];

	// Write the value for all display attributes on this point feature
	if ($_POST['force-display-wfo'] == 'on') {
		$value = "force_show";
	} else if ($_POST['hide-display-wfo'] == 'on') {
		$value = "hide";
	} else {
		$value = "default";
	}
	$feature['properties']['WFO_display'] = $value;

	if ($_POST['force-display-state'] == 'on') {
		$value = "force_show";
	} else if ($_POST['hide-display-state'] == 'on') {
		$value = "hide";
	} else {
		$value = "default";
	}
	$feature['properties']['state_display'] = $value;

	if ($_POST['force-display-nws-reg'] == 'on') {
		$value = "force_show";
	} else if ($_POST['hide-display-nws-reg'] == 'on') {
		$value = "hide";
	} else {
		$value = "default";
	}
	$feature['properties']['NWS_REG_display'] = $value;

	if ($_POST['force-display-fema'] == 'on') {
		$value = "force_show";
	} else if ($_POST['hide-display-fema'] == 'on') {
		$value = "hide";
	} else {
		$value = "default";
	}
	$feature['properties']['FEMA_REG_display'] = $value;

	if ($_POST['force-display-rfc'] == 'on') {
		$value = "force_show";
	} else if ($_POST['hide-display-rfc'] == 'on') {
		$value = "hide";
	} else {
		$value = "default";
	}
	$feature['properties']['RFC_display'] = $value;

	if ($_POST['force-display-cwsu'] == 'on') {
		$value = "force_show";
	} else if ($_POST['hide-display-cwsu'] == 'on') {
		$value = "hide";
	} else {
		$value = "default";
	}
	$feature['properties']['CWSU_display'] = $value;

	// Copy our changes into the GeoJSON string
	if ($existingFeatureIndex == null) {
		$geojson['features'][] = $feature;
	} else {
		$geojson['features'][$existingFeatureIndex] = $feature;
	}

	// Write the updates GeoJSON array into a GeoJSON string
	$updatedGeojsonData = json_encode($geojson, JSON_PRETTY_PRINT);

    // Write data to the file
    if (file_put_contents($geojsonFile, $updatedGeojsonData) !== false) {
        echo "Changes made successfully";
    } else {
        echo "Could not make changes";
    }
} else {
    echo "This PHP file expects a POST request, and will not operate otherwise.";
}
?>

