<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\Logger;

class RenewalEmailService
{
    private NotificationChannelService $notifier;

    public function __construct(?NotificationChannelService $notifier = null)
    {
        $this->notifier = $notifier ?? new NotificationChannelService();
    }

    public function sendSubscriptionRenewal(array $payload): array
    {
        $adminEmail = strtolower(trim((string) ($payload['admin_email'] ?? '')));
        if ($adminEmail === '' || !filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
            return [
                'ok' => false,
                'error' => 'Correo de destino inválido para renovación.',
                'response' => null,
            ];
        }

        if (!$this->notifier->isChannelEnabled('email')) {
            return [
                'ok' => false,
                'error' => 'Canal email desactivado.',
                'response' => null,
            ];
        }

        $adminName = trim((string) ($payload['admin_name'] ?? 'Administrador'));
        $companyName = trim((string) ($payload['company_name'] ?? 'Tu empresa'));
        $planName = trim((string) ($payload['plan_name'] ?? 'Plan activo'));
        $renewedUntil = trim((string) ($payload['renewed_until'] ?? ''));
        $paymentAt = trim((string) ($payload['payment_at'] ?? date('Y-m-d H:i:s')));
        $reference = trim((string) ($payload['reference'] ?? ''));
        $gateway = trim((string) ($payload['gateway'] ?? 'manual'));
        $currency = strtoupper(trim((string) ($payload['currency'] ?? 'COP')));
        $amount = (float) ($payload['amount'] ?? 0);
        $amountFormatted = $this->formatMoney($amount, $currency);
        $supportUrl = 'https://wa.me/573122644576';

        $subject = 'Renovación confirmada - ' . $companyName;
        $textMessage = $this->buildTextMessage(
            $adminName,
            $companyName,
            $planName,
            $amountFormatted,
            $paymentAt,
            $renewedUntil,
            $gateway,
            $reference,
            $supportUrl
        );
        $htmlMessage = $this->buildHtmlMessage(
            $adminName,
            $companyName,
            $planName,
            $amountFormatted,
            $paymentAt,
            $renewedUntil,
            $gateway,
            $reference,
            $supportUrl
        );

        $result = $this->notifier->sendEmail($adminEmail, $subject, $textMessage, $htmlMessage);
        if (!(bool) ($result['ok'] ?? false)) {
            Logger::info('No fue posible enviar correo de renovación SaaS', [
                'admin_email' => $adminEmail,
                'company_name' => $companyName,
                'error' => (string) ($result['error'] ?? 'Error desconocido'),
            ]);
        }

        return $result;
    }

    private function formatMoney(float $amount, string $currency): string
    {
        $symbol = $currency === 'COP' ? '$' : ($currency . ' ');
        return $symbol . number_format($amount, 2, ',', '.');
    }

    private function buildTextMessage(
        string $adminName,
        string $companyName,
        string $planName,
        string $amountFormatted,
        string $paymentAt,
        string $renewedUntil,
        string $gateway,
        string $reference,
        string $supportUrl
    ): string {
        $referenceLine = $reference !== '' ? ("\nReferencia: " . $reference) : '';

        return trim(
            'Hola ' . $adminName . ',' . "\n\n"
            . 'Confirmamos la renovación mensual de tu suscripción en Veltrix POS.' . "\n\n"
            . 'Empresa: ' . $companyName . "\n"
            . 'Plan: ' . $planName . "\n"
            . 'Monto pagado: ' . $amountFormatted . "\n"
            . 'Fecha de pago: ' . $paymentAt . "\n"
            . 'Pasarela: ' . strtoupper($gateway)
            . $referenceLine . "\n"
            . 'Nueva vigencia: ' . ($renewedUntil !== '' ? $renewedUntil : 'Sin cambio') . "\n\n"
            . 'Tu servicio continúa activo.' . "\n\n"
            . 'Soporte WhatsApp: ' . $supportUrl
        );
    }

