<?php

namespace App\Helpers;

use App\Models\EmailTemplate;
use App\Models\EmailTemplateContent;
use App\Models\Setting;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;

class EmailTemplateHelper
{
    /**
     * Email template'ini render eder
     *
     * @param  string  $templateName  Template adı
     * @param  array  $mergeFields  Merge edilecek alanlar
     * @param  string  $language  Dil kodu (varsayılan: tr)
     * @return array ['subject' => string, 'content' => string]
     */
    public static function renderTemplate(string $templateName, array $mergeFields = [], string $language = 'tr'): array
    {


        // Template'i bul
        $template = EmailTemplate::where('name', $templateName)
            ->where('status', 'active')
            ->first();

        if (! $template) {
            \Log::error('EmailTemplateHelper::renderTemplate - Template not found', [
                'template_name' => $templateName,
            ]);
            throw new \Exception(__('admin/common.email_templates_template_not_found', ['template_name' => $templateName]));
        }


        // Template içeriğini al
        $content = EmailTemplateContent::where('template_id', $template->id)
            ->where('language', $language)
            ->first();

        if (! $content) {
            \Log::warning('EmailTemplateHelper::renderTemplate - Content not found for language, trying default', [
                'template_id' => $template->id,
                'language' => $language,
            ]);

            // Varsayılan dil içeriğini dene (PRC-625: hardcoded 'tr' yerine site
            // varsayılan dili — SmsTemplateHelper::fallbackLanguage paterniyle aynı).
            $content = EmailTemplateContent::where('template_id', $template->id)
                ->where('language', \App\Models\Language::getSiteDefaultCode() ?: 'tr')
                ->first();

            if (! $content) {
                \Log::error('EmailTemplateHelper::renderTemplate - No content found', [
                    'template_id' => $template->id,
                ]);
                throw new \Exception(__('admin/common.email_templates_content_not_found'));
            }
        }



        // Hook: EmailTplMergeFields — allows augmenting merge fields for this template type
        $extraTplFields = app(\App\Core\Hook\HookManager::class)->filter(
            'EmailTplMergeFields',
            [],
            $template->type ?? $template->name,
            $language
        );
        if (!empty($extraTplFields) && is_array($extraTplFields)) {
            $mergeFields = array_merge($mergeFields, $extraTplFields);
        }

        // Merge fields'ları hazırla
        $preparedMergeFields = self::prepareMergeFields($mergeFields);



        // Subject ve content'i render et
        $renderedSubject = self::replaceMergeFields($content->subject, $preparedMergeFields);
        $renderedContent = self::replaceMergeFields($content->content, $preparedMergeFields);



        // Header ve footer ekle
        $finalContent = self::wrapWithHeaderFooter($renderedContent, $renderedSubject, $preparedMergeFields);



        return [
            'subject' => $renderedSubject,
            'content' => $finalContent,
            'template' => $template,
        ];
    }

    /**
     * Merge fields'ları hazırlar
     */
    private static function prepareMergeFields(array $mergeFields): array
    {
        $prepared = [];

        // PRC-625: dual-emit — kanonik + legacy adları birlikte doldur. Brace'le
        // sarmadan ÖNCE genişlet ki hangi stildeki içerik olursa olsun değer bassın.
        $mergeFields = \App\Support\MergeFieldDictionary::expand($mergeFields);

        // Sistem merge fields'ları
        $systemFields = self::getSystemMergeFields();
        $prepared = array_merge($prepared, $systemFields);

        // Kullanıcı merge fields'ları
        foreach ($mergeFields as $key => $value) {
            $prepared['{'.strtoupper($key).'}'] = $value;
        }

        // Özel merge fields'ları
        $specialFields = self::getSpecialMergeFields($mergeFields);
        $prepared = array_merge($prepared, $specialFields);

        return $prepared;
    }

