<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\SchemaRuntime;
use App\Repositories\QuotationDispatchRepository;
use App\Shared\Schema\QuotationSchemaSupport;
use InvalidArgumentException;
use PDO;
use RuntimeException;

final class QuotationDispatchService
{
    public function __construct(private PDO $pdo, private QuotationDispatchRepository $repo)
    {
    }

    public function quotation(int $id): array
    {
        $pdo = $this->pdo;
        SchemaRuntime::ensure($pdo, 'quotations_schema', static function () use ($pdo): void {
            QuotationSchemaSupport::ensureQuotationsSchema($pdo);
        }, 'sql/migrate_v1_26_quotations.sql');
        $row = $this->repo->find($id);
        if (!$row) {
            throw new RuntimeException('Quotation not found');
        }
        return $row;
    }

    public function defaultEmailForm(array $quotation): array
    {
        $publicUrl = quotation_public_share_url($this->pdo, (int)$quotation['id']);
        return [
            'to' => (string)($quotation['party_email'] ?? ''),
            'subject' => 'عرض سعر رقم ' . (string)$quotation['quotation_no'],
            'message' => $this->buildQuotationEmailHtml($quotation, $publicUrl),
        ];
    }

    public function sendEmail(int $id, array $input): array
    {
        $to = trim((string)($input['to'] ?? ''));
        $subject = trim((string)($input['subject'] ?? ''));
        $message = trim((string)($input['message'] ?? ''));
        if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException('أدخل بريدًا صحيحًا.');
        }
        if ($subject === '') {
            throw new InvalidArgumentException('الموضوع مطلوب.');
        }
        if ($message === '') {
            throw new InvalidArgumentException('نص الرسالة مطلوب.');
        }
        $res = send_simple_mail($this->pdo, $to, $subject, $message, []);
        $status = !empty($res['ok']) ? 'sent' : 'failed';
        $this->repo->log($id, 'email', $to, $status, (string)($res['message'] ?? ''));
        if (empty($res['ok'])) {
            throw new RuntimeException((string)($res['message'] ?? 'تعذر الإرسال.'));
        }
        $this->repo->markSent($id);
        return $res;
    }

    public function whatsappUrl(int $id, array $quotation): string
    {
        $settings = communication_settings($this->pdo);
        $template = trim((string)($settings['whatsapp_template'] ?? ''));
        if ($template === '') {
            $template = self::defaultWhatsappTemplate();
        }

        $url = quotation_public_share_url($this->pdo, $id);
        $company = company_profile($this->pdo);
        $companyName = trim((string)($company['name'] ?? '')) !== '' ? (string)$company['name'] : (string)config('app.name', 'Sales & Stock');
        $map = [
            '{customer_name}' => (string)($quotation['party_name'] ?: 'عميلنا الكريم'),
            '{quotation_no}' => (string)$quotation['quotation_no'],
            '{quotation_date}' => (string)($quotation['quotation_date'] ?? ''),
            '{total_amount}' => number_format((float)$quotation['total_amount'], 2),
            '{quotation_url}' => $url,
            '{quotation_pdf_url}' => $this->ltrUrl($url),
            '{quotation_pdf_plain_url}' => $url,
            '{company_name}' => $companyName,
        ];
        $message = strtr($template, $map);

        $phone = $this->normalizeWhatsappPhone((string)($quotation['party_phone'] ?? ''), (string)($settings['whatsapp_default_country_code'] ?? '20'));
        if ($phone === '') {
            throw new InvalidArgumentException('رقم هاتف العميل غير موجود أو غير صالح لفتح واتساب.');
        }

        $this->repo->log($id, 'whatsapp', $phone, 'opened', 'فتح رابط واتساب');
        $this->repo->markSent($id);
        return 'https://wa.me/' . $phone . '?text=' . rawurlencode($message);
    }

    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 ltrUrl(string $url): string
    {
        return "⁦" . trim($url) . "⁩";
    }

    private function normalizeWhatsappPhone(string $phone, string $defaultCountryCode): string
    {
        $digits = preg_replace('/[^0-9+]/', '', trim($phone));
        if ($digits === '') {
            return '';
        }

        if (str_starts_with($digits, '+')) {
            return preg_replace('/[^0-9]/', '', $digits);
        }

        $digits = preg_replace('/[^0-9]/', '', $digits);
        if ($digits === '') {
            return '';
        }

        $cc = preg_replace('/[^0-9]/', '', $defaultCountryCode);
        if ($cc === '') {
            $cc = '20';
        }

        if (str_starts_with($digits, '00')) {
            return substr($digits, 2);
        }

        if (str_starts_with($digits, '0')) {
            return $cc . ltrim($digits, '0');
        }

        if (!str_starts_with($digits, $cc) && strlen($digits) <= 11) {
            return $cc . $digits;
        }

        return $digits;
    }


    private function buildQuotationEmailHtml(array $quotation, string $publicUrl): string
    {
        $settings = communication_settings($this->pdo);
        $company = company_profile($this->pdo);
        $companyName = trim((string)($company['name'] ?? '')) !== '' ? (string)$company['name'] : (string)config('app.name', 'Sales & Stock');
        $template = trim((string)($settings['quotation_email_template'] ?? ''));
        if ($template === '') {
            $template = '<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>';
        }
        return strtr($template, [
            '{customer_name}' => (string)($quotation['party_name'] ?: 'عميلنا الكريم'),
            '{quotation_no}' => (string)($quotation['quotation_no'] ?? ''),
            '{quotation_date}' => (string)($quotation['quotation_date'] ?? ''),
            '{total_amount}' => number_format((float)($quotation['total_amount'] ?? 0), 2),
            '{quotation_pdf_url}' => e($publicUrl),
            '{quotation_pdf_plain_url}' => e($publicUrl),
            '{quotation_url}' => e($publicUrl),
            '{company_name}' => e($companyName),
        ]);
    }

}
