<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /templates/billing.php
// Description: Billing & Plans render template — full lifecycle UI incl. downgrade and cancel with refund preview
// Last Edited: 2026-03-30
// ==================================================
if (!defined('ABSPATH')) {
    exit;
}

$notice_html = '';
if (isset($_GET['upgrade'])) {
    if ($_GET['upgrade'] === 'success') {
        // Redirect new customers to install onboarding. Existing installs get the notice.
        if (!get_option('amai_install_completed', false)) {
            wp_safe_redirect(admin_url('admin.php?page=amai-install-onboarding'));
            exit;
        }
        $notice_html = '<div class="am-bill-notice success">&#127881; &nbsp;You\'re upgraded - welcome to the next level. Your new plan is active immediately.</div>';
    } elseif ($_GET['upgrade'] === 'cancelled') {
        $notice_html = '<div class="am-bill-notice info">Your subscription has been cancelled. You\'re now on the free plan - Facebook and Instagram stay active.</div>';
    } elseif ($_GET['upgrade'] === 'cancel') {
        $notice_html = '<div class="am-bill-notice info">No changes made - you can upgrade whenever you\'re ready.</div>';
    }
}

$is_on_paid_plan = ($current_plan !== 'free');
$sub_id          = get_option('automarketer_ai_stripe_sub_id', '');
$addon_seats     = (int) get_option('automarketer_ai_addon_seats', 0);

$addon_prices = [
    10 => ['monthly' => 'price_1TAZboJfH56oJEdkDgQ0Rlbn', 'yearly' => 'price_1TAbCFJfH56oJEdkud6GxSQX', 'price_mo' => 149,  'price_yr' => 1490],
    25 => ['monthly' => 'price_1TAbP8JfH56oJEdkt5naeX8L', 'yearly' => 'price_1TAbQnJfH56oJEdkNnqNdHOx', 'price_mo' => 299,  'price_yr' => 2990],
    50 => ['monthly' => 'price_1TAbTaJfH56oJEdkp1ahNzq1', 'yearly' => 'price_1TAbVXJfH56oJEdkoLNG4gW8', 'price_mo' => 499,  'price_yr' => 4990],
];

