<?php namespace App\Http\Controllers; use App\Models\{Asset,AssetAssignment}; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class AssetLifecycleController extends Controller {public function assign(Request $r,Asset $asset){$d=$r->validate(['user_id'=>'required|exists:users,id','issue_condition'=>'nullable|string|max:120']);DB::transaction(function()use($r,$asset,$d){abort_if($asset->status==='assigned',422,'Asset is already assigned.');AssetAssignment::create(['asset_id'=>$asset->id,'user_id'=>$d['user_id'],'issued_at'=>now(),'issue_condition'=>$d['issue_condition']??null,'issued_by'=>$r->user()->id]);$asset->update(['assigned_user_id'=>$d['user_id'],'issued_at'=>now(),'returned_at'=>null,'status'=>'assigned']);});return back()->with('success','Asset assigned.');}public function returnAsset(Request $r,Asset $asset){$d=$r->validate(['return_condition'=>'nullable|string|max:120','damage_notes'=>'nullable|string|max:2000','recovery_amount'=>'nullable|numeric|min:0']);DB::transaction(function()use($r,$asset,$d){$a=AssetAssignment::where('asset_id',$asset->id)->whereNull('returned_at')->latest()->firstOrFail();$a->update(['returned_at'=>now(),'return_condition'=>$d['return_condition']??null,'damage_notes'=>$d['damage_notes']??null,'recovery_amount'=>$d['recovery_amount']??0,'received_by'=>$r->user()->id]);$asset->update(['assigned_user_id'=>null,'returned_at'=>now(),'condition'=>$d['return_condition']??$asset->condition,'status'=>($d['damage_notes']??null)?'maintenance':'available']);});return back()->with('success','Asset returned.');}}