<?php
namespace App\Http\Controllers\Admin\Inventory;
use App\Http\Controllers\Controller;
use App\Models\Inventory\StockMovement;
use App\Models\Inventory\Inventory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class StockMovementController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = StockMovement::query()->with('warehouse');
        $query->when($request->warehouse_id, fn($q, $v) => $q->where('warehouse_id', $v));
        $query->when($request->type, fn($q, $v) => $q->where('type', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));
        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }
    public function store(Request $request): JsonResponse
    {
        $v = $request->validate([
            'warehouse_id'=>'required|exists:warehouses,id','movement_no'=>'required|string|max:50|unique:stock_movements',
            'type'=>'required|integer|in:1,2,3,4','direction'=>'nullable|integer|in:1,2',
            'items'=>'nullable|array','related_order'=>'nullable|string|max:50','remark'=>'nullable|string',
        ]);
        $v['status'] = 0; $v['operator_id'] = auth()->id();
        return $this->success(StockMovement::create($v));
    }
    public function show(StockMovement $stockMovement): JsonResponse { return $this->success($stockMovement->load(['warehouse','operator'])); }
    public function confirm(StockMovement $stockMovement): JsonResponse
    {
        if ($stockMovement->status === 1) return $this->error('已确认', 40001);
        $stockMovement->update(['status' => 1]);
        // 更新库存
        if ($stockMovement->items) {
            foreach ($stockMovement->items as $item) {
                $inv = Inventory::firstOrCreate(
                    ['warehouse_id'=>$stockMovement->warehouse_id,'material_id'=>$item['material_id'],'batch_no'=>$item['batch_no']??null],
                    ['quantity'=>0]
                );
                $qty = $item['quantity'] ?? 0;
                $inv->quantity = $stockMovement->direction === 1 ? $inv->quantity + $qty : $inv->quantity - $qty;
                $inv->save();
            }
        }
        return $this->success($stockMovement);
    }
}