$plan_order    = ['free' => 0, 'starter' => 1, 'starter_pro' => 2, 'unlimited_ai' => 3, 'agency' => 4];
$current_order = $plan_order[$current_plan] ?? 0;
?>
<div id="amai-billing-root" data-current-plan="<?php echo esc_attr($current_plan); ?>">

    <div class="am-bill-header">
        <h1 class="am-bill-title">Plans &amp; Pricing</h1>
        <p class="am-bill-sub">One platform. Every channel. No per-seat nonsense - pick a plan and go.</p>
        <?php include AMAI_PLUGIN_DIR . 'templates/partials/tabs.php'; ?>
        <div class="am-global-toggle-wrap">
            <div class="am-global-toggle" id="am-global-toggle" role="button" tabindex="0" aria-label="Toggle billing period">
                <span class="am-gtog-lbl" id="am-lbl-monthly">Monthly</span>
                <div class="am-gtog-track" id="am-gtog-track">
                    <div class="am-gtog-thumb"></div>
                </div>
                <span class="am-gtog-lbl" id="am-lbl-yearly">Yearly</span>
                <span class="am-gtog-pill" id="am-gtog-pill">2 months free</span>
            </div>
        </div>
    </div>

    <?php echo $notice_html; ?>

    <div class="am-plan-grid">
        <?php foreach ($plans as $slug => $plan):
            $price_monthly    = $plan['price_monthly'];
            $price_yearly     = $plan['price_yearly'] ?? $price_monthly * 10;
            $price_id_yearly  = $plan['stripe_price_id_yearly']  ?? '';
            $price_id_monthly = $plan['stripe_price_id_monthly'] ?? '';
            $savings_amt      = number_format($price_monthly * 2, 0);
            $is_featured      = ($slug === 'starter_pro');
            $is_current       = ($slug === $current_plan);
            $is_agency        = ($slug === 'agency');
            $is_free_plan     = ($slug === 'free');
            $this_order       = $plan_order[$slug] ?? 0;
            $is_downgrade     = ($this_order < $current_order);
            $is_upgrade       = ($this_order > $current_order);

            $card_class = 'am-plan-card';
            if ($is_featured && !$is_current)           $card_class .= ' is-featured';
            if ($is_current)                            $card_class .= ' is-current';
            if ($is_free_plan && $is_on_paid_plan)      $card_class .= ' is-inactive-free';
        ?>
            <div class="<?php echo esc_attr($card_class); ?>"
                 data-slug="<?php echo esc_attr($slug); ?>"
                 data-price-monthly="<?php echo esc_attr($price_id_monthly); ?>"
                 data-price-yearly="<?php echo esc_attr($price_id_yearly); ?>"
                 data-monthly="<?php echo esc_attr((string)$price_monthly); ?>"
                 data-yearly="<?php echo esc_attr((string)$price_yearly); ?>"
                 data-savings="<?php echo esc_attr($savings_amt); ?>">

                <?php if ($is_current): ?>
                    <div class="am-plan-banner am-plan-banner--current">Your Current Plan</div>
                <?php elseif ($is_featured && !$is_current): ?>
                    <div class="am-plan-banner am-plan-banner--popular">Most Popular</div>
                <?php else: ?>
                    <div class="am-plan-banner-spacer"></div>
                <?php endif; ?>

                <div class="am-card-body">

                    <h2 class="am-plan-name"><?php echo esc_html($plan['name']); ?></h2>

                    <div class="am-price-block">
                        <?php if ($is_free_plan): ?>
                            <div class="am-price am-price--free" id="am-price-free">$0<span class="am-price-period" id="am-period-free">/yr</span></div>
                            <div class="am-price-sub">Always free, no card needed</div>
                        <?php else: ?>
                            <div class="am-price" id="am-price-<?php echo esc_attr($slug); ?>">
                                <span class="am-price-inner">$<span class="am-price-num"><?php echo esc_html((string)$price_yearly); ?></span></span>
                            </div>
                            <div class="am-price-period" id="am-period-<?php echo esc_attr($slug); ?>">/yr</div>
                            <div class="am-savings-line" id="am-savings-<?php echo esc_attr($slug); ?>">
                                <span class="am-savings-yearly">2 months free - save $<?php echo esc_html($savings_amt); ?>/yr</span>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="am-modules-line"><?php echo esc_html($plan['modules'] ?? ''); ?></div>

                    <ul class="am-features">
                        <?php foreach ($plan['features'] as $i => $feature):
                            $is_key = ($i === 0);
                        ?>
                            <li class="<?php echo $is_key ? 'am-feature--key' : ''; ?>">
                                <span class="am-feat-text">
                                    <?php echo esc_html($feature); ?>
                                    <?php if ($slug === 'starter' && strpos($feature, '5 additional') !== false): ?>
                                        <button class="am-module-link" data-modal="modules" type="button">what's a module?</button>
                                    <?php endif; ?>
                                    <?php if ($slug === 'starter_pro' && strpos($feature, 'Unlimited modules') !== false): ?>
                                        <a class="am-module-link" href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-modules')); ?>">see all</a>
                                    <?php endif; ?>
                                </span>
                            </li>
                        <?php endforeach; ?>
                    </ul>

                    <?php if (!empty($plan['bottom_text'])): ?>
                        <p class="am-pitch"><?php echo esc_html($plan['bottom_text']); ?></p>
                    <?php endif; ?>

                    <?php if ($is_agency): ?>
                        <div class="am-addon-section">
                            <div class="am-addon-label">Activations add-on (base includes 10):</div>
                            <div class="am-addon-pills">
                                <button class="am-addon-pill am-addon-pill--selected"
                                        data-seats="0"
                                        data-price-monthly=""
                                        data-price-yearly=""
                                        data-price-mo="0"
                                        data-price-yr="0"
                                        type="button">No add-on (+$0)</button>
                                <?php foreach ($addon_prices as $seats => $ap): ?>
                                    <button class="am-addon-pill<?php echo ($addon_seats === $seats && $is_current) ? ' am-addon-pill--selected' : ''; ?>"
                                            data-seats="<?php echo esc_attr((string)$seats); ?>"
                                            data-price-monthly="<?php echo esc_attr($ap['monthly']); ?>"
                                            data-price-yearly="<?php echo esc_attr($ap['yearly']); ?>"
                                            data-price-mo="<?php echo esc_attr((string)$ap['price_mo']); ?>"
                                            data-price-yr="<?php echo esc_attr((string)$ap['price_yr']); ?>"
                                            type="button">+<?php echo esc_html((string)$seats); ?> seats</button>
                                <?php endforeach; ?>
                            </div>
                            <div class="am-addon-price-line" id="am-addon-price-line"></div>
                        </div>
                    <?php endif; ?>

                </div>

                <div class="am-cta-wrap">
                    <?php if ($is_current && $is_free_plan): ?>
                        <div class="am-current-label">Active plan</div>

                    <?php elseif ($is_current && !$is_free_plan): ?>
                        <div class="am-current-label">Active plan</div>
                        <button class="am-btn-cancel"
                                type="button"
                                data-plan-name="<?php echo esc_attr($plan['name']); ?>"
                                data-sub-id="<?php echo esc_attr($sub_id); ?>"
                                data-nonce="<?php echo esc_attr(wp_create_nonce('amai_cancel_subscription')); ?>"
                                data-preview-nonce="<?php echo esc_attr(wp_create_nonce('amai_refund_preview')); ?>">
                            Cancel subscription
                        </button>

                    <?php elseif ($is_free_plan && $is_on_paid_plan): ?>
                        <button class="am-btn-downgrade"
                                type="button"
                                data-target="free"
                                data-plan-name="Free"
                                data-sub-id="<?php echo esc_attr($sub_id); ?>"
                                data-nonce="<?php echo esc_attr(wp_create_nonce('amai_cancel_subscription')); ?>"
                                data-preview-nonce="<?php echo esc_attr(wp_create_nonce('amai_refund_preview')); ?>">
                            Downgrade to Free
                        </button>

                    <?php elseif ($is_downgrade && !$is_free_plan && $is_on_paid_plan): ?>
                        <button class="am-btn-downgrade secondary"
                                type="button"
                                data-target="<?php echo esc_attr($slug); ?>"
                                data-plan-name="<?php echo esc_attr($plan['name']); ?>"
                                data-plan-id="<?php echo esc_attr($price_id_yearly); ?>"
                                data-nonce="<?php echo esc_attr(wp_create_nonce('amai_downgrade_plan')); ?>">
                            Downgrade to <?php echo esc_html($plan['name']); ?> &rarr;
                        </button>

                    <?php elseif ($is_agency && !$is_current): ?>
                        <div class="am-coming-soon-pill">Coming Soon</div>

                    <?php elseif ($is_upgrade && !$is_agency): ?>
                        <button class="am-btn-upgrade upgrade-btn<?php echo ($is_featured && !$is_current) ? '' : ' secondary'; ?>"
                                type="button"
                                data-plan-id="<?php echo esc_attr($price_id_yearly); ?>">
                            Upgrade to <?php echo esc_html($plan['name']); ?> &rarr;
                        </button>

                    <?php endif; ?>
                </div>

            </div>
        <?php endforeach; ?>
    </div>

