<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\SchemaRuntime;
use App\Shared\Schema\FinanceSchemaSupport;
use InvalidArgumentException;
use PDO;

final class CommunicationService
{
    public function __construct(private PDO $pdo)
    {
    }

    public function settings(): array
    {
        $pdo = $this->pdo;
        SchemaRuntime::ensure($pdo, 'app_settings_schema', static function () use ($pdo): void {
            FinanceSchemaSupport::ensureAppSettingsSchema($pdo);
        }, 'sql/migrate_v1_16_app_settings.sql');
        return communication_settings($this->pdo);
    }

    public function save(array $input): void
    {
        $settings = [
            'mail_from_name' => trim((string)($input['mail_from_name'] ?? '')),
            'mail_from_email' => trim((string)($input['mail_from_email'] ?? '')),
            'mail_transport' => trim((string)($input['mail_transport'] ?? 'mail')),
            'mail_reply_to' => trim((string)($input['mail_reply_to'] ?? '')),
            'smtp_host' => trim((string)($input['smtp_host'] ?? '')),
            'smtp_port' => trim((string)($input['smtp_port'] ?? '587')),
            'smtp_username' => trim((string)($input['smtp_username'] ?? '')),
            'smtp_password' => (string)($input['smtp_password'] ?? ''),
            'smtp_encryption' => trim((string)($input['smtp_encryption'] ?? 'tls')),
            'smtp_timeout' => trim((string)($input['smtp_timeout'] ?? '15')),
            'public_base_url' => trim((string)($input['public_base_url'] ?? '')), 
            'whatsapp_template' => trim((string)($input['whatsapp_template'] ?? '')),
            'quotation_email_template' => trim((string)($input['quotation_email_template'] ?? '')),
            'whatsapp_default_country_code' => trim((string)($input['whatsapp_default_country_code'] ?? '20')),
        ];
        if ($settings['mail_from_email'] !== '' && !filter_var($settings['mail_from_email'], FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException('البريد الافتراضي غير صحيح.');
        }
        if ($settings['mail_reply_to'] !== '' && !filter_var($settings['mail_reply_to'], FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException('بريد الرد غير صحيح.');
        }

        if ($settings['smtp_port'] !== '' && (!ctype_digit($settings['smtp_port']) || (int)$settings['smtp_port'] <= 0 || (int)$settings['smtp_port'] > 65535)) {
            throw new InvalidArgumentException('SMTP Port غير صحيح.');
        }
        if ($settings['smtp_timeout'] !== '' && (!is_numeric($settings['smtp_timeout']) || (float)$settings['smtp_timeout'] <= 0 || (float)$settings['smtp_timeout'] > 120)) {
            throw new InvalidArgumentException('SMTP Timeout غير صحيح.');
        }
        $allowedEncryption = ['tls', 'ssl', 'none'];
        if (!in_array(strtolower($settings['smtp_encryption']), $allowedEncryption, true)) {
            $settings['smtp_encryption'] = 'tls';
        }
        if ($settings['mail_transport'] === 'smtp') {
            if ($settings['smtp_host'] === '') {
                throw new InvalidArgumentException('SMTP Host مطلوب عند اختيار SMTP.');
            }
            if ($settings['smtp_username'] === '') {
                throw new InvalidArgumentException('SMTP Username مطلوب عند اختيار SMTP.');
            }
            if ($settings['smtp_password'] === '') {
                throw new InvalidArgumentException('SMTP Password مطلوب عند اختيار SMTP.');
            }
        }
        $allowedTransports = ['mail', 'smtp', 'log', 'disabled'];
        if (!in_array($settings['mail_transport'], $allowedTransports, true)) {
            $settings['mail_transport'] = 'mail';
        }
        $settings['whatsapp_default_country_code'] = preg_replace('/[^0-9]/', '', $settings['whatsapp_default_country_code']) ?: '20';
        if ($settings['whatsapp_template'] === '' || $this->isLegacyWhatsappTemplate($settings['whatsapp_template'])) {
            $settings['whatsapp_template'] = self::defaultWhatsappTemplate();
        }
        if ($settings['quotation_email_template'] === '' || $this->isLegacyQuotationEmailTemplate($settings['quotation_email_template'])) {
            $settings['quotation_email_template'] = self::defaultQuotationEmailTemplate();
        }
        save_communication_settings($this->pdo, $settings);
    }
    private static function defaultQuotationEmailTemplate(): string
    {
        return '<div dir="rtl" style="font-family:Tahoma,Arial,sans-serif;font-size:15px;line-height:1.9;color:#1f2937">'
            . '<p>مرحبًا {customer_name}،</p>'
            . '<p>نرسل لكم عرض السعر رقم <strong>{quotation_no}</strong><br>بتاريخ <strong>{quotation_date}</strong><br>إجمالي العرض: <strong>{total_amount}</strong></p>'
            . '<p><a href="{quotation_url}" target="_blank" rel="noopener">اضغط هنا لفتح عرض السعر</a></p>'
            . '<p>مع تحيات<br><strong>{company_name}</strong></p>'
            . '</div>';
    }

    private function isLegacyQuotationEmailTemplate(string $template): bool
    {
        $normalized = trim(preg_replace('/\s+/u', ' ', strip_tags(html_entity_decode($template, ENT_QUOTES | ENT_HTML5, 'UTF-8'))));
        $legacy = [
            trim(preg_replace('/\s+/u', ' ', 'مرحبًا {customer_name}، نرفق لكم رابط عرض السعر رقم {quotation_no}. فتح عرض السعر')),
            trim(preg_replace('/\s+/u', ' ', 'مرحبًا {customer_name}، نرفق لكم رابط عرض السعر رقم {quotation_no}.')),
        ];
        return in_array($normalized, $legacy, true);
    }

    private static function defaultWhatsappTemplate(): string
    {
        return "مرحبًا {customer_name}،\n\nهذا عرض السعر رقم {quotation_no}\nبتاريخ {quotation_date}\nإجمالي العرض: {total_amount}\n\nرابط عرض السعر:\n{quotation_url}\n\nمع تحيات\n{company_name}";
    }

    private function isLegacyWhatsappTemplate(string $template): bool
    {
        $normalized = trim(preg_replace('/\s+/u', ' ', $template));
        $legacy = [
            trim(preg_replace('/\s+/u', ' ', "Hi {customer_name} please check this {quotation_no} from {quotation_url}")),
            trim(preg_replace('/\s+/u', ' ', "مرحبًا {customer_name}\nنرسل لكم عرض السعر رقم {quotation_no}\nالإجمالي: {total_amount}\nرابط العرض: {quotation_url}")),
            trim(preg_replace('/\s+/u', ' ', "مرحبًا {customer_name}،\n\nهذا عرض السعر رقم {quotation_no}\nبتاريخ {quotation_date}\nإجمالي العرض: {total_amount}\n\nرابط تحميل العرض PDF:\n{quotation_pdf_url}\n\nمع تحيات\n{company_name}")),
        ];
        return in_array($normalized, $legacy, true);
    }

}
