<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-email-templates.php
// Description: Editable email template storage, token swap, and chrome wrapping - NUCLEAR+++
// Last Edited: 2026-05-22
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class EmailTemplates
{
    // Option key prefix for stored templates
    private const OPTION_PREFIX = 'amai_email_tpl_';

    // Registry of all editable templates
    // key => [ label, subject, tokens[], dynamic_tokens[] ]
    public static function getRegistry(): array
    {
        return [
            'welcome' => [
                'label'          => 'Welcome email',
                'subject'        => 'Welcome to ' . get_bloginfo('name'),
                'tokens'         => ['{{first_name}}', '{{license_key}}', '{{login_url}}'],
                'dynamic_tokens' => [],
            ],
            'paid_welcome' => [
                'label'          => 'Paid welcome email',
                'subject'        => 'Welcome to ' . get_bloginfo('name'),
                'tokens'         => ['{{first_name}}', '{{email}}', '{{temp_password}}', '{{license_key}}', '{{login_url}}', '{{change_password_url}}'],
                'dynamic_tokens' => [],
            ],
            'upgrade_starter' => [
                'label'          => 'Upgrade email - Starter',
                'subject'        => 'You upgraded - here is what is waiting for you',
                'tokens'         => ['{{first_name}}', '{{modules_url}}'],
                'dynamic_tokens' => [],
            ],
            'upgrade_starter_pro' => [
                'label'          => 'Upgrade email - Starter Pro',
                'subject'        => 'You upgraded - here is what is waiting for you',
                'tokens'         => ['{{first_name}}', '{{modules_url}}'],
                'dynamic_tokens' => [],
            ],
            'upgrade_unlimited_ai' => [
                'label'          => 'Upgrade email - Unlimited AI',
                'subject'        => 'You upgraded - here is what is waiting for you',
                'tokens'         => ['{{first_name}}', '{{modules_url}}'],
                'dynamic_tokens' => [],
            ],
            'cancellation' => [
                'label'          => 'Cancellation email',
                'subject'        => 'Your AutoMarketer AI subscription has been cancelled',
                'tokens'         => ['{{first_name}}'],
                'dynamic_tokens' => [],
            ],
            'blog_nudge' => [
                'label'          => 'Blog email - Title picker',
                'subject'        => 'Time to write a new blog post',
                'tokens'         => ['{{first_name}}', '{{site_name}}'],
                'dynamic_tokens' => ['{{title_links}}'],
            ],
            'blog_draft_ready' => [
                'label'          => 'Blog email - Draft ready',
                'subject'        => 'We wrote a blog post for you - go take a look',
                'tokens'         => ['{{first_name}}', '{{post_title}}', '{{edit_url}}'],
                'dynamic_tokens' => ['{{score_card}}'],
            ],
            'blog_published' => [
                'label'          => 'Blog email - Published',
                'subject'        => 'AutoMarketer AI just published a new blog post for you',
                'tokens'         => ['{{first_name}}', '{{post_title}}', '{{post_url}}', '{{edit_url}}'],
                'dynamic_tokens' => ['{{score_card}}', '{{optimize_card}}', '{{issues_list}}'],
            ],
            'setup_nudge' => [
                'label'          => 'Setup nudge email',
                'subject'        => 'A few things left to set up',
                'tokens'         => ['{{first_name}}', '{{dashboard_url}}'],
                'dynamic_tokens' => ['{{nudge_items}}'],
            ],
            're_engagement' => [
                'label'          => 'Re-engagement email',
                'subject'        => 'You left a few things behind',
                'tokens'         => ['{{first_name}}', '{{store_name}}', '{{store_url}}'],
                'dynamic_tokens' => [],
            ],
            'cart_abandonment' => [
                'label'          => 'Abandoned cart - Nudge 1',
                'subject'        => 'You left something behind',
                'tokens'         => ['{{first_name}}', '{{store_name}}', '{{store_url}}', '{{cart_url}}'],
                'dynamic_tokens' => ['{{cart_items}}'],
            ],
            'cart_abandonment_2' => [
                'label'          => 'Abandoned cart - Nudge 2',
                'subject'        => 'Still thinking it over?',
                'tokens'         => ['{{first_name}}', '{{store_name}}', '{{store_url}}', '{{cart_url}}'],
                'dynamic_tokens' => ['{{cart_items}}'],
            ],
            'cart_abandonment_3' => [
                'label'          => 'Abandoned cart - Nudge 3',
                'subject'        => 'Last chance to grab your items',
                'tokens'         => ['{{first_name}}', '{{store_name}}', '{{store_url}}', '{{cart_url}}'],
                'dynamic_tokens' => ['{{cart_items}}'],
            ],
            'cart_abandonment_2_opened' => [
                'label'          => 'Abandoned cart - Nudge 2 (opened)',
                'subject'        => 'Glad you opened this - your cart is waiting',
                'tokens'         => ['{{first_name}}', '{{store_name}}', '{{store_url}}', '{{cart_url}}'],
                'dynamic_tokens' => ['{{cart_items}}'],
            ],
            'cart_abandonment_3_opened' => [
                'label'          => 'Abandoned cart - Nudge 3 (opened)',
                'subject'        => 'One last look before these go',
                'tokens'         => ['{{first_name}}', '{{store_name}}', '{{store_url}}', '{{cart_url}}'],
                'dynamic_tokens' => ['{{cart_items}}'],
            ],
            'cart_recovery' => [
                'label'          => 'Abandoned cart - Recovery alert',
                'subject'        => 'Cart recovered',
                'tokens'         => ['{{first_name}}', '{{store_name}}', '{{order_total}}'],
                'dynamic_tokens' => [],
            ],
            'comment_digest' => [
                'label'          => 'Comment digest',
                'subject'        => 'You have unread comments waiting',
                'tokens'         => ['{{first_name}}', '{{inbox_url}}'],
                'dynamic_tokens' => ['{{comment_list}}'],
            ],
            'posting_failure' => [
                'label'          => 'Post failure alert',
                'subject'        => 'A scheduled post failed to publish',
                'tokens'         => ['{{first_name}}', '{{channel}}', '{{post_type}}', '{{reason}}', '{{dashboard_url}}'],
                'dynamic_tokens' => [],
            ],
        ];
    }

    // ── Storage ────────────────────────────────────────────────────────────

    public static function save(string $type, string $subject, string $body): bool
    {
        $registry = self::getRegistry();
        if (!isset($registry[$type])) {
            return false;
        }
        update_option(self::OPTION_PREFIX . $type . '_subject', sanitize_text_field($subject), false);
        update_option(self::OPTION_PREFIX . $type . '_body', wp_kses_post($body), false);
        return true;
    }

    public static function reset(string $type): bool
    {
        $registry = self::getRegistry();
        if (!isset($registry[$type])) {
            return false;
        }
        delete_option(self::OPTION_PREFIX . $type . '_subject');
        delete_option(self::OPTION_PREFIX . $type . '_body');
        return true;
    }

    public static function hasCustom(string $type): bool
    {
        return (string) get_option(self::OPTION_PREFIX . $type . '_body', '') !== '';
    }

    public static function getSubject(string $type): string
    {
        $custom = (string) get_option(self::OPTION_PREFIX . $type . '_subject', '');
        if ($custom !== '') {
            return $custom;
        }
        return self::getRegistry()[$type]['subject'] ?? '';
    }

    public static function getBody(string $type): string
    {
        return (string) get_option(self::OPTION_PREFIX . $type . '_body', '');
    }

    // ── Chrome wrapper ─────────────────────────────────────────────────────
    // Wraps a plain HTML body in the standard email chrome.
    // Dynamic block tokens in $body are replaced from $dynamic_blocks before wrapping.

    public static function buildFromCustom(string $type, array $token_values = [], array $dynamic_blocks = []): string
    {
        $body = self::getBody($type);
        if ($body === '') {
            return '';
        }

        // Swap dynamic block tokens first
        foreach ($dynamic_blocks as $token => $html) {
            $body = str_replace($token, $html, $body);
        }

        // Swap business_name globally
        $business_name = (string) get_bloginfo('name');
        $body = str_replace('{{business_name}}', esc_html($business_name), $body);

        // Strip any remaining unresolved dynamic token chips
        $registry = self::getRegistry();
        foreach (($registry[$type]['dynamic_tokens'] ?? []) as $dt) {
            $body = str_replace($dt, '', $body);
        }

        // Swap scalar tokens
        foreach ($token_values as $token => $value) {
            $body = str_replace($token, $value, $body);
        }

        $sender_email = esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email());
        $sender_name  = esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name());

        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head>'
            . '<body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">' . esc_html($sender_name) . '</div>'
            . $body
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . esc_html($sender_name) . ' &bull; ' . $sender_email . '</p>'
            . '</td></tr></table>'
            . '</table></td></tr></table></body></html>';
    }

    // ── Default subject helper ──────────────────────────────────────────────
    // Returns the resolved subject -- custom if saved, default otherwise.
    // Scalar token swap applied to custom subjects.

    public static function resolveSubject(string $type, array $token_values = []): string
    {
        $subject = self::getSubject($type);
        foreach ($token_values as $token => $value) {
            $subject = str_replace($token, $value, $subject);
        }
        return $subject;
    }

    // ── Dynamic block renderers ────────────────────────────────────────────
    // These produce the HTML fragments injected in place of dynamic tokens.

    public static function renderTitleLinks(array $title_links): string
    {
        $out = '';
        foreach ($title_links as $idx => $item) {
            $border = $idx > 0 ? 'border-top:1px solid #F0EBE6;' : '';
            $out .= '<div style="padding:12px 0;' . $border . '">'
                . '<a href="' . esc_url((string) ($item['url'] ?? '#')) . '" style="font-size:15px;font-weight:600;color:#D97757;text-decoration:none;line-height:1.5;">'
                . esc_html((string) ($item['title'] ?? ''))
                . '</a></div>';
        }
        return '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">' . $out . '</div>';
    }

    public static function renderNudgeItems(array $items): string
    {
        $out = '';
        foreach ($items as $item) {
            $out .= '<div style="padding:8px 0;border-top:1px solid #F0EBE6;font-size:14px;color:#57534E;line-height:1.6;">' . esc_html($item) . '</div>';
        }
        return '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">' . $out . '</div>';
    }

    public static function renderScoreCard(int $score): string
    {
        if ($score >= 80) {
            $bar_color = '#10B981';
            $label     = 'Looking great';
        } elseif ($score >= 50) {
            $bar_color = '#F59E0B';
            $label     = 'A few things to tidy up';
        } else {
            $bar_color = '#EF4444';
            $label     = 'Could use some attention';
        }
        $bar_pct   = min(100, max(0, $score));
        $bar_empty = 100 - $bar_pct;
        return '<div style="margin-bottom:28px;">'
            . '<div style="font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#9E8D8A;margin-bottom:10px">Content Score</div>'
            . '<table width="100%" cellpadding="0" cellspacing="0"><tr>'
            . '<td style="font-size:32px;font-weight:700;font-family:Georgia,serif;color:#1a1a1a;width:56px;vertical-align:middle">' . $score . '</td>'
            . '<td style="vertical-align:middle;padding-left:14px">'
            . '<table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:6px"><tr>'
            . '<td style="background:' . $bar_color . ';height:6px;border-radius:3px 0 0 3px;width:' . $bar_pct . '%"></td>'
            . '<td style="background:#E7DDD5;height:6px;border-radius:0 3px 3px 0;width:' . $bar_empty . '%"></td>'
            . '</tr></table>'
            . '<span style="font-size:12px;color:#9E8D8A">' . esc_html($label) . ' &bull; out of 100</span>'
            . '</td></tr></table>'
            . '</div>';
    }

    public static function renderOptimizeCard(string $optimize_url): string
    {
        return '<div style="background:#FAF7F5;border:1.5px solid #E7DDD5;border-left:3px solid #D97757;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . '<div style="font-size:15px;font-weight:600;color:#1a1a1a;margin-bottom:6px">Let AI clean it up for you.</div>'
            . '<div style="font-size:13px;color:#6B6260;line-height:1.6;margin-bottom:16px">One click and AutoMarketer AI will automatically fix the most common issues - titles, descriptions, readability, and more. Most posts are sorted in under a minute.</div>'
            . '<a href="' . esc_url($optimize_url) . '" style="display:inline-block;background:#D97757;color:#fff;font-size:14px;font-weight:600;text-decoration:none;padding:12px 28px;border-radius:4px">Auto-Optimize this post &rarr;</a>'
            . '</div>';
    }

    public static function renderIssuesList(array $issues): string
    {
        if (empty($issues)) {
            return '';
        }
        $out = '<div style="background:#FAF7F5;border-radius:4px;padding:20px 22px;margin-bottom:28px">'
            . '<div style="font-size:13px;font-weight:600;color:#57534E;margin-bottom:12px">Auto-Optimize will take care of these:</div>';
        foreach ($issues as $idx => $issue) {
            $border = $idx > 0 ? 'border-top:1px solid #F0EBE6;' : '';
            $out .= '<div style="font-size:13px;color:#78716C;padding:8px 0;' . $border . '">&ndash; ' . esc_html((string) ($issue['message'] ?? '')) . '</div>';
        }
        $out .= '</div>';
        return $out;
    }

    // ── Default HTML for preview in editor ────────────────────────────────────
    public static function getDefault(string $type): string
    {
        $first_name    = '{{first_name}}';
        $login_url     = '{{login_url}}';
        $modules_url   = '{{modules_url}}';
        $dashboard_url = '{{dashboard_url}}';
        $site_name     = '{{site_name}}';
        $store_url     = '{{store_url}}';

        switch ($type) {
            case 'welcome':
                return \AutoMarketerAI\MarketingSite::buildWelcomeEmailHtml($first_name, '{{license_key}}', $login_url);
            case 'paid_welcome':
                return \AutoMarketerAI\MarketingSite::buildWizardWelcomeEmailHtml($first_name, '{{email}}', '{{temp_password}}', '{{license_key}}', $login_url, '{{change_password_url}}');
            case 'upgrade_starter':
                return \AutoMarketerAI\MarketingSite::buildUpgradeEmailHtmlStarter($first_name, $modules_url);
            case 'upgrade_starter_pro':
                return \AutoMarketerAI\MarketingSite::buildUpgradeEmailHtmlStarterPro($first_name, $modules_url);
            case 'upgrade_unlimited_ai':
                return \AutoMarketerAI\MarketingSite::buildUpgradeEmailHtmlUnlimitedAi($first_name, $modules_url);
            case 'cancellation':
                return \AutoMarketerAI\MarketingSite::buildCancellationEmailHtml($first_name);
            case 'blog_nudge':
                return \AutoMarketerAI\MarketingSite::buildNudgeEmailHtml($first_name, $site_name, [
                    ['title' => '5 Ways to Grow Your Business This Quarter',   'url' => '#'],
                    ['title' => 'Why Customer Reviews Matter More Than Ever',  'url' => '#'],
                    ['title' => 'How to Use Social Media to Drive More Sales', 'url' => '#'],
                ]);
            case 'blog_draft_ready':
                return \AutoMarketerAI\MarketingSite::buildDraftReadyEmailHtml($first_name, '5 Ways to Grow Your Business This Quarter', $dashboard_url, 0);
            case 'blog_published':
                return \AutoMarketerAI\MarketingSite::buildBlogPublishedEmailHtml($first_name, '5 Ways to Grow Your Business This Quarter', 0);
            case 'setup_nudge':
                return \AutoMarketerAI\MarketingSite::buildSetupNudgeEmailHtml($first_name, ['Connect a social channel', 'Set up your AI provider', 'Fill in your business profile'], $dashboard_url);
            case 're_engagement':
                return \AutoMarketerAI\MarketingSite::buildReEngagementEmailHtml($first_name, $site_name, $store_url);
            case 'cart_abandonment':
            case 'cart_abandonment_2':
            case 'cart_abandonment_3':
            case 'cart_abandonment_2_opened':
            case 'cart_abandonment_3_opened':
                return self::buildCartAbandonmentDefault();
            case 'cart_recovery':
                return self::buildCartRecoveryDefault();
            case 'comment_digest':
                return self::buildCommentDigestDefault();
            case 'posting_failure':
                return self::buildPostingFailureDefault();
            default:
                return '';
        }
    }

    // ── Default HTML builders for types without MarketingSite methods ──────

    private static function chromeWrap(string $body): string
    {
        $sender_email = esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_email());
        $sender_name  = esc_html(\AutoMarketerAI\AbstractEmailProvider::get_sender_name());
        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><style>:root{color-scheme:light}</style></head>'
            . '<body style="margin:0;padding:0;background:#F0EBE6;font-family:Helvetica Neue,Helvetica,Arial,sans-serif">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#F0EBE6"><tr><td align="center" style="padding:32px 16px">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;margin:0 auto;background:#ffffff;border-radius:4px;overflow:hidden">'
            . '<div style="height:4px;background:#D97757"></div>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:40px 48px">'
            . '<div style="font-family:Georgia,serif;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:#D97757;margin-bottom:20px">' . $sender_name . '</div>'
            . $body
            . '</td></tr></table>'
            . '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding:24px 48px;background:#FAF7F5;border-top:1px solid #F0EBE6">'
            . '<p style="margin:0;font-size:11px;color:#B8A9A6;line-height:1.6;text-align:center">' . $sender_name . ' &bull; ' . $sender_email . '</p>'
            . '</td></tr></table>'
            . '</table></td></tr></table></body></html>';
    }

    private static function buildCartAbandonmentDefault(): string
    {
        $body = '<p style="font-size:16px;color:#1C1917;line-height:1.7;margin:0 0 20px">Hi {{first_name}},</p>'
            . '<p style="font-size:15px;color:#57534E;line-height:1.7;margin:0 0 28px">You left some items in your cart at {{store_name}}. They are still waiting for you.</p>'
            . '{{cart_items}}'
            . '<p style="margin:28px 0"><a href="{{cart_url}}" style="display:inline-block;background:#D97757;color:#ffffff;font-size:15px;font-weight:600;text-decoration:none;padding:14px 32px;border-radius:4px">Complete your order</a></p>'
            . '<p style="font-size:13px;color:#78716C;line-height:1.6;margin:0">- The {{business_name}} Team</p>';
        return self::chromeWrap($body);
    }

    private static function buildCartRecoveryDefault(): string
    {
        $body = '<p style="font-size:16px;color:#1C1917;line-height:1.7;margin:0 0 20px">Hi {{first_name}},</p>'
            . '<p style="font-size:15px;color:#57534E;line-height:1.7;margin:0 0 28px">Great news -- your order at {{store_name}} was completed successfully. Total charged: {{order_total}}.</p>'
            . '<p style="font-size:15px;color:#57534E;line-height:1.7;margin:0 0 28px">Thank you for your purchase. If you have any questions, just reply to this email.</p>'
            . '<p style="font-size:13px;color:#78716C;line-height:1.6;margin:0">- The {{business_name}} Team</p>';
        return self::chromeWrap($body);
    }

    private static function buildCommentDigestDefault(): string
    {
        $body = '<p style="font-size:16px;color:#1C1917;line-height:1.7;margin:0 0 20px">Hi {{first_name}},</p>'
            . '<p style="font-size:15px;color:#57534E;line-height:1.7;margin:0 0 28px">You have unread comments waiting in your inbox.</p>'
            . '{{comment_list}}'
            . '<p style="margin:28px 0"><a href="{{inbox_url}}" style="display:inline-block;background:#D97757;color:#ffffff;font-size:15px;font-weight:600;text-decoration:none;padding:14px 32px;border-radius:4px">View your inbox</a></p>'
            . '<p style="font-size:13px;color:#78716C;line-height:1.6;margin:0">- The {{business_name}} Team</p>';
        return self::chromeWrap($body);
    }

    private static function buildPostingFailureDefault(): string
    {
        $body = '<p style="font-size:16px;color:#1C1917;line-height:1.7;margin:0 0 20px">Hi {{first_name}},</p>'
            . '<p style="font-size:15px;color:#57534E;line-height:1.7;margin:0 0 12px">A scheduled post failed to publish. Here are the details:</p>'
            . '<table style="width:100%;border-collapse:collapse;margin-bottom:28px">'
            . '<tr><td style="padding:10px 14px;font-size:13px;color:#78716C;background:#FAF7F5;border:1px solid #F0EBE6;width:120px">Channel</td><td style="padding:10px 14px;font-size:14px;color:#1C1917;border:1px solid #F0EBE6">{{channel}}</td></tr>'
            . '<tr><td style="padding:10px 14px;font-size:13px;color:#78716C;background:#FAF7F5;border:1px solid #F0EBE6">Post type</td><td style="padding:10px 14px;font-size:14px;color:#1C1917;border:1px solid #F0EBE6">{{post_type}}</td></tr>'
            . '<tr><td style="padding:10px 14px;font-size:13px;color:#78716C;background:#FAF7F5;border:1px solid #F0EBE6">Reason</td><td style="padding:10px 14px;font-size:14px;color:#1C1917;border:1px solid #F0EBE6">{{reason}}</td></tr>'
            . '</table>'
            . '<p style="margin:0 0 28px"><a href="{{dashboard_url}}" style="display:inline-block;background:#D97757;color:#ffffff;font-size:15px;font-weight:600;text-decoration:none;padding:14px 32px;border-radius:4px">Go to dashboard</a></p>'
            . '<p style="font-size:13px;color:#78716C;line-height:1.6;margin:0">- The {{business_name}} Team</p>';
        return self::chromeWrap($body);
    }
}
