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

class PurchaseOrderController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = PurchaseOrder::query()->with(['supplier','auditor']);
        $query->when($request->order_no, fn($q, $v) => $q->where('order_no', 'like', "%{$v}%"));
        $query->when($request->supplier_id, fn($q, $v) => $q->where('supplier_id', $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(['order_no'=>'required|string|max:50|unique:purchase_orders','supplier_id'=>'nullable|exists:suppliers,id','total_amount'=>'nullable|numeric|min:0','items'=>'nullable|array','remark'=>'nullable|string']);
        $v['status'] = 0; $v['created_by'] = auth()->id();
        return $this->success(PurchaseOrder::create($v));
    }
    public function show(PurchaseOrder $purchaseOrder): JsonResponse { return $this->success($purchaseOrder->load(['supplier','auditor','creator'])); }
    public function update(Request $request, PurchaseOrder $purchaseOrder): JsonResponse
    {
        if ($purchaseOrder->status >= 2) return $this->error('已审批的采购单不可修改', 40001);
        $v = $request->validate(['supplier_id'=>'nullable|exists:suppliers,id','total_amount'=>'nullable|numeric|min:0','items'=>'nullable|array','remark'=>'nullable|string']);
        $purchaseOrder->update($v);
        return $this->success($purchaseOrder);
    }
    public function audit(Request $request, PurchaseOrder $purchaseOrder): JsonResponse
    {
        if ($purchaseOrder->status >= 2) return $this->error('已审批', 40001);
        $v = $request->validate(['status'=>'required|integer|in:2,4']);
        $purchaseOrder->update(['status'=>$v['status'],'audit_user_id'=>auth()->id(),'audit_at'=>now()]);
        return $this->success($purchaseOrder);
    }
    public function destroy(PurchaseOrder $purchaseOrder): JsonResponse
    {
        if ($purchaseOrder->status >= 2) return $this->error('已审批不可删除', 40001);
        $purchaseOrder->delete(); return $this->success(null);
    }
}
