'whatsapp', 'instagram_url' => 'instagram', 'facebook_url' => 'facebook', ]; public function activeForTenant(Tenant $tenant): Event { return $tenant->events() ->whereKey($tenant->active_event_id) ->with(['dates', 'tenant.socialMedia']) ->firstOrFail(); } /** @param array $data */ public function updateActiveForTenant(Tenant $tenant, array $data): Event { return DB::transaction(function () use ($tenant, $data): Event { $tenant = Tenant::query()->whereKey($tenant->getKey())->lockForUpdate()->firstOrFail(); $event = $tenant->active_event_id === null ? $tenant->events()->create([ 'name' => $data['title'], 'address' => $data['location'], ]) : $tenant->events() ->whereKey($tenant->active_event_id) ->lockForUpdate() ->firstOrFail(); $event->update([ 'name' => $data['title'], 'address' => $data['location'], ]); if ($tenant->active_event_id === null) { $tenant->update(['active_event_id' => $event->id]); } $this->syncDates($event, $data['dates']); if (array_key_exists('social_media', $data)) { $this->syncSocialMedia($tenant, $data['social_media']); } else { $this->syncLegacyContact($tenant, $data['contact']); } return $event->load(['dates', 'tenant.socialMedia']); }); } /** @param array $dates */ private function syncDates(Event $event, array $dates): void { $existingDates = $event->dates()->get()->values(); foreach (array_values($dates) as $index => $date) { $attributes = [ 'date' => $date['date'], 'time_start' => $date['start_time'], 'time_end' => $date['end_time'], ]; $existingDate = $existingDates->get($index); if ($existingDate) { $existingDate->update($attributes); } else { $event->dates()->create($attributes); } } $existingDates->slice(count($dates))->each->delete(); $event->unsetRelation('dates'); } /** @param array $contact */ private function syncLegacyContact(Tenant $tenant, array $contact): void { foreach (self::CONTACT_CODES as $field => $code) { $url = $contact[$field] ?? null; if ($url === null || $url === '') { $tenant->socialMedia()->detach($code); continue; } $tenant->socialMedia()->syncWithoutDetaching([ $code => ['url' => $url], ]); } $tenant->unsetRelation('socialMedia'); } /** @param array $socialMedia */ private function syncSocialMedia(Tenant $tenant, array $socialMedia): void { $associations = []; foreach (array_values($socialMedia) as $index => $item) { $associations[$item['code']] = [ 'url' => $item['url'], 'orden' => $item['orden'] ?? $index, ]; } $tenant->socialMedia()->sync($associations); $tenant->unsetRelation('socialMedia'); } }