Employee::where('status', 'active')->orderBy('name')->get(), 'variants' => StockVariant::with('item')->where('quantity', '>', 0)->orderBy('size')->get()->sortBy('item.name'), 'issues' => UniformIssue::with(['employee', 'variant.item'])->latest('issued_at')->paginate(15), ]); } public function store(Request $request) { $data = $request->validate([ 'employee_id' => ['required', 'exists:employees,id'], 'stock_variant_id' => ['required', 'exists:stock_variants,id'], 'quantity' => ['required', 'integer', 'min:1'], 'issued_at' => ['required', 'date'], 'notes' => ['nullable', 'string', 'max:500'], ]); DB::transaction(function () use ($data) { $employee = Employee::lockForUpdate()->findOrFail($data['employee_id']); if ($employee->status !== 'active') { throw ValidationException::withMessages(['employee_id' => 'Uniforms can only be issued to active employees.']); } $variant = StockVariant::lockForUpdate()->findOrFail($data['stock_variant_id']); if ($variant->quantity < $data['quantity']) { throw ValidationException::withMessages(['quantity' => "Only {$variant->quantity} item(s) are available in this size."]); } $issue = UniformIssue::create($data); $variant->decrement('quantity', $data['quantity']); StockMovement::create([ 'stock_variant_id' => $variant->id, 'employee_id' => $employee->id, 'uniform_issue_id' => $issue->id, 'type' => 'issue', 'quantity_change' => -$data['quantity'], 'notes' => "Issued to {$employee->name}", ]); }); return back()->with('success', 'Uniform issued and stock adjusted.'); } }