</div>

<!-- ── Upgrade preview modal ───────────────────────────── -->
<?php if (!$is_on_paid_plan && isset($has_license) && $has_license): ?>
<div class="am-bill-deactivate-wrap">
    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="am-bill-deactivate-form">
        <input type="hidden" name="action" value="amai_deactivate_license">
        <?php wp_nonce_field('amai_deactivate_license', '_wpnonce'); ?>
        <button type="submit" class="am-bill-deactivate-btn">Deactivate license</button>
    </form>
</div>
<?php endif; ?>
<div class="am-modal-overlay" id="am-modal-upgrade" role="dialog" aria-modal="true" aria-label="Confirm upgrade">
    <div class="am-modal-box am-modal-box--upgrade">
        <div class="am-upgrade-icon">&#9650;</div>
        <h3 class="am-modal-title">Upgrade to <span id="am-up-plan-name"></span></h3>
        <p class="am-modal-sub">Here's what you're unlocking:</p>
        <div class="am-upgrade-gain-box">
            <p class="am-upgrade-gain-text" id="am-up-gain-text"></p>
        </div>
        <p class="am-upgrade-price-note" id="am-up-price-note"></p>
        <div class="am-modal-actions">
            <button class="am-modal-close am-btn-keep-upgrade" type="button">I'll do it later</button>
            <button class="am-btn-confirm-upgrade" type="button" id="am-confirm-upgrade">Yes, upgrade now</button>
        </div>
    </div>
