<?php

declare(strict_types=1);

namespace ShieldX\Core;

defined('ABSPATH') || exit;

final class EmailTemplate
{
    /**
     * @return array<int,string>
     */
    public static function headers(): array
    {
        $headers = ['Content-Type: text/html; charset=UTF-8'];
        $from = self::senderAddress();
        if ($from !== '') {
            $headers[] = 'From: SHIELD-X <' . $from . '>';
        }

        return $headers;
    }

    public static function render(string $title, string $contentHtml, string $preheader = ''): string
    {
        $title = self::escape($title);
        $preheader = self::escape($preheader);

        $parts = [
            '<!doctype html>',
            '<html>',
            '<head>',
            '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">',
            '<meta name="viewport" content="width=device-width, initial-scale=1.0">',
            '<title>' . $title . '</title>',
            '</head>',
            '<body style="margin:0;padding:0;background:#f4f7fb;color:#101935;font-family:Arial,Helvetica,sans-serif;line-height:1.55;">',
        ];
        if ($preheader !== '') {
            $parts[] = '<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;">' . $preheader . '</div>';
        }

        $parts = array_merge($parts, [
            '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;background:#f4f7fb;margin:0;padding:0;">',
            '<tr><td align="center" style="padding:28px 12px;">',
            '<table role="presentation" width="640" cellspacing="0" cellpadding="0" style="border-collapse:collapse;width:100%;max-width:640px;background:#ffffff;border:1px solid #dce6f5;border-radius:8px;overflow:hidden;">',
            '<tr><td style="background:#ffffff;padding:22px 26px 20px;color:#101935;">',
            self::logo(),
            '</td></tr>',
            '<tr><td style="padding:28px 26px 10px;">',
            '<h1 style="margin:0 0 18px;color:#101935;font-size:18.2px;line-height:1.2;font-weight:700;letter-spacing:0;">' . $title . '</h1>',
            $contentHtml,
            '</td></tr>',
            '<tr><td style="padding:16px 26px;background:#ffffff;color:#4b5d7d;font-size:12px;">',
            self::escape(__('This message was sent by SHIELD-X from your WordPress site.', 'xerotact-shield-x-security')),
            '</td></tr>',
            '</table>',
            '</td></tr>',
            '</table>',
            '</body>',
            '</html>',
        ]);

        return implode("\r\n", $parts);
    }

    /**
     * @param array<int,string> $paragraphs
     */
    public static function paragraphs(array $paragraphs): string
    {
        $html = '';
        foreach ($paragraphs as $paragraph) {
            $paragraph = trim((string) $paragraph);
            if ($paragraph === '') {
                continue;
            }

            $html .= '<p style="margin:0 0 14px;color:#4b5568;font-size:15px;">' . self::escape($paragraph) . '</p>';
        }

        return $html;
    }

    /**
     * @param array<string,string> $items
     */
    public static function details(array $items): string
    {
        if (empty($items)) {
            return '';
        }

        $parts = [
            '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:18px 0;border:1px solid #dce6f5;border-radius:8px;overflow:hidden;">',
        ];
        foreach ($items as $label => $value) {
            $parts[] = '<tr>'
                . '<td style="padding:10px 12px;background:#f6f9fd;color:#435579;font-size:13px;font-weight:700;border-bottom:1px solid #dce6f5;width:34%;">' . self::escape((string) $label) . '</td>'
                . '<td style="padding:10px 12px;color:#101935;font-size:13px;border-bottom:1px solid #dce6f5;">' . self::escape((string) $value) . '</td>'
                . '</tr>';
        }
        $parts[] = '</table>';

        return implode("\r\n", $parts);
    }

    public static function notice(string $title, string $message, string $tone = 'info'): string
    {
        $styles = self::noticeStyles($tone);

        return '<div style="margin:0 0 18px;padding:14px 16px;background:' . $styles['background'] . ';border:1px solid ' . $styles['border'] . ';border-left:5px solid ' . $styles['accent'] . ';border-radius:8px;">'
            . '<strong style="display:block;margin:0 0 5px;color:#101935;font-size:15px;line-height:1.3;">' . self::escape($title) . '</strong>'
            . '<span style="display:block;margin:0;color:#435579;font-size:14px;line-height:1.5;">' . self::escape($message) . '</span>'
            . '</div>';
    }

    public static function button(string $label, string $url): string
    {
        $label = self::escape($label);
        $url = self::escape($url);

        return '<p style="margin:20px 0 18px;"><a href="' . $url . '" style="display:inline-block;background:#050914;color:#ffffff;text-decoration:none;font-size:15px;font-weight:700;padding:12px 18px;border-radius:8px;">' . $label . '</a></p>';
    }

    public static function codeBlock(string $value): string
    {
        return '<div style="margin:14px 0 18px;padding:14px 16px;background:#f6f9fd;border:1px solid #dce6f5;border-radius:8px;color:#101935;font-size:20px;font-weight:700;letter-spacing:2px;font-family:Consolas,Monaco,monospace;"><code>' . self::escape($value) . '</code></div>';
    }

