<?php
// api/location_latest.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);

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

// Delivery info (pickup/dropoff coords if present)
$ds = $pdo->prepare("
  SELECT id, delivery_code, status,
         pickup_lat, pickup_lng, dropoff_lat, dropoff_lng
  FROM deliveries
  WHERE id = :id
  LIMIT 1
");
$ds->execute([':id' => $delivery_id]);
$delivery = $ds->fetch();

if (!$delivery) {
    http_response_code(404);
    echo json_encode(['ok' => false, 'error' => 'Delivery not found']);
    exit;
}

// Latest location
$ls = $pdo->prepare("
  SELECT lat, lng, accuracy_m, speed_mps, heading_deg, recorded_at
  FROM delivery_locations
  WHERE delivery_id = :id
  ORDER BY recorded_at DESC
  LIMIT 1
");
$ls->execute([':id' => $delivery_id]);
$loc = $ls->fetch();

echo json_encode([
    'ok' => true,
    'delivery' => [
        'id' => (int)$delivery['id'],
        'delivery_code' => $delivery['delivery_code'],
        'status' => $delivery['status'],
        'pickup_lat' => $delivery['pickup_lat'] !== null ? (float)$delivery['pickup_lat'] : null,
        'pickup_lng' => $delivery['pickup_lng'] !== null ? (float)$delivery['pickup_lng'] : null,
        'dropoff_lat' => $delivery['dropoff_lat'] !== null ? (float)$delivery['dropoff_lat'] : null,
        'dropoff_lng' => $delivery['dropoff_lng'] !== null ? (float)$delivery['dropoff_lng'] : null,
    ],
    'latest' => $loc ? [
        'lat' => (float)$loc['lat'],
        'lng' => (float)$loc['lng'],
        'accuracy_m' => $loc['accuracy_m'] !== null ? (float)$loc['accuracy_m'] : null,
        'speed_mps' => $loc['speed_mps'] !== null ? (float)$loc['speed_mps'] : null,
        'heading_deg' => $loc['heading_deg'] !== null ? (float)$loc['heading_deg'] : null,
        'recorded_at' => $loc['recorded_at'],
    ] : null
]);