</div>

<!-- ── Downgrade confirm modal ──────────────────────── -->
<div class="am-modal-overlay" id="am-modal-downgrade" role="dialog" aria-modal="true" aria-label="Confirm downgrade">
    <div class="am-modal-box am-modal-box--downgrade">
        <div class="am-dg-icon">&#8595;</div>
        <h3 class="am-modal-title">Downgrade to <span id="am-dg-plan-name"></span>?</h3>
        <p class="am-modal-sub">Your plan changes immediately. Here's what you'll give up:</p>
        <div class="am-dg-loss-box">
            <p class="am-dg-loss-text" id="am-dg-loss-text"></p>
        </div>
        <div class="am-modal-actions">
            <button class="am-modal-close am-btn-keep-dg" type="button">Keep my plan</button>
            <button class="am-btn-confirm-downgrade" type="button" id="am-confirm-downgrade">Yes, downgrade</button>
        </div>
    </div>
</div>

<!-- ── What's a module modal ──────────────────────────────── -->
<div class="am-modal-overlay" id="am-modal-modules" role="dialog" aria-modal="true" aria-label="What's a module?">
    <div class="am-modal-box">
        <h3 class="am-modal-title">What's a module?</h3>
        <p class="am-modal-sub">Modules are plug-and-play tools that extend what AutoMarketer AI can do - each one adds a new channel, content type, or workflow to your dashboard.</p>
        <div class="am-module-grid">
            <div class="am-module-chip"><span class="am-module-dot"></span>LinkedIn</div>
            <div class="am-module-chip"><span class="am-module-dot"></span>Pinterest</div>
            <div class="am-module-chip"><span class="am-module-dot"></span>Twitter / X</div>
            <div class="am-module-chip"><span class="am-module-dot"></span>Email campaigns</div>
            <div class="am-module-chip"><span class="am-module-dot"></span>AI image gen</div>
            <div class="am-module-chip"><span class="am-module-dot"></span>Blog writer</div>
            <div class="am-module-chip"><span class="am-module-dot"></span>Analytics hub</div>
        </div>
        <button class="am-modal-close" type="button">Got it</button>
    </div>
</div>

<!-- ── Cancel / downgrade confirmation modal ─────────────── -->
<div class="am-modal-overlay" id="am-modal-cancel" role="dialog" aria-modal="true" aria-label="Cancel subscription">
    <div class="am-modal-box am-modal-box--cancel">
        <div class="am-cancel-icon">&#9888;</div>
        <h3 class="am-modal-title" id="am-cancel-title">Cancel your subscription?</h3>
        <p class="am-modal-sub" id="am-cancel-sub">We calculate exactly what you haven't used and send it straight back.</p>
        <div class="am-refund-box" id="am-refund-box">
            <div class="am-refund-loading" id="am-refund-loading">Calculating your refund…</div>
            <div class="am-refund-amount" id="am-refund-amount" style="display:none;"></div>
            <div class="am-refund-label" id="am-refund-label" style="display:none;">will be returned to your card - no questions, no waiting</div>
        </div>
        <p class="am-refund-note" id="am-refund-note"></p>
        <div class="am-modal-actions">
            <button class="am-modal-close am-btn-keep" type="button">Keep my plan</button>
            <button class="am-btn-confirm-cancel" type="button" id="am-confirm-cancel" disabled>Yes, cancel now</button>
        </div>
    </div>
</div>