<?php

// Include connection file
include 'connection.php';

// Get device name from GET request
$deviceName = isset($_GET['devicename']) ? $_GET['devicename'] : '';

// Check if device name is provided
if (empty($deviceName)) {
    // Device name not provided, return error message
    $response = array('error' => 'Device name not provided');
    header('Content-Type: application/json');
    echo json_encode($response);
    exit; // Stop script execution
}

try {
    // Retrieve the most recent location data from the database based on device name
    $sql = "SELECT latitude, longitude FROM location WHERE devicename = :devicename ORDER BY id DESC LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':devicename', $deviceName);
    $stmt->execute();

    // Fetch the data
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($result) {
        // Location data found, return as JSON
        header('Content-Type: application/json');
        echo json_encode($result);
    } else {
        // Location data not found for the device name
        // Return default values or a proper response indicating no data found
        $defaultLocation = array('latitude' => 0, 'longitude' => 0);
        header('Content-Type: application/json');
        echo json_encode($defaultLocation);
    }
} catch (PDOException $e) {
    // Database error occurred
    $response = array('error' => 'Database error: ' . $e->getMessage());
    header('Content-Type: application/json');
    echo json_encode($response);
}
?>
