<?php
require_once __DIR__ . '/../helpers/auth.php';
require_once __DIR__ . '/../helpers/audit.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);

    $payload = json_decode(file_get_contents('php://input'), true);
    if (!is_array($payload)) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid JSON']);
        exit;
    }

    $deliveryId = (int)($payload['delivery_id'] ?? 0);
    $newStatus = strtoupper(trim((string)($payload['status'] ?? '')));
    $allowed = ['PICKED_UP', 'IN_TRANSIT', 'DELIVERED'];

    if ($deliveryId <= 0 || !in_array($newStatus, $allowed, true)) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid delivery or status']);
        exit;
    }

    $delivery = delivery_load($pdo, $deliveryId);
    if (!$delivery || (int)($delivery['assigned_driver_id'] ?? 0) !== $driverId) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'Delivery not found or not assigned to you']);
        exit;
    }

    $currentStatus = strtoupper((string)($delivery['status'] ?? 'PENDING'));
    if ($currentStatus === 'CANCELLED') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Cancelled deliveries cannot be updated']);
        exit;
    }

    $statusOrder = [
        'PENDING' => 0,
        'ASSIGNED' => 1,
        'PICKED_UP' => 2,
        'IN_TRANSIT' => 3,
        'DELIVERED' => 4,
    ];
    if (isset($statusOrder[$currentStatus], $statusOrder[$newStatus]) && $statusOrder[$newStatus] < $statusOrder[$currentStatus]) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Status cannot move backward from ' . $currentStatus . ' to ' . $newStatus]);
        exit;
    }

    $result = delivery_update_status($pdo, $deliveryId, $newStatus, $driverId);
    $updatedDelivery = $result['delivery'] ?? delivery_load($pdo, $deliveryId);

    audit_log(
        'DRIVER_UPDATE_STATUS',
        'deliveries',
        (string)$deliveryId,
        json_encode([
            'driver_id' => $driverId,
            'status' => $newStatus,
            'stock_deducted' => !empty($result['stock_deducted']),
        ], JSON_UNESCAPED_SLASHES)
    );

    echo json_encode([
        'ok' => true,
        'status' => $updatedDelivery['status'] ?? $newStatus,
        'picked_up_at' => $updatedDelivery['picked_up_at'] ?? null,
        'in_transit_at' => $updatedDelivery['in_transit_at'] ?? null,
        'delivered_at' => $updatedDelivery['delivered_at'] ?? null,
        'stock_deducted' => !empty($result['stock_deducted']),
        'updated_at' => date('Y-m-d H:i:s'),
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
