<?php
require_once __DIR__ . '/../helpers/auth.php';
require_once __DIR__ . '/../helpers/inventory.php';
require_login();

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

try {
    $pdo = db();
    $user = current_user();
    $role = (string)($user['role_name'] ?? '');
    $deliveryId = (int)($_GET['delivery_id'] ?? 0);
    $limit = (int)($_GET['limit'] ?? 120);

    if ($deliveryId <= 0) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid delivery ID']);
        exit;
    }
    if ($limit < 5) {
        $limit = 5;
    }
    if ($limit > 500) {
        $limit = 500;
    }

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

    $isDriverOwner = $role === 'driver' && (int)($delivery['assigned_driver_id'] ?? 0) === (int)($user['id'] ?? 0);
    if (!in_array($role, ['admin', 'staff'], true) && !$isDriverOwner) {
        http_response_code(403);
        echo json_encode(['ok' => false, 'error' => 'Forbidden']);
        exit;
    }

    $stmt = $pdo->prepare("\n        SELECT id, delivery_id, driver_id, lat, lng, accuracy_m, speed_mps, heading_deg, recorded_at\n        FROM delivery_locations\n        WHERE delivery_id = :delivery_id\n        ORDER BY recorded_at DESC, id DESC\n        LIMIT {$limit}\n    ");
    $stmt->execute([':delivery_id' => $deliveryId]);
    $rows = array_reverse($stmt->fetchAll(PDO::FETCH_ASSOC));

    echo json_encode([
        'ok' => true,
        'delivery_id' => $deliveryId,
        'points' => array_map(static function (array $row): array {
            return [
                'id' => (int)$row['id'],
                'delivery_id' => (int)$row['delivery_id'],
                'driver_id' => $row['driver_id'] !== null ? (int)$row['driver_id'] : null,
                'lat' => (float)$row['lat'],
                'lng' => (float)$row['lng'],
                'accuracy_m' => $row['accuracy_m'] !== null ? (float)$row['accuracy_m'] : null,
                'speed_mps' => $row['speed_mps'] !== null ? (float)$row['speed_mps'] : null,
                'heading_deg' => $row['heading_deg'] !== null ? (float)$row['heading_deg'] : null,
                'recorded_at' => $row['recorded_at'],
            ];
        }, $rows),
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
