validate([ 'status' => ['nullable', 'in:active,maintenance,retired'], 'q' => ['nullable', 'string', 'max:100'], 'per_page' => ['nullable', 'integer', 'min:1', 'max:500'], ]); $perPage = (int) $request->input('per_page', 25); $trucks = Truck::query() ->when($request->filled('status'), fn ($q) => $q->where('status', $request->string('status'))) ->when($request->filled('q'), function ($q) use ($request) { $term = '%'.$request->string('q').'%'; $q->where(fn ($qq) => $qq->where('plate_number', 'like', $term)->orWhere('model', 'like', $term)); }) ->orderBy('plate_number') ->paginate($perPage); return $this->ok( TruckResource::collection($trucks), null, [ 'page' => $trucks->currentPage(), 'per_page' => $trucks->perPage(), 'total' => $trucks->total(), 'last_page' => $trucks->lastPage(), ], ); } public function store(StoreTruckRequest $request): JsonResponse { $truck = Truck::create($request->validated()); return $this->created(new TruckResource($truck), 'Truck created'); } public function show(Truck $truck): JsonResponse { return $this->ok(new TruckResource($truck)); } public function update(StoreTruckRequest $request, Truck $truck): JsonResponse { $validated = $request->validated(); $oldStatus = $truck->status; $newStatus = $validated['status'] ?? $oldStatus; DB::transaction(function () use ($truck, $validated, $oldStatus, $newStatus) { $truck->update($validated); if ($newStatus !== Truck::STATUS_ACTIVE && $oldStatus === Truck::STATUS_ACTIVE) { // 1. Cancel active/scheduled trips $trips = Trip::where('truck_id', $truck->id) ->whereIn('status', [Trip::STATUS_SCHEDULED, Trip::STATUS_IN_PROGRESS, Trip::STATUS_AT_DUMPSITE]) ->get(); foreach ($trips as $trip) { $trip->update([ 'status' => Trip::STATUS_CANCELLED, 'notes' => trim(($trip->notes ?? '')."\nSystem: Trip cancelled because the truck was moved to ".$newStatus.' status.'), ]); } // 2. Unassign from collection teams CollectionTeam::where('truck_id', $truck->id) ->update(['truck_id' => null]); } }); return $this->ok(new TruckResource($truck->fresh()), 'Truck updated'); } public function destroy(Truck $truck): JsonResponse { $truck->delete(); return $this->ok(null, 'Truck deleted'); } }