    /**
     * @param array<int,string> $values
     */
    public static function codeList(array $values): string
    {
        $parts = [
            '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:14px 0 18px;background:#f6f9fd;border:1px solid #dce6f5;border-radius:8px;overflow:hidden;">',
        ];
        foreach ($values as $value) {
            $parts[] = '<tr><td style="padding:10px 14px;border-bottom:1px solid #dce6f5;color:#101935;font-size:18px;font-weight:700;letter-spacing:1px;font-family:Consolas,Monaco,monospace;"><code>' . self::escape((string) $value) . '</code></td></tr>';
        }
        $parts[] = '</table>';

        return implode("\r\n", $parts);
    }

    public static function preformatted(string $text): string
    {
        return '<pre style="white-space:pre-wrap;word-wrap:break-word;overflow-wrap:break-word;word-break:break-word;width:100%;max-width:100%;box-sizing:border-box;margin:0;color:#101935;font-size:13px;line-height:1.55;font-family:Consolas,Monaco,monospace;border:1px solid #dce6f5;border-radius:8px;padding:14px;">' . self::escape(self::wrapDiagnosticText($text)) . '</pre>';
    }

    public static function escape(string $value): string
    {
        return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
    }

    private static function logo(): string
    {
        $logoUrl = self::logoUrl();
        if ($logoUrl !== '') {
            return '<table role="presentation" cellspacing="0" cellpadding="0" style="border-collapse:collapse;">'
                . '<tr>'
                . '<td style="width:46px;vertical-align:middle;">'
                . '<img src="' . self::escape($logoUrl) . '" width="42" alt="SHIELD-X" style="display:block;width:42px;max-width:42px;height:auto;border:0;outline:none;text-decoration:none;">'
                . '</td>'
                . '<td style="padding-left:12px;vertical-align:middle;">'
                . '<div style="margin:0;color:#101935;font-size:15px;line-height:1.2;font-weight:700;letter-spacing:0;">SHIELD-X</div>'
                . '<div style="margin:2px 0 0;color:#4b5d7d;font-size:12px;line-height:1.35;">' . self::escape(__('WordPress security notification', 'xerotact-shield-x-security')) . '</div>'
                . '</td>'
                . '</tr>'
                . '</table>';
        }

        return '<div style="display:inline-block;padding:8px 10px;border:1px solid #dce6f5;border-radius:8px;color:#101935;font-size:13px;font-weight:700;letter-spacing:.04em;">SHIELD-X</div>';
    }

    private static function logoUrl(): string
    {
        if (!defined('SHIELDX_PLUGIN_URL')) {
            return '';
        }

        $baseUrl = trim((string) SHIELDX_PLUGIN_URL);
        if ($baseUrl === '') {
            return '';
        }

        return rtrim($baseUrl, '/') . '/assets/images/shield-x-email-logo.webp';
    }

    /**
     * @return array{background:string,border:string,accent:string}
     */
    private static function noticeStyles(string $tone): array
    {
        switch ($tone) {
            case 'success':
                return ['background' => '#ecfdf5', 'border' => '#bbf7d0', 'accent' => '#16a34a'];
            case 'warning':
                return ['background' => '#fff7ed', 'border' => '#fed7aa', 'accent' => '#d97706'];
            case 'critical':
                return ['background' => '#fef2f2', 'border' => '#fecaca', 'accent' => '#dc2626'];
            case 'info':
            default:
                return ['background' => '#eff6ff', 'border' => '#bfdbfe', 'accent' => '#2563eb'];
        }
    }

    private static function senderAddress(): string
    {
        $host = '';
        if (function_exists('home_url') && function_exists('wp_parse_url')) {
            $host = (string) wp_parse_url((string) home_url('/'), PHP_URL_HOST);
        }

        $host = strtolower(trim($host));
        $host = preg_replace('/^www\./', '', $host) ?: '';
        $host = preg_replace('/[^a-z0-9.\-]/', '', $host) ?: '';
        if ($host !== '' && strpos($host, '.') !== false && filter_var($host, FILTER_VALIDATE_IP) === false) {
            $from = self::validEmail('shield-x@' . $host);
            if ($from !== '') {
                return $from;
            }
        }

        if (function_exists('get_option')) {
            return self::validEmail((string) get_option('admin_email', ''));
        }

        return '';
    }

    private static function validEmail(string $email): string
    {
        $email = trim($email);
        if ($email === '') {
            return '';
        }

        if (function_exists('sanitize_email')) {
            $email = (string) sanitize_email($email);
        }

        if ($email === '') {
            return '';
        }

        if (function_exists('is_email')) {
            return is_email($email) ? $email : '';
        }

        return filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : '';
    }

    private static function wrapDiagnosticText(string $text): string
    {
        $normalized = str_replace(["\r\n", "\r"], "\n", $text);
        $lines = explode("\n", $normalized);

        foreach ($lines as $index => $line) {
            $lines[$index] = wordwrap($line, 120, "\n", true);
        }

        return implode("\n", $lines);
    }
}
