with(['user', 'profileMedia']) ->orderBy("created_at", "desc") ->get(); return $providers; } public function findById(int $id): ?Provider { return Provider::with(['user', 'profileMedia'])->find($id); } public function create(array $data): Provider { return Provider::create($data); } public function update(int $id, array $data): ?Provider { $model = $this->findById($id); if (!$model) { return null; } $model->update($data); return $model->fresh(['user', 'profileMedia']); } public function delete(int $id): bool { $model = $this->findById($id); if (!$model) { return false; } return $model->delete(); } public function register(array $data): ?array { try { DB::beginTransaction(); $user = User::when($data['email'], function ($q) use ($data) { $q->where('email', $data['email']); }) ->when($data['phone'], function ($q) use ($data) { $q->where('phone', $data['phone']); }) ->where('type', 'PROVIDER') ->where('code', $data['code']) ->where('validated_code', false) ->first(); if(!$user) { throw new \Exception(__('messages.user_not_found_or_code_not_validated')); } $user->name = $data['name']; $user->save(); $provider = new Provider(); $provider->user_id = $user->id; $provider->rg = $data['document']; $provider->document = $data['document']; $provider->save(); $provider->refresh(); $address = new Address(); $address->source = 'client'; $address->source_id = $provider->id; $address->zip_code = $data['zip_code'] ?? null; $address->address = $data['address'] ?? null; $address->has_complement = $data['has_complement'] ?? null; $address->nickname = $data['nickname'] ?? null; $address->instructions = $data['instructions'] ?? null; $address->address_type = $data['address_type'] ?? null; $state = State::where('code', $data['state'])->first(); $city = City::where('name', $data['city'])->where('state_id', $state->id)->first(); $address->state_id = $state->id; $address->city_id = $city->id; $address->save(); $result = $this->authService->loginWithEmail( email: $user->email, code: $user->code, ); DB::commit(); return $result; } catch (\Exception $e) { DB::rollBack(); Log::error("Error registering client: " . $e->getMessage()); throw $e; } } }