<?php
 namespace App\Services; use App\Models\CommunicationTemplate; use App\Models\Setting; class NotificationTemplateService { public function render(string $channel, string $name, array $mergeFields = [], ?string $language = null): ?string { $template = CommunicationTemplate::where('channel', $channel) ->where('name', $name) ->where('status', 'active') ->first(); if (!$template) { return null; } $language = $language ?? app()->getLocale(); $content = $template->getContent($language); if (!$content) { return null; } return $this->replaceMergeFields($content->content, $this->withSystemFields($mergeFields)); } public function hasTemplateRow(string $channel, string $name): bool { return CommunicationTemplate::where('channel', $channel) ->where('name', $name) ->exists(); } private function withSystemFields(array $mergeFields): array { $fields = array_merge([ 'COMPANY_NAME' => Setting::get('company_name', config('app.name')), 'COMPANY_EMAIL' => Setting::get('company_email', config('mail.from.address')), 'SITE_URL' => config('app.url'), 'SITE_NAME' => Setting::get('company_name', config('app.name')), 'CURRENT_DATE' => now()->format('d/m/Y'), 'CURRENT_TIME' => now()->format('H:i'), ], $mergeFields); return \App\Support\MergeFieldDictionary::expand($fields); } private function replaceMergeFields(string $content, array $mergeFields): string { foreach ($mergeFields as $key => $value) { $content = str_replace('{' . $key . '}', (string) $value, $content); } return $content; } public function getAvailableMergeFields(?string $type = null): array { $all = [ 'system' => ['COMPANY_NAME', 'COMPANY_EMAIL', 'SITE_URL', 'SITE_NAME', 'CURRENT_DATE', 'CURRENT_TIME'], 'client' => ['CLIENT_ID', 'CLIENT_NAME', 'CLIENT_EMAIL', 'CLIENT_PHONE', 'CLIENT_COMPANY'], 'ticket' => ['TICKET_ID', 'TICKET_TITLE', 'TICKET_STATUS', 'TICKET_PRIORITY', 'TICKET_DEPARTMENT', 'TICKET_URL', 'TICKET_MESSAGE'], 'invoice' => ['INVOICE_ID', 'INVOICE_NUMBER', 'INVOICE_DATE', 'INVOICE_DUE_DATE', 'INVOICE_TOTAL', 'INVOICE_STATUS', 'INVOICE_URL'], 'domain' => ['DOMAIN_NAME', 'DOMAIN_TLD', 'DOMAIN_EXPIRY_DATE', 'DOMAIN_STATUS'], 'product' => ['PRODUCT_ID', 'PRODUCT_NAME', 'PRODUCT_PRICE'], 'provisioning' => ['ENTITY_TYPE', 'ENTITY_ID', 'ACTION', 'ERROR_MESSAGE', 'PROVISIONING_ID'], ]; $map = [ 'ticket' => ['system', 'client', 'ticket'], 'invoice' => ['system', 'client', 'invoice'], 'domain' => ['system', 'client', 'domain'], 'product' => ['system', 'client', 'product'], 'notification' => ['system', 'client', 'provisioning'], ]; if ($type && isset($map[$type])) { return array_intersect_key($all, array_flip($map[$type])); } return $all; } } 