<?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
    {
        // PRC-621: base model üzerinden sorgula — NotificationTemplate scope'u
        // yalnız 5 admin kanalını kapsar; admin SMS şablonları channel='sms'
        // satırlarında yaşar (type-key adlarıyla, örn. 'order_created').
        $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));
    }

    /**
     * PRC-622 review F5 — bu kanal+ad için (status'tan bağımsız) bir şablon
     * SATIRI var mı? render() null döndüğünde "şablon hiç yok → ham fallback"
     * ile "şablon var ama inactive/içeriksiz → kanalı sustur" ayrımı için.
     */
    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);

        // PRC-625: dual-emit — kanonik + legacy adları birlikte doldur.
        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;
    }

    /**
     * Get available merge fields filtered by template type.
     */
    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'],
        ];

        // Type-to-relevant-groups mapping
        $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;
    }
}