    /**
     * Sistem merge fields'larını döndürür
     */
    private static function getSystemMergeFields(): array
    {
        $settings = self::getSettings();

        return [
            '{COMPANY_NAME}' => $settings['company_name'] ?? __('admin/common.email_templates_company_name_default'),
            '{COMPANY_EMAIL}' => $settings['system_emails_from_email'] ?? __('admin/common.email_templates_system_email_default'),
            '{SITE_URL}' => config('app.url'),
            '{SITE_NAME}' => config('app.name'),
            '{CURRENT_DATE}' => now()->format('d.m.Y'),
            '{CURRENT_TIME}' => now()->format('H:i'),
            '{CURRENT_YEAR}' => now()->format('Y'),
            '{CURRENT_MONTH}' => now()->format('m'),
            '{CURRENT_DAY}' => now()->format('d'),
            '{LOGIN_URL}' => config('app.url').'/login',
            '{ADMIN_URL}' => config('app.url').'/admin',
            '{CLIENT_AREA_URL}' => config('app.url').'/clientarea',
            '{SIGNATURE}' => $settings['global_email_signature'] ?? '',
        ];
    }

    /**
     * Özel merge fields'ları döndürür (Deprecated - SendEmailJob'a taşındı)
     * Legacy support için korunuyor
     */
    private static function getSpecialMergeFields(array $mergeFields): array
    {
        $special = [];

        // Sadece direct entity support - complex logic SendEmailJob'da
        foreach ($mergeFields as $key => $value) {
            if (is_scalar($value) || is_null($value)) {
                $special['{'.strtoupper($key).'}'] = $value;
            }
        }

        return $special;
    }

    /**
     * Merge fields'ları replace eder
     */
    private static function replaceMergeFields(string $content, array $mergeFields): string
    {
        // PRC-626 — merge field değerleri (cPanel parolası, doğrulama kodu,
        // şifre-sıfırlama token'ı) hassastır; loglanmaz.
        foreach ($mergeFields as $field => $value) {
            $content = str_replace($field, $value, $content);
        }

        return $content;
    }

    /**
     * Header ve footer ile content'i sarar
     *
     * @param  array  $mergeFields  All merge fields from template
     */
    private static function wrapWithHeaderFooter(string $content, string $subject = '', array $mergeFields = []): string
    {
        $settings = self::getSettings();

        $header = $settings['client_email_header_content'] ?? '';
        $footer = $settings['client_email_footer_content'] ?? '';
        $css = $settings['global_email_css_styling'] ?? '';

        // Header ve footer için merge fields'ları hazırla
        $headerFooterMergeFields = [
            '{SUBJECT}' => $subject,
            '{EMAIL_STYLES}' => $css,
            '{COMPANY_NAME}' => $settings['company_name'] ?? __('admin/common.email_templates_company_name_test'),
        ];

        // Template'den gelen tüm merge fields'ları ekle
        $headerFooterMergeFields = array_merge($headerFooterMergeFields, $mergeFields);

        $header = self::replaceMergeFields($header, $headerFooterMergeFields);
        $footer = self::replaceMergeFields($footer, $headerFooterMergeFields);

        // Content'i header ve footer arasına yerleştir
        $fullContent = $header.$content.$footer;

        return $fullContent;
    }

    /**
     * Settings'leri döndürür
     */
    private static function getSettings(): array
    {
        $settings = [];

        // Settings tablosundan al
        $dbSettings = Setting::all()->pluck('value', 'key')->toArray();
        $settings = array_merge($settings, $dbSettings);

        // Config'den fallback olarak al - DB'de yoksa veya boşsa config kullan
        if (empty($settings['system_emails_from_name'])) {
            $settings['system_emails_from_name'] = config('mail.from.name');
        }
        if (empty($settings['system_emails_from_email'])) {
            $settings['system_emails_from_email'] = config('mail.from.address');
        }

        return $settings;
    }

    /**
     * Email gönderir
     */
    public static function sendEmail(string $templateName, string $to, array $mergeFields = [], string $language = 'tr'): bool
    {
        try {
            $rendered = self::renderTemplate($templateName, $mergeFields, $language);

            // Email gönderme işlemi burada yapılacak
            // Mail::to($to)->send(new EmailTemplate($rendered));

            return true;
        } catch (\Exception $e) {
            \Log::error(__('admin/common.email_templates_email_send_error', ['error' => $e->getMessage()]));

            return false;
        }
    }

