<?php
 namespace App\Listeners; use App\Events\DomainProvisioningCompleted; use App\Models\ClientDomain; use App\Models\ClientProduct; use App\Models\DnsZone; use App\Models\Setting; use App\Services\Dns\DnsZoneService; use Illuminate\Support\Facades\Log; class SetupDnsForCoOrderListener { public function __construct(private DnsZoneService $zones) {} public function handle(DomainProvisioningCompleted $event): void { if (! Setting::getValue('dns_auto_setup_on_co_order', false)) { return; } if ($event->action !== 'register' || ! $event->entityId) { return; } $domain = ClientDomain::find($event->entityId); if (! $domain || ! $domain->client_id) { return; } if (DnsZone::where('client_domain_id', $domain->id)->exists()) { return; } $hosting = $domain->order_id ? ClientProduct::where('client_id', $domain->client_id) ->where('order_id', $domain->order_id) ->whereNotNull('ip_address') ->first() : null; if (! $hosting) { $hosting = ClientProduct::where('client_id', $domain->client_id) ->whereNotNull('ip_address') ->where('status', 'active') ->latest() ->first(); } if (! $hosting || ! $hosting->ip_address) { return; } try { $zone = $this->zones->createZone( $domain->domain, $domain->client_id, $domain->id, ); $this->zones->createRecord($zone, [ 'type' => 'A', 'name' => $domain->domain, 'content' => $hosting->ip_address, 'ttl' => 3600, ]); $this->zones->createRecord($zone, [ 'type' => 'A', 'name' => 'www.'.$domain->domain, 'content' => $hosting->ip_address, 'ttl' => 3600, ]); Log::info('PRC-299: auto-DNS zone + A records created on co-order', [ 'domain' => $domain->domain, 'hosting_id' => $hosting->id, 'ip' => $hosting->ip_address, 'zone_id' => $zone->id, 'provider' => $zone->provider, ]); } catch (\Throwable $e) { Log::warning('PRC-299: auto-DNS setup failed (non-fatal): '.$e->getMessage(), [ 'domain' => $domain->domain, 'client_id' => $domain->client_id, ]); } } } 