    private function buildHtmlMessage(
        string $adminName,
        string $companyName,
        string $planName,
        string $amountFormatted,
        string $paymentAt,
        string $renewedUntil,
        string $gateway,
        string $reference,
        string $supportUrl
    ): string {
        $safeAdmin = htmlspecialchars($adminName, ENT_QUOTES, 'UTF-8');
        $safeCompany = htmlspecialchars($companyName, ENT_QUOTES, 'UTF-8');
        $safePlan = htmlspecialchars($planName, ENT_QUOTES, 'UTF-8');
        $safeAmount = htmlspecialchars($amountFormatted, ENT_QUOTES, 'UTF-8');
        $safePaymentAt = htmlspecialchars($paymentAt, ENT_QUOTES, 'UTF-8');
        $safeRenewedUntil = htmlspecialchars($renewedUntil !== '' ? $renewedUntil : 'Sin cambio', ENT_QUOTES, 'UTF-8');
        $safeGateway = htmlspecialchars(strtoupper($gateway), ENT_QUOTES, 'UTF-8');
        $safeReference = htmlspecialchars($reference !== '' ? $reference : 'N/A', ENT_QUOTES, 'UTF-8');
        $safeSupportUrl = htmlspecialchars($supportUrl, ENT_QUOTES, 'UTF-8');
        $safeYear = htmlspecialchars(date('Y'), ENT_QUOTES, 'UTF-8');

        return '<!doctype html>'
            . '<html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">'
            . '<title>Renovación confirmada</title></head>'
            . '<body style="margin:0;padding:0;background:#f2f6fc;font-family:Arial,Helvetica,sans-serif;color:#1f2a3d;">'
            . '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#f2f6fc;padding:20px 10px;">'
            . '<tr><td align="center">'
            . '<table role="presentation" width="620" cellspacing="0" cellpadding="0" style="max-width:620px;width:100%;background:#ffffff;border-radius:18px;overflow:hidden;border:1px solid #dce5f4;">'
            . '<tr><td style="padding:24px 28px;background:linear-gradient(135deg,#102348 0%,#176e97 100%);">'
            . '<div style="font-size:13px;letter-spacing:.08em;text-transform:uppercase;color:#ffffff !important;-webkit-text-fill-color:#ffffff !important;font-weight:700;">Veltrix POS</div>'
            . '<h1 style="margin:10px 0 0;font-size:28px;line-height:1.15;color:#ffffff !important;-webkit-text-fill-color:#ffffff !important;text-shadow:0 1px 2px rgba(0,0,0,.35);font-weight:800;">Renovación mensual confirmada</h1>'
            . '<p style="margin:10px 0 0;font-size:15px;line-height:1.6;color:#ffffff !important;-webkit-text-fill-color:#ffffff !important;text-shadow:0 1px 2px rgba(0,0,0,.3);">Hola ' . $safeAdmin . ', tu suscripción sigue activa sin interrupciones.</p>'
            . '</td></tr>'
            . '<tr><td style="padding:22px 28px 8px;">'
            . '<table role="presentation" width="100%" cellspacing="0" cellpadding="0">'
            . '<tr><td style="padding:0 0 12px;font-size:14px;color:#6b7a96;">Empresa</td><td align="right" style="padding:0 0 12px;font-size:16px;font-weight:700;color:#1b2c48;">' . $safeCompany . '</td></tr>'
            . '<tr><td style="padding:0 0 12px;font-size:14px;color:#6b7a96;">Plan</td><td align="right" style="padding:0 0 12px;font-size:16px;font-weight:700;color:#1b2c48;">' . $safePlan . '</td></tr>'
            . '<tr><td style="padding:0 0 12px;font-size:14px;color:#6b7a96;">Monto</td><td align="right" style="padding:0 0 12px;font-size:18px;font-weight:800;color:#0a7c54;">' . $safeAmount . '</td></tr>'
            . '<tr><td style="padding:0 0 12px;font-size:14px;color:#6b7a96;">Fecha de pago</td><td align="right" style="padding:0 0 12px;font-size:14px;font-weight:600;color:#1b2c48;">' . $safePaymentAt . '</td></tr>'
            . '<tr><td style="padding:0 0 12px;font-size:14px;color:#6b7a96;">Pasarela</td><td align="right" style="padding:0 0 12px;font-size:14px;font-weight:600;color:#1b2c48;">' . $safeGateway . '</td></tr>'
            . '<tr><td style="padding:0 0 12px;font-size:14px;color:#6b7a96;">Referencia</td><td align="right" style="padding:0 0 12px;font-size:14px;font-weight:600;color:#1b2c48;">' . $safeReference . '</td></tr>'
            . '<tr><td style="padding:0 0 12px;font-size:14px;color:#6b7a96;">Nueva vigencia</td><td align="right" style="padding:0 0 12px;font-size:16px;font-weight:700;color:#0d6ba3;">' . $safeRenewedUntil . '</td></tr>'
            . '</table>'
            . '</td></tr>'
            . '<tr><td style="padding:10px 28px 24px;">'
            . '<p style="margin:0 0 8px;font-size:13px;line-height:1.6;color:#6e7f9c;">Gracias por continuar con Veltrix POS.</p>'
            . '<p style="margin:0;font-size:13px;line-height:1.6;color:#6e7f9c;">¿Necesitas ayuda? Escríbenos por <a href="' . $safeSupportUrl . '" style="color:#0b78a3;text-decoration:none;font-weight:700;">WhatsApp de soporte</a>.</p>'
            . '</td></tr>'
            . '<tr><td style="padding:14px 28px;background:#f7faff;border-top:1px solid #e2e9f6;font-size:12px;color:#7c8faa;">'
            . 'Veltrix POS · ' . $safeYear . ' · Confirmación automática de renovación.'
            . '</td></tr>'
            . '</table>'
            . '</td></tr></table></body></html>';
    }
}