    /**
     * Template tipine göre hangi merge field gruplarının alakalı olduğunu döner.
     */
    public static function getRelevantFieldGroups(?string $type = null): array
    {
        $map = [
            'admin'        => ['system', 'client'],
            'affiliate'    => ['system', 'client'],
            'domain'       => ['system', 'client', 'domain'],
            'general'      => ['system', 'client'],
            'hosting'      => ['system', 'client', 'product'],
            'invite'       => ['system', 'client'],
            'invoice'      => ['system', 'client', 'invoice', 'order'],
            'notification' => ['system', 'client'],
            'product'      => ['system', 'client', 'product'],
            'support'      => ['system', 'client', 'ticket'],
            'ticket'       => ['system', 'client', 'ticket'],
            'user'         => ['system', 'client'],
        ];

        return $map[$type] ?? array_keys(self::getMergeFieldGroups());
    }

    /**
     * Tüm merge field gruplarını döner (filtresiz).
     */
    public static function getMergeFieldGroups(): array
    {
        return [
            'system' => [
                '{COMPANY_NAME}' => __('admin/common.email_templates_merge_field_system_company_name'),
                '{COMPANY_EMAIL}' => __('admin/common.email_templates_merge_field_system_company_email'),
                '{SITE_URL}' => __('admin/common.email_templates_merge_field_system_site_url'),
                '{SITE_NAME}' => __('admin/common.email_templates_merge_field_system_site_name'),
                '{CURRENT_DATE}' => __('admin/common.email_templates_merge_field_system_current_date'),
                '{CURRENT_TIME}' => __('admin/common.email_templates_merge_field_system_current_time'),
                '{CURRENT_YEAR}' => __('admin/common.email_templates_merge_field_system_current_year'),
                '{LOGIN_URL}' => __('admin/common.email_templates_merge_field_system_login_url'),
                '{ADMIN_URL}' => __('admin/common.email_templates_merge_field_system_admin_url'),
                '{CLIENT_AREA_URL}' => __('admin/common.email_templates_merge_field_system_client_area_url'),
            ],
            'client' => [
                '{CLIENT_ID}' => __('admin/common.email_templates_merge_field_client_id'),
                '{CLIENT_NAME}' => __('admin/common.email_templates_merge_field_client_name'),
                '{CLIENT_EMAIL}' => __('admin/common.email_templates_merge_field_client_email'),
                '{CLIENT_PHONE}' => __('admin/common.email_templates_merge_field_client_phone'),
                '{CLIENT_COMPANY}' => __('admin/common.email_templates_merge_field_client_company'),
                '{CLIENT_ADDRESS}' => __('admin/common.email_templates_merge_field_client_address'),
                '{CLIENT_CITY}' => __('admin/common.email_templates_merge_field_client_city'),
                '{CLIENT_COUNTRY}' => __('admin/common.email_templates_merge_field_client_country'),
                '{CLIENT_POSTCODE}' => __('admin/common.email_templates_merge_field_client_postcode'),
            ],
            'order' => [
                '{ORDER_ID}' => __('admin/common.email_templates_merge_field_order_id'),
                '{ORDER_NUMBER}' => __('admin/common.email_templates_merge_field_order_number'),
                '{ORDER_DATE}' => __('admin/common.email_templates_merge_field_order_date'),
                '{ORDER_TOTAL}' => __('admin/common.email_templates_merge_field_order_total'),
                '{ORDER_STATUS}' => __('admin/common.email_templates_merge_field_order_status'),
                '{ORDER_URL}' => __('admin/common.email_templates_merge_field_order_url'),
            ],
            'invoice' => [
                '{INVOICE_ID}' => __('admin/common.email_templates_merge_field_invoice_id'),
                '{INVOICE_NUMBER}' => __('admin/common.email_templates_merge_field_invoice_number'),
                '{INVOICE_DATE}' => __('admin/common.email_templates_merge_field_invoice_date'),
                '{INVOICE_DUE_DATE}' => __('admin/common.email_templates_merge_field_invoice_due_date'),
                '{INVOICE_TOTAL}' => __('admin/common.email_templates_merge_field_invoice_total'),
                '{INVOICE_STATUS}' => __('admin/common.email_templates_merge_field_invoice_status'),
                '{INVOICE_URL}' => __('admin/common.email_templates_merge_field_invoice_url'),
            ],
            'ticket' => [
                '{TICKET_ID}' => __('admin/common.email_templates_merge_field_ticket_id'),
                '{TICKET_NUMBER}' => __('admin/common.email_templates_merge_field_ticket_number'),
                '{TICKET_TITLE}' => __('admin/common.email_templates_merge_field_ticket_title'),
                '{TICKET_STATUS}' => __('admin/common.email_templates_merge_field_ticket_status'),
                '{TICKET_PRIORITY}' => __('admin/common.email_templates_merge_field_ticket_priority'),
                '{TICKET_DEPARTMENT}' => __('admin/common.email_templates_merge_field_ticket_department'),
                '{TICKET_URL}' => __('admin/common.email_templates_merge_field_ticket_url'),
            ],
            'product' => [
                '{PRODUCT_ID}' => __('admin/common.email_templates_merge_field_product_id'),
                '{PRODUCT_NAME}' => __('admin/common.email_templates_merge_field_product_name'),
                '{PRODUCT_DESCRIPTION}' => __('admin/common.email_templates_merge_field_product_description'),
                '{PRODUCT_PRICE}' => __('admin/common.email_templates_merge_field_product_price'),
                '{PRODUCT_CATEGORY}' => __('admin/common.email_templates_merge_field_product_category'),
            ],
            'domain' => [
                '{DOMAIN_NAME}' => __('admin/common.email_templates_merge_field_domain_name'),
                '{DOMAIN_TLD}' => __('admin/common.email_templates_merge_field_domain_tld'),
                '{DOMAIN_REGISTRATION_DATE}' => __('admin/common.email_templates_merge_field_domain_registration_date'),
                '{DOMAIN_EXPIRY_DATE}' => __('admin/common.email_templates_merge_field_domain_expiry_date'),
                '{DOMAIN_STATUS}' => __('admin/common.email_templates_merge_field_domain_status'),
            ],
        ];
    }

