<?php
session_start();

header('Content-Type: application/json');

// Define the service area bounds for Majuro
const MAJURO_BOUNDS = [
    'minLat' => 7.05,
    'maxLat' => 7.15,
    'minLng' => 171.17,
    'maxLng' => 171.39
];

function isWithinMajuro($lat, $lng) {
    return $lat >= MAJURO_BOUNDS['minLat'] && $lat <= MAJURO_BOUNDS['maxLat'] &&
           $lng >= MAJURO_BOUNDS['minLng'] && $lng <= MAJURO_BOUNDS['maxLng'];
}

$data = json_decode(file_get_contents('php://input'), true);

if (isset($data['lat']) && isset($data['lng'])) {
    $lat = filter_var($data['lat'], FILTER_VALIDATE_FLOAT);
    $lng = filter_var($data['lng'], FILTER_VALIDATE_FLOAT);

    if ($lat === false || $lng === false) {
        echo json_encode(['success' => false, 'message' => 'Invalid coordinates provided.']);
        exit;
    }

    if (!isWithinMajuro($lat, $lng)) {
        echo json_encode(['success' => false, 'message' => 'The selected location is outside our service area.']);
        exit;
    }

    $_SESSION['delivery_location'] = [
        'lat' => $lat,
        'lng' => $lng
    ];

    echo json_encode(['success' => true, 'message' => 'Location saved.']);
} else {
    echo json_encode(['success' => false, 'message' => 'No coordinates provided.']);
}
?>