<?php
/**
 * Email-safe Forge transactional email renderer.
 *
 * Uses table layout, inline CSS and tiny progressive media queries so the
 * output remains readable in Gmail, Apple Mail, Outlook desktop/web, Yahoo
 * and common mobile clients.
 */

defined('ABSPATH') || exit;

if (!class_exists('Forge_Email_Template')) {

class Forge_Email_Template {
    /** @var string */
    private static $alt_body = '';

    private static function palettes() {
        return [
            'avakode'    => ['label' => 'Avakode',       'accent' => '#7C5CFC', 'subtle' => '#F5F3FF', 'on_accent' => '#FFFFFF'],
            'bundle'     => ['label' => 'Forge Suite',   'accent' => '#7C5CFC', 'subtle' => '#F5F3FF', 'on_accent' => '#FFFFFF'],
            'support'    => ['label' => 'Forge Support', 'accent' => '#7C5CFC', 'subtle' => '#F5F3FF', 'on_accent' => '#FFFFFF'],
            'alerts'     => ['label' => 'Forge Alerts',  'accent' => '#EF4444', 'subtle' => '#FEF2F2', 'on_accent' => '#FFFFFF'],
            'langforge'  => ['label' => 'Lang Forge',    'accent' => '#0EC49E', 'subtle' => '#F0FDF9', 'on_accent' => '#0C1A3A'],
            'rankforge'   => ['label' => 'Rank Forge',     'accent' => '#FF6B35', 'subtle' => '#FFF7ED', 'on_accent' => '#FFFFFF'],
            'formforge'  => ['label' => 'Form Forge',    'accent' => '#3B82F6', 'subtle' => '#EFF6FF', 'on_accent' => '#FFFFFF'],
            'fieldforge' => ['label' => 'Field Forge',   'accent' => '#F43F5E', 'subtle' => '#FFF1F2', 'on_accent' => '#FFFFFF'],
        ];
    }

    public static function render(array $args) {
        $args = wp_parse_args($args, [
            'product'     => 'avakode',
            'title'       => '',
            'preheader'   => '',
            'eyebrow'     => '',
            'intro'       => '',
            'blocks'      => [],
            'cta'         => null,
            'footer_note' => '',
        ]);

        $palettes = self::palettes();
        $palette = $palettes[$args['product']] ?? $palettes['avakode'];
        $preheader = $args['preheader'] ?: ($args['intro'] ?: $args['title']);
        $blocks = is_array($args['blocks']) ? $args['blocks'] : [];
        $blocks_html = self::blocks_html($blocks);

        $cta_html = '';
        if (is_array($args['cta']) && !empty($args['cta']['label']) && !empty($args['cta']['url'])) {
            $cta_html = '<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="border-collapse:separate;margin:28px 0 4px 0;">'
                . '<tr><td bgcolor="' . esc_attr($palette['accent']) . '" style="border-radius:14px;background:' . esc_attr($palette['accent']) . ';mso-padding-alt:15px 24px;">'
                . '<a href="' . esc_url($args['cta']['url']) . '" style="display:inline-block;padding:15px 24px;color:' . esc_attr($palette['on_accent']) . ';font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:20px;font-weight:700;text-decoration:none;border-radius:14px;" class="forge-btn">' . self::esc($args['cta']['label']) . '</a>'
                . '</td></tr></table>';
        }

        $footer_note = $args['footer_note']
            ? '<p style="Margin:12px 0 0 0;color:#6B7280;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:18px;">' . self::esc($args['footer_note']) . '</p>'
            : '';

        $intro_html = $args['intro']
            ? '<p style="Margin:0 0 22px 0;color:#4B5563;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:25px;">' . self::esc($args['intro']) . '</p>'
            : '';

        $html = '<!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">
  <meta name="x-apple-disable-message-reformatting">
  <style>
    @media only screen and (max-width: 620px) {
      .forge-container { width: 100% !important; }
      .forge-px { padding-left: 20px !important; padding-right: 20px !important; }
      .forge-card { border-radius: 18px !important; }
      .forge-title { font-size: 28px !important; line-height: 34px !important; }
      .forge-btn { display: block !important; text-align: center !important; }
      .forge-row-label { display: block !important; width: 100% !important; padding-bottom: 4px !important; border-bottom: 0 !important; }
      .forge-row-value { display: block !important; width: 100% !important; text-align: left !important; padding-top: 0 !important; }
    }
  </style>
</head>
<body style="Margin:0;padding:0;background:#F8F9FC;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;">
  <div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;mso-hide:all;">' . self::esc($preheader) . '</div>
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F8F9FC;">
    <tr><td align="center" style="padding:32px 14px;">
      <!--[if mso]>
      <table role="presentation" width="600" align="center" cellpadding="0" cellspacing="0" border="0"><tr><td>
      <![endif]-->
      <table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" class="forge-container" style="width:600px;max-width:600px;border-collapse:separate;">
        <tr><td style="padding:0 0 14px 0;">
          <p style="Margin:0;color:#6B7280;font-family:Arial,Helvetica,sans-serif;font-size:13px;line-height:20px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;">' . self::esc($args['eyebrow'] ?: $palette['label']) . '</p>
        </td></tr>
        <tr><td class="forge-card" style="background:#FFFFFF;border:1px solid #E5E7EB;border-top:6px solid ' . esc_attr($palette['accent']) . ';border-radius:24px;overflow:hidden;">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;">
            <tr><td class="forge-px" style="padding:38px 40px 34px 40px;">
              <div style="display:inline-block;background:' . esc_attr($palette['subtle']) . ';border:1px solid ' . esc_attr($palette['accent']) . ';border-radius:999px;padding:6px 11px;color:' . esc_attr($palette['accent']) . ';font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:16px;font-weight:700;">' . self::esc($palette['label']) . '</div>
              <h1 class="forge-title" style="Margin:18px 0 12px 0;color:#1A1A2E;font-family:Arial,Helvetica,sans-serif;font-size:34px;line-height:40px;font-weight:800;">' . self::esc($args['title']) . '</h1>
              ' . $intro_html . $blocks_html . $cta_html . '
            </td></tr>
          </table>
        </td></tr>
        <tr><td style="padding:20px 6px 0 6px;text-align:center;">
          <p style="Margin:0;color:#6B7280;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:18px;">' . esc_html__('Avakode · AI-powered WordPress ecosystem', 'rankforge') . '</p>
          ' . $footer_note . '
        </td></tr>
      </table>
      <!--[if mso]>
      </td></tr></table>
      <![endif]-->
    </td></tr>
  </table>
</body>
</html>';

        return [
            'html' => $html,
            'text' => self::text_from_parts($args, $palette),
        ];
    }

    public static function send_wp($to, $subject, array $args, array $headers = []) {
        $rendered = self::render($args);
        $headers = self::html_headers($headers);
        if (!empty($args['from'])) {
            $headers[] = 'From: ' . preg_replace('/[\r\n]+/', ' ', (string) $args['from']);
        }
        $subject = preg_replace('/[\r\n]+/', ' ', wp_specialchars_decode((string) $subject, ENT_QUOTES));

        self::prime_alt_body($rendered['text']);
        add_filter('wp_mail_content_type', [__CLASS__, 'html_content_type']);
        try {
            return (bool) wp_mail($to, $subject, $rendered['html'], $headers);
        } finally {
            remove_filter('wp_mail_content_type', [__CLASS__, 'html_content_type']);
            remove_action('phpmailer_init', [__CLASS__, 'set_alt_body']);
            self::$alt_body = '';
        }
    }

    public static function html_headers(array $headers = []) {
        foreach ($headers as $header) {
            if (stripos((string) $header, 'content-type:') === 0) {
                return $headers;
            }
        }
        $headers[] = 'Content-Type: text/html; charset=UTF-8';
        return $headers;
    }

    public static function prime_alt_body($text) {
        self::$alt_body = (string) $text;
        add_action('phpmailer_init', [__CLASS__, 'set_alt_body']);
    }

    public static function html_content_type() {
        return 'text/html';
    }

    public static function set_alt_body($phpmailer) {
        if (self::$alt_body !== '' && is_object($phpmailer) && property_exists($phpmailer, 'AltBody')) {
            $phpmailer->AltBody = self::$alt_body;
        }
        remove_action('phpmailer_init', [__CLASS__, 'set_alt_body']);
        self::$alt_body = '';
    }

    private static function text_from_parts(array $args, array $palette) {
        $parts = array_filter([
            $args['eyebrow'] ?: $palette['label'],
            $args['title'],
            $args['intro'],
            self::text_from_blocks(is_array($args['blocks']) ? $args['blocks'] : []),
            is_array($args['cta'] ?? null) && !empty($args['cta']['label']) && !empty($args['cta']['url'])
                ? $args['cta']['label'] . ': ' . $args['cta']['url']
                : '',
            $args['footer_note'],
        ], function($part) {
            return (string) $part !== '';
        });
        return implode("\n\n", array_map('wp_strip_all_tags', $parts));
    }

    private static function text_from_blocks(array $blocks) {
        $parts = [];
        foreach ($blocks as $block) {
            if (is_array($block)) {
                if (!empty($parts)) {
                    $last = end($parts);
                    if (strpos((string) $last, ':') === false) {
                        $parts[] = '';
                    }
                }
                $parts[] = ($block['label'] ?? '') . ': ' . self::format_value($block['value'] ?? '');
            } else {
                $parts[] = (string) $block;
            }
        }
        return implode("\n", $parts);
    }

    private static function format_value($value) {
        if (is_array($value)) {
            return implode(', ', array_map('strval', $value));
        }
        return (string) $value;
    }

    private static function blocks_html(array $blocks) {
        $html = '';
        $rows = [];

        foreach ($blocks as $block) {
            if (is_array($block)) {
                $rows[] = $block;
                continue;
            }

            $html .= self::rows_table_html($rows);
            $rows = [];
            $html .= '<p style="Margin:0 0 16px 0;color:#4B5563;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:24px;">' . nl2br(self::esc($block), false) . '</p>';
        }

        $html .= self::rows_table_html($rows);
        return $html;
    }

    private static function rows_table_html(array $rows) {
        if (empty($rows)) {
            return '';
        }

        $row_html = '';
        foreach ($rows as $row) {
            $label = self::esc($row['label'] ?? '');
            $value = self::esc(self::format_value($row['value'] ?? ''));
            $row_html .= '<tr>'
                . '<td class="forge-row-label" style="padding:13px 0;border-bottom:1px solid #E5E7EB;color:#6B7280;font-family:Arial,Helvetica,sans-serif;font-size:13px;line-height:18px;text-transform:uppercase;">' . $label . '</td>'
                . '<td class="forge-row-value" align="right" style="padding:13px 0;border-bottom:1px solid #E5E7EB;color:#1A1A2E;font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:22px;font-weight:700;">' . $value . '</td>'
                . '</tr>';
        }

        return '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin:6px 0 24px 0;">' . $row_html . '</table>';
    }

    private static function esc($value) {
        return esc_html(self::format_value($value));
    }
}

}
