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

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

$pdo = db();
$data = json_decode(file_get_contents('php://input'), true);

$delivery_id = (int)($data['delivery_id'] ?? 0);
$status = $data['status'] ?? '';

$allowed = ['PICKED_UP', 'IN_TRANSIT', 'DELIVERED'];

if ($delivery_id <= 0 || !in_array($status, $allowed)) {
    echo json_encode(['ok' => false, 'error' => 'Invalid request']);
    exit;
}

// Update only if assigned to this driver
$stmt = $pdo->prepare("
    UPDATE deliveries
    SET status = :status,
        picked_up_at = IF(:status='PICKED_UP', NOW(), picked_up_at),
        delivered_at = IF(:status='DELIVERED', NOW(), delivered_at)
    WHERE id = :id AND assigned_driver_id = :driver
");
$stmt->execute([
    ':status' => $status,
    ':id' => $delivery_id,
    ':driver' => $_SESSION['user']['id']
]);

if ($stmt->rowCount() === 0) {
    echo json_encode(['ok' => false, 'error' => 'Update failed']);
    exit;
}

echo json_encode(['ok' => true]);
