clientId = $clientId; $this->client = Client::findOrFail($clientId); $this->contactId = null; $this->isPrimary = !$this->client->contacts()->exists(); $this->resetValidation(); Flux::modal('add-contact')->show(); } #[Computed] public function availableContacts() { if (!$this->client) { return collect(); } $existingContactIds = $this->client->contacts()->pluck('contacts.id'); return Contact::whereNotIn('id', $existingContactIds) ->orderBy('last_name') ->orderBy('first_name') ->get(); } public function openCreateModal(): void { $this->first_name = ''; $this->last_name = ''; $this->email = ''; $this->phone = ''; $this->newContactIsPrimary = !$this->client->contacts()->exists(); $this->resetValidation(); Flux::modal('add-contact')->close(); Flux::modal('create-client-contact')->show(); } public function backToSelect(): void { Flux::modal('create-client-contact')->close(); Flux::modal('add-contact')->show(); } public function attachContact(): void { if (!$this->contactId) { return; } if ($this->isPrimary) { $this->client->contacts()->updateExistingPivot( $this->client->contacts()->wherePivot('is_primary', true)->pluck('contacts.id'), ['is_primary' => false] ); } $this->client->contacts()->attach($this->contactId, ['is_primary' => $this->isPrimary]); $this->reset(['clientId', 'client', 'contactId', 'isPrimary']); Flux::modal('add-contact')->close(); $this->dispatch('client-updated'); } public function createAndAttach(): void { $this->validate([ 'first_name' => 'required|string|max:255', 'last_name' => 'required|string|max:255', 'email' => 'required|email|max:255|unique:contacts,email', 'phone' => 'nullable|string|max:20', ]); $contact = Contact::create([ 'first_name' => $this->first_name, 'last_name' => $this->last_name, 'email' => $this->email, 'phone' => $this->phone ?: null, ]); if ($this->newContactIsPrimary) { $this->client->contacts()->updateExistingPivot( $this->client->contacts()->wherePivot('is_primary', true)->pluck('contacts.id'), ['is_primary' => false] ); } $this->client->contacts()->attach($contact->id, ['is_primary' => $this->newContactIsPrimary]); $this->reset(['clientId', 'client', 'contactId', 'isPrimary', 'first_name', 'last_name', 'email', 'phone', 'newContactIsPrimary']); Flux::modal('create-client-contact')->close(); $this->dispatch('client-updated'); $this->dispatch('contact-created'); } #[Computed] public function clientHasContacts(): bool { return $this->client?->contacts()->exists() ?? false; } }; ?>