
    /**
     * Get active box reservations for order preparation
     */
    public function getBoxReservations()
    {
        $reservations = BoxReservation::with(['client', 'items'])
            ->whereIn('status', ['pending', 'in_progress'])
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($reservation) {
                return [
                    'id' => $reservation->id,
                    'reservation_code' => $reservation->reservation_code,
                    'client_name' => $reservation->client->client_name,
                    'client_id' => $reservation->client_id,
                    'status' => $reservation->status,
                    'total_boxes' => $reservation->total_boxes,
                    'confirmed_boxes' => $reservation->confirmed_boxes,
                    'pending_boxes' => $reservation->pending_boxes,
                    'completion_percentage' => $reservation->completion_percentage,
                    'created_at' => $reservation->created_at->format('Y-m-d H:i'),
                ];
            });

        return response()->json($reservations);
    }

    /**
     * Start processing a box reservation
     */
    public function startBoxReservation(Request $request)
    {
        $request->validate([
            'reservation_id' => 'required|exists:box_reservations,id',
        ]);

        $reservation = BoxReservation::with(['client', 'items.inventory'])->findOrFail($request->reservation_id);

        // Update status to in_progress if pending
        if ($reservation->isPending()) {
            $reservation->update(['status' => 'in_progress']);
        }

        // Get all reservation items with inventory details
        $boxes = $reservation->items->map(function ($item) {
            return [
                'id' => $item->id,
                'box_number' => $item->box_number,
                'quantity' => $item->quantity,
                'status' => $item->status,
                'scanned_at' => $item->scanned_at?->format('Y-m-d H:i:s'),
                'inventory' => [
                    'id' => $item->inventory->id,
                    'mocaco' => $item->inventory->mocaco,
                    'marca' => $item->inventory->cadena,
                    'seccion' => $item->inventory->seccion,
                    'familia' => $item->inventory->familia_articulo_description,
                    'ubicacion' => $item->inventory->ubicacion,
                ],
            ];
        });

        return response()->json([
            'reservation' => [
                'id' => $reservation->id,
                'reservation_code' => $reservation->reservation_code,
                'client_name' => $reservation->client->client_name,
                'client_id' => $reservation->client_id,
                'status' => $reservation->status,
                'notes' => $reservation->notes,
            ],
            'boxes' => $boxes,
            'stats' => [
                'total' => $reservation->total_boxes,
                'confirmed' => $reservation->confirmed_boxes,
                'pending' => $reservation->pending_boxes,
            ],
        ]);
    }

    /**
     * Confirm a scanned box from reservation
     */
    public function confirmBoxReservationScan(Request $request)
    {
        $request->validate([
            'reservation_id' => 'required|exists:box_reservations,id',
            'box_number' => 'required|string',
        ]);

        $reservation = BoxReservation::findOrFail($request->reservation_id);
        $boxNumber = trim($request->box_number);

        // Check if box is in this reservation
        $reservationItem = BoxReservationItem::where('reservation_id', $reservation->id)
            ->where('box_number', $boxNumber)
            ->where('status', 'reserved')
            ->first();

        if ($reservationItem) {
            // Box is in reservation - confirm it
            $reservationItem->confirm();

            return response()->json([
                'status' => 'confirmed',
                'message' => 'Caja confirmada correctamente',
                'is_from_reservation' => true,
                'item' => $reservationItem,
                'stats' => [
                    'total' => $reservation->fresh()->total_boxes,
                    'confirmed' => $reservation->fresh()->confirmed_boxes,
                    'pending' => $reservation->fresh()->pending_boxes,
                ],
            ]);
        }

        // Box not in reservation - check if it's available
        $inventory = Inventory::where('n_carton', $boxNumber)
            ->where('reservation_status', 'available')
            ->first();

        if ($inventory) {
            return response()->json([
                'status' => 'not_in_reservation',
                'message' => '¿Desea agregar esta caja a la reserva?',
                'box' => [
                    'n_carton' => $inventory->n_carton,
                    'marca' => $inventory->cadena,
                    'seccion' => $inventory->seccion,
                    'ubicacion' => $inventory->ubicacion,
                ],
                'is_from_reservation' => false,
            ]);
        }

        return response()->json([
            'status' => 'error',
            'message' => 'Caja no encontrada o no disponible',
        ], 404);
    }

    /**
     * Add extra box to reservation (not originally in the list)
     */
    public function addExtraBoxToReservation(Request $request)
    {
        $request->validate([
            'reservation_id' => 'required|exists:box_reservations,id',
            'box_number' => 'required|string',
        ]);

        DB::beginTransaction();

        try {
            $reservation = BoxReservation::findOrFail($request->reservation_id);
            $boxNumber = trim($request->box_number);

            // Find available inventory
            $inventory = Inventory::where('n_carton', $boxNumber)
                ->where('reservation_status', 'available')
                ->firstOrFail();

            // Create reservation item
            $item = BoxReservationItem::create([
                'reservation_id' => $reservation->id,
                'inventory_id' => $inventory->id,
                'box_number' => $boxNumber,
                'quantity' => 1,
                'status' => 'confirmed',
                'scanned_at' => now(),
                'notes' => 'Agregada por operario durante confirmación',
            ]);

            // Update inventory
            $inventory->update([
                'reservation_status' => 'confirmed',
                'reserved_for_client_id' => $reservation->client_id,
                'reservation_id' => $reservation->id,
            ]);

            DB::commit();

            return response()->json([
                'status' => 'added',
                'message' => 'Caja agregada a la reserva',
                'item' => $item,
                'stats' => [
                    'total' => $reservation->fresh()->total_boxes,
                    'confirmed' => $reservation->fresh()->confirmed_boxes,
                    'pending' => $reservation->fresh()->pending_boxes,
                ],
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error adding extra box to reservation', [
                'reservation_id' => $request->reservation_id,
                'box_number' => $request->box_number,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'status' => 'error',
                'message' => 'Error al agregar caja: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Complete box reservation and create order
     */
    public function completeBoxReservation(Request $request)
    {
        $request->validate([
            'reservation_id' => 'required|exists:box_reservations,id',
        ]);

        DB::beginTransaction();

        try {
            $reservation = BoxReservation::with(['items.inventory', 'client'])->findOrFail($request->reservation_id);

            // Validate that at least one box is confirmed
            if ($reservation->confirmed_boxes == 0) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Debe confirmar al menos una caja antes de completar la reserva',
                ], 400);
            }

            // Generate order number
            $lastOrder = Order::orderBy('id', 'desc')->first();
            $orderNumber = 'ORD-' . date('Ymd') . '-' . str_pad(($lastOrder?->id ?? 0) + 1, 4, '0', STR_PAD_LEFT);

            // Create order
            $order = Order::create([
                'client_id' => $reservation->client_id,
                'user_id' => Auth::id(),
                'operario_id' => Auth::user()->operario_id ?? Auth::user()->name,
                'order_number' => $orderNumber,
                'status' => 'dispatched',
                'order_date' => now(),
                'dispatched_at' => now(),
                'notes' => "Creado desde reserva {$reservation->reservation_code}",
            ]);

            // Get all confirmed items
            $confirmedItems = $reservation->items()->where('status', 'confirmed')->get();

            foreach ($confirmedItems as $item) {
                // Create order item
                OrderItem::create([
                    'order_id' => $order->id,
                    'inventory_id' => $item->inventory_id,
                    'full_barcode' => $item->inventory->full_barcode,
                    'mocaco' => $item->inventory->mocaco,
                    'n_carton' => $item->box_number,
                ]);

                // Update inventory status to dispatched
                $item->inventory->update([
                    'status' => 'Despachado',
                    'client_id' => $reservation->client_id,
                    'order_id' => $order->id,
                ]);

                // Log audit
                AuditLog::logAction(
                    'dispatch_inventory',
                    $item->inventory,
                    Auth::user(),
                    ['status' => 'confirmed'],
                    ['status' => 'Despachado'],
                    "Despachado en orden {$orderNumber} desde reserva {$reservation->reservation_code}"
                );
            }

            // Update reservation status
            $reservation->update([
                'status' => 'completed',
                'confirmed_by_user_id' => Auth::id(),
                'confirmed_at' => now(),
            ]);

            // Log reservation completion
            AuditLog::logAction(
                'complete_reservation',
                $reservation,
                Auth::user(),
                ['status' => $reservation->getOriginal('status')],
                ['status' => 'completed'],
                "Reserva completada. Orden {$orderNumber} creada con {$confirmedItems->count()} cajas"
            );

            DB::commit();

            return response()->json([
                'status' => 'completed',
                'message' => "Reserva completada. Orden {$orderNumber} creada con {$confirmedItems->count()} cajas",
                'order' => [
                    'id' => $order->id,
                    'order_number' => $orderNumber,
                    'client_name' => $reservation->client->client_name,
                    'total_boxes' => $confirmedItems->count(),
                ],
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error completing box reservation', [
                'reservation_id' => $request->reservation_id,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'status' => 'error',
                'message' => 'Error al completar reserva: ' . $e->getMessage(),
            ], 500);
        }
    }
}
