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

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

$pdo = db();
$driver_id = (int)$_SESSION['user']['id'];
$delivery_id = (int)($_GET['delivery_id'] ?? 0);

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

// Make sure delivery belongs to this driver
$stmt = $pdo->prepare("
    SELECT id, delivery_code, status, pickup_address, dropoff_address
    FROM deliveries
    WHERE id = :id AND assigned_driver_id = :driver
    LIMIT 1
");
$stmt->execute([
    ':id' => $delivery_id,
    ':driver' => $driver_id
]);

$delivery = $stmt->fetch(PDO::FETCH_ASSOC);

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

// Load items
$stmt = $pdo->prepare("
    SELECT p.name, di.quantity
    FROM delivery_items di
    JOIN products p ON p.id = di.product_id
    WHERE di.delivery_id = :id
");
$stmt->execute([':id' => $delivery_id]);

$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'ok' => true,
    'delivery' => $delivery,
    'items' => $items
]);
