<?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);

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

    $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;
    }

    $latest = delivery_latest_location($pdo, $deliveryId);
    $routeStats = delivery_route_stats($pdo, $deliveryId);

    echo json_encode([
        'ok' => true,
        'delivery' => [
            'id' => (int)$delivery['id'],
            'delivery_code' => (string)$delivery['delivery_code'],
            'status' => (string)$delivery['status'],
            'pickup_address' => (string)($delivery['pickup_address'] ?? ''),
            'dropoff_address' => (string)($delivery['dropoff_address'] ?? ''),
            '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,
            'assigned_driver_id' => $delivery['assigned_driver_id'] !== null ? (int)$delivery['assigned_driver_id'] : null,
            'driver_name' => $delivery['driver_name'] ?? null,
            'scheduled_at' => $delivery['scheduled_at'] ?? null,
        ],
        'latest' => $latest ? [
            'lat' => (float)$latest['lat'],
            'lng' => (float)$latest['lng'],
            'accuracy_m' => $latest['accuracy_m'] !== null ? (float)$latest['accuracy_m'] : null,
            'speed_mps' => $latest['speed_mps'] !== null ? (float)$latest['speed_mps'] : null,
            'heading_deg' => $latest['heading_deg'] !== null ? (float)$latest['heading_deg'] : null,
            'recorded_at' => $latest['recorded_at'],
        ] : null,
        'route_stats' => $routeStats,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
