<?php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['driver']);

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

try {
    $pdo = db();
    $user = current_user();
    $driver_id = (int)($user['id'] ?? 0);
    $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;
    }

    $stmt = $pdo->prepare("\n        SELECT\n            d.id,\n            d.delivery_code,\n            d.status,\n            d.pickup_address,\n            d.dropoff_address,\n            d.pickup_lat,\n            d.pickup_lng,\n            d.dropoff_lat,\n            d.dropoff_lng,\n            d.scheduled_at,\n            d.picked_up_at,\n            d.delivered_at,\n            c.name AS customer_name\n        FROM deliveries d\n        LEFT JOIN customers c ON c.id = d.customer_id\n        WHERE d.id = :id AND d.assigned_driver_id = :driver\n        LIMIT 1\n    ");
    $stmt->execute([
        ':id' => $delivery_id,
        ':driver' => $driver_id,
    ]);
    $delivery = $stmt->fetch(PDO::FETCH_ASSOC);

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

    $itemsStmt = $pdo->prepare("\n        SELECT\n            di.id,\n            di.product_id,\n            di.quantity,\n            di.unit_price,\n            p.sku,\n            p.name\n        FROM delivery_items di\n        JOIN products p ON p.id = di.product_id\n        WHERE di.delivery_id = :id\n        ORDER BY p.name ASC, di.id ASC\n    ");
    $itemsStmt->execute([':id' => $delivery_id]);
    $items = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);

    $gpsStmt = $pdo->prepare("\n        SELECT lat, lng, accuracy_m, speed_mps, heading_deg, recorded_at\n        FROM delivery_locations\n        WHERE delivery_id = :id\n        ORDER BY recorded_at DESC, id DESC\n        LIMIT 1\n    ");
    $gpsStmt->execute([':id' => $delivery_id]);
    $lastGps = $gpsStmt->fetch(PDO::FETCH_ASSOC) ?: null;

    $responseDelivery = [
        'id' => (int)$delivery['id'],
        'delivery_code' => $delivery['delivery_code'],
        'status' => $delivery['status'],
        'pickup_address' => $delivery['pickup_address'],
        'dropoff_address' => $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,
        'scheduled_at' => $delivery['scheduled_at'],
        'picked_up_at' => $delivery['picked_up_at'],
        'delivered_at' => $delivery['delivered_at'],
        'customer_name' => $delivery['customer_name'],
    ];

    $responseItems = array_map(static function (array $item): array {
        return [
            'id' => (int)$item['id'],
            'product_id' => (int)$item['product_id'],
            'sku' => (string)$item['sku'],
            'name' => (string)$item['name'],
            'quantity' => (int)$item['quantity'],
            'unit_price' => $item['unit_price'] !== null ? (float)$item['unit_price'] : null,
        ];
    }, $items);

    $responseGps = null;
    if ($lastGps) {
        $responseGps = [
            'lat' => (float)$lastGps['lat'],
            'lng' => (float)$lastGps['lng'],
            'accuracy_m' => $lastGps['accuracy_m'] !== null ? (float)$lastGps['accuracy_m'] : null,
            'speed_mps' => $lastGps['speed_mps'] !== null ? (float)$lastGps['speed_mps'] : null,
            'heading_deg' => $lastGps['heading_deg'] !== null ? (float)$lastGps['heading_deg'] : null,
            'recorded_at' => $lastGps['recorded_at'],
        ];
    }

    echo json_encode([
        'ok' => true,
        'delivery' => $responseDelivery,
        'items' => $responseItems,
        'last_gps' => $responseGps,
    ]);
    exit;

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
    exit;
}
