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

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

try {
    $pdo = db();
    $user = current_user();
    $driverId = (int)($user['id'] ?? 0);
    $deliveryId = (int)($_GET['delivery_id'] ?? 0);

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

    $stmt = $pdo->prepare("\n        SELECT d.id\n        FROM deliveries d\n        WHERE d.id = :id\n          AND d.assigned_driver_id = :driver_id\n        LIMIT 1\n    ");
    $stmt->execute([
        ':id' => $deliveryId,
        ':driver_id' => $driverId,
    ]);
    if (!$stmt->fetch(PDO::FETCH_ASSOC)) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'Delivery not found or not assigned to this driver']);
        exit;
    }

    $delivery = delivery_load($pdo, $deliveryId);
    $items = delivery_items($pdo, $deliveryId);
    $latestGps = delivery_latest_location($pdo, $deliveryId);
    $routeStats = delivery_route_stats($pdo, $deliveryId);

    $proofCountStmt = $pdo->prepare('SELECT COUNT(*) FROM delivery_proofs WHERE delivery_id = :delivery_id');
    $proofCountStmt->execute([':delivery_id' => $deliveryId]);
    $proofCount = (int)$proofCountStmt->fetchColumn();

    $latestProofStmt = $pdo->prepare("\n        SELECT photo_path, signature_path, notes, created_at\n        FROM delivery_proofs\n        WHERE delivery_id = :delivery_id\n        ORDER BY created_at DESC, id DESC\n        LIMIT 1\n    ");
    $latestProofStmt->execute([':delivery_id' => $deliveryId]);
    $latestProof = $latestProofStmt->fetch(PDO::FETCH_ASSOC) ?: null;

    $deliveryStatus = (string)($delivery['status'] ?? 'PENDING');
    $nextStop = $deliveryStatus === 'DELIVERED'
        ? null
        : (($deliveryStatus === 'PICKED_UP' || $deliveryStatus === 'IN_TRANSIT') ? 'dropoff' : 'pickup');

    echo json_encode([
        'ok' => true,
        'delivery' => [
            'id' => (int)$delivery['id'],
            'delivery_code' => (string)$delivery['delivery_code'],
            'status' => $deliveryStatus,
            '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,
            'notes' => $delivery['notes'] ?? null,
            'scheduled_at' => $delivery['scheduled_at'] ?? null,
            'picked_up_at' => $delivery['picked_up_at'] ?? null,
            'in_transit_at' => $delivery['in_transit_at'] ?? null,
            'delivered_at' => $delivery['delivered_at'] ?? null,
            'customer_name' => $delivery['customer_name'] ?? null,
            'driver_name' => $delivery['driver_name'] ?? null,
            'next_stop' => $nextStop,
            'stock_released' => delivery_stock_already_deducted($pdo, $deliveryId),
        ],
        'items' => 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'],
                'unit' => (string)($item['unit'] ?? ''),
                'barcode_value' => $item['barcode_value'] !== null ? (string)$item['barcode_value'] : null,
                'quantity' => (int)$item['quantity'],
                'current_stock' => (int)($item['current_stock'] ?? 0),
                'unit_price' => $item['unit_price'] !== null ? (float)$item['unit_price'] : null,
            ];
        }, $items),
        'last_gps' => $latestGps ? [
            'lat' => (float)$latestGps['lat'],
            'lng' => (float)$latestGps['lng'],
            'accuracy_m' => $latestGps['accuracy_m'] !== null ? (float)$latestGps['accuracy_m'] : null,
            'speed_mps' => $latestGps['speed_mps'] !== null ? (float)$latestGps['speed_mps'] : null,
            'heading_deg' => $latestGps['heading_deg'] !== null ? (float)$latestGps['heading_deg'] : null,
            'recorded_at' => $latestGps['recorded_at'],
        ] : null,
        'route_stats' => $routeStats,
        'proof_count' => $proofCount,
        'latest_proof' => $latestProof,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