    /**
     * Mevcut merge fields'ları listeler. Tip verilirse sadece alakalı grupları döner.
     */
    public static function getAvailableMergeFields(?string $type = null): array
    {
        $allGroups = self::getMergeFieldGroups();
        $relevantKeys = self::getRelevantFieldGroups($type);

        $groupLabels = [
            'system'  => __('admin/common.email_templates_merge_field_group_system'),
            'client'  => __('admin/common.email_templates_merge_field_group_client'),
            'order'   => __('admin/common.email_templates_merge_field_group_order'),
            'invoice' => __('admin/common.email_templates_merge_field_group_invoice'),
            'ticket'  => __('admin/common.email_templates_merge_field_group_ticket'),
            'product' => __('admin/common.email_templates_merge_field_group_product'),
            'domain'  => __('admin/common.email_templates_merge_field_group_domain'),
        ];

        $result = [];
        foreach ($relevantKeys as $key) {
            if (isset($allGroups[$key])) {
                $label = $groupLabels[$key] ?? ucfirst($key);
                $result[$label] = $allGroups[$key];
            }
        }

        return $result;
    }

    /**
     * Template'i test eder
     */
    public static function testTemplate(string $templateName, array $mergeFields = [], string $language = 'tr'): array
    {
        try {
            $rendered = self::renderTemplate($templateName, $mergeFields, $language);

            return [
                'success' => true,
                'subject' => $rendered['subject'],
                'content' => $rendered['content'],
                'preview' => self::generatePreview($rendered['content']),
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage(),
            ];
        }
    }

    /**
     * Email preview oluşturur
     */
    private static function generatePreview(string $content): string
    {
        // HTML'i temizle ve preview oluştur
        $preview = strip_tags($content);
        $preview = Str::limit($preview, 200);

        return $preview;
    }
}
