<?php
include "../root.class.php";

$db = new db_safeguard();

// BUG 1 FIX: validate the decoded JSON before accessing keys
$data = json_decode(file_get_contents('php://input'), true);

if (!$data || !isset($data['latitude'], $data['longitude'], $data['distance'], $data['jobcard'])) {
    http_response_code(400);
    echo "Invalid or missing data.";
    exit;
}

// BUG 2 FIX: escape every value through mysqli before inserting
$lat      = $db->escape($data['latitude']);
$lng      = $db->escape($data['longitude']);
$distance = $db->escape($data['distance']);
$jobcard  = $db->escape($data['jobcard']);
$notes    = $db->escape($data['notes'] ?? '');

$result = $db->query(
    "test_locations",
    "INSERT INTO `test_locations`(`latitude`, `longitude`, `distance`, `jobcard`, `notes`)
     VALUES ('$lat', '$lng', '$distance', '$jobcard', '$notes')"
);

if ($result) {
    echo "Location saved successfully.";
} else {
    http_response_code(500);
    echo "Failed to save location.";
}