<?php
 namespace App\Observers; use App\Events\TicketRepliedByAdmin; use App\Events\TicketRepliedByClient; use App\Core\Hook\HookBridge; use App\Models\TicketReply; class TicketReplyObserver { public function created(TicketReply $reply): void { $reply->loadMissing(['ticket', 'admin', 'client']); $isFirstReply = $reply->ticket->replies()->count() === 1; if ($reply->admin_id && $reply->admin) { \App\Models\Log::create([ 'type' => \App\Models\Log::TYPE_SYSTEM, 'observer' => 'TicketReplyObserver', 'module' => 'TicketReply', 'method' => 'created_by_admin', 'admin_id' => $reply->admin_id, 'client_id' => $reply->ticket->client_id, 'ip_address' => request()->ip() ?? '0.0.0.0', 'user_agent' => request()->userAgent(), 'description' => "Admin {$reply->admin->name} replied to ticket #{$reply->ticket->id}", 'request' => [ 'entity_id' => $reply->id, 'ticket_id' => $reply->ticket->id, 'is_first_reply' => $isFirstReply, 'message_length' => strlen($reply->message), ], ]); if (!$isFirstReply) { TicketRepliedByAdmin::dispatch($reply->ticket, $reply, $reply->admin); } $this->fireCreatedHooks($reply); return; } if ($reply->client_id && $reply->client) { \App\Models\Log::create([ 'type' => \App\Models\Log::TYPE_CLIENT, 'observer' => 'TicketReplyObserver', 'module' => 'TicketReply', 'method' => 'created_by_client', 'client_id' => $reply->client_id, 'ip_address' => request()->ip() ?? '0.0.0.0', 'user_agent' => request()->userAgent(), 'description' => "Client {$reply->client->first_name} {$reply->client->last_name} replied to ticket #{$reply->ticket->id}", 'request' => [ 'entity_id' => $reply->id, 'ticket_id' => $reply->ticket->id, 'message_length' => strlen($reply->message), ], ]); TicketRepliedByClient::dispatch($reply->ticket, $reply, $reply->client); $this->fireCreatedHooks($reply); } } public function deleted(TicketReply $reply): void { app(HookBridge::class)->fireAction('TicketDeleteReply', [ 'ticketId' => $reply->ticket_id, 'ticket_id' => $reply->ticket_id, 'replyId' => $reply->id, 'reply_id' => $reply->id, 'adminId' => request()->user('admin')?->id, ]); } private function fireCreatedHooks(TicketReply $reply): void { $bridge = app(HookBridge::class); $ticket = $reply->ticket; $baseCtx = $bridge->buildTicketReplyContext($reply, $bridge->buildTicketContext($ticket)); if ($reply->is_internal) { $bridge->fireAction('TicketAddNote', array_merge($baseCtx, [ 'adminid' => $reply->admin_id, 'attachments' => '', ])); return; } if (! empty($reply->admin_id)) { $bridge->fireAction('TicketAdminReply', array_merge($baseCtx, [ 'admin' => optional($reply->admin)->name, ])); } else { $bridge->fireAction('TicketUserReply', $baseCtx); } } } 