<?php
// api/location_points.php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['admin', 'staff']);

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

$pdo = db();
$delivery_id = (int)($_GET['delivery_id'] ?? 0);
$limit = (int)($_GET['limit'] ?? 50);

if ($delivery_id <= 0) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Invalid delivery_id']);
    exit;
}

if ($limit < 5) $limit = 5;
if ($limit > 300) $limit = 300;

$stmt = $pdo->prepare("
  SELECT lat, lng, accuracy_m, recorded_at
  FROM delivery_locations
  WHERE delivery_id = :id
  ORDER BY recorded_at DESC
  LIMIT $limit
");
$stmt->execute([':id' => $delivery_id]);
$rows = $stmt->fetchAll();

// Return in oldest->newest order for polyline
$rows = array_reverse($rows);

echo json_encode([
    'ok' => true,
    'delivery_id' => $delivery_id,
    'points' => array_map(function($r) {
        return [
            'lat' => (float)$r['lat'],
            'lng' => (float)$r['lng'],
            'accuracy_m' => $r['accuracy_m'] !== null ? (float)$r['accuracy_m'] : null,
            'recorded_at' => $r['recorded_at'],
        ];
    }, $rows)
]);
