<?php
namespace App\Http\Controllers\Admin\Inventory;
use App\Http\Controllers\Controller;
use App\Models\Inventory\InventoryCheck;
use App\Models\Inventory\Inventory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class InventoryCheckController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = InventoryCheck::query()
            ->with(['warehouse', 'operator'])
            ->when($request->warehouse_id, fn($q, $v) => $q->where('warehouse_id', $v))
            ->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([
            'check_no'     => 'required|string|max:50|unique:inventory_checks',
            'warehouse_id' => 'required|exists:warehouses,id',
            'items'        => 'nullable|array',
            'remark'       => 'nullable|string|max:500',
        ]);
        $v['status'] = 0;
        $v['operator_id'] = auth()->id();

        return $this->success(InventoryCheck::create($v));
    }

    public function show(InventoryCheck $inventoryCheck): JsonResponse
    {
        return $this->success($inventoryCheck->load(['warehouse', 'operator']));
    }

    /**
     * 完成盘点 — 可选择按实际数量修正库存
     */
    public function complete(InventoryCheck $inventoryCheck, Request $request): JsonResponse
    {
        if ($inventoryCheck->status === 2) {
            return $this->error('已完成', 40001);
        }

        $v = $request->validate([
            'items'         => 'nullable|array',
            'finish_remark' => 'nullable|string|max:500',
        ]);

        DB::transaction(function () use ($inventoryCheck, $v) {
            $items = $v['items'] ?? $inventoryCheck->items ?? [];

            // 如果有差异且需要调整库存
            foreach ($items as $item) {
                if (!isset($item['actual_qty'])) continue;
                $diff = ($item['actual_qty'] ?? 0) - ($item['book_qty'] ?? 0);
                if ($diff == 0) continue;

                $inv = Inventory::firstOrCreate(
                    ['warehouse_id' => $inventoryCheck->warehouse_id, 'material_id' => $item['material_id'], 'batch_no' => null],
                    ['quantity' => 0]
                );
                $inv->increment('quantity', $diff);
            }

            $inventoryCheck->update([
                'status'        => 2,
                'items'         => $items,
                'finish_remark' => $v['finish_remark'] ?? null,
            ]);
        });

        return $this->success($inventoryCheck->fresh(['warehouse']));
    }
}
