Files
2026-09-16 23:20:08 +07:00

64 lines
2.2 KiB
PHP

<?php
// api/location.php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/config/database.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) {
echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
exit;
}
$action = $_REQUEST['action'] ?? '';
if ($action === 'update_location') {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid method']);
exit;
}
$lat = $_POST['lat'] ?? null;
$lng = $_POST['lng'] ?? null;
$user_id = $_SESSION['user_id'];
if ($lat && $lng) {
$db = Database::getInstance();
// Upsert location (Insert or Update if exists)
$query = "INSERT INTO user_locations (user_id, latitude, longitude)
VALUES (:user_id, :lat, :lng)
ON DUPLICATE KEY UPDATE
latitude = :lat2, longitude = :lng2, last_updated = CURRENT_TIMESTAMP";
$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $user_id);
$stmt->bindParam(':lat', $lat);
$stmt->bindParam(':lng', $lng);
$stmt->bindParam(':lat2', $lat);
$stmt->bindParam(':lng2', $lng);
if ($stmt->execute()) {
echo json_encode(['status' => 'success']);
} else {
echo json_encode(['status' => 'error', 'message' => 'DB update failed']);
}
} else {
echo json_encode(['status' => 'error', 'message' => 'Missing coords']);
}
} elseif ($action === 'get_locations') {
// API for the map view to get all staff locations
$db = Database::getInstance();
$query = "SELECT l.latitude, l.longitude, l.last_updated, u.full_name, u.status
FROM user_locations l
JOIN users u ON l.user_id = u.id
WHERE l.last_updated >= NOW() - INTERVAL 5 MINUTE";
$stmt = $db->prepare($query);
$stmt->execute();
$locations = $stmt->fetchAll();
echo json_encode(['status' => 'success', 'data' => $locations]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Unknown action']);
}