?php header('Content-Type: application/json'); $device_id = $_GET['device_id'] ?? ''; $limit = intval($_GET['limit'] ?? 20); // Default 20, adjustable $limit = max(1, min($limit, 100)); // Clamp between 1-100 if (empty($device_id)) { echo json_encode(['success' => false, 'message' => 'Missing device_id']); exit; } try { $pdo = new PDO('sqlite:gps_tracker.db'); // Updated: SQLite file path $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('SELECT lat, lng, timestamp, device_id FROM locations WHERE device_id = ? ORDER BY timestamp DESC LIMIT ?'); $stmt->execute([$device_id, $limit]); $locations = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode(['success' => true, 'locations' => array_reverse($locations)]); // Reverse for chronological order } catch (PDOException $e) { echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]); } ?>