<?php
/**
 * License admin page — plan status & upgrade CTA.
 *
 * Activation / deactivation is handled by Freemius's own Account page.
 *
 * @package SEOForge
 */

if (!defined('ABSPATH')) exit;

class SEOFORGE_License_Admin {

    private static $instance = null;

    public static function instance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action('admin_menu', [$this, 'register_menu'], 99);
    }

    public function register_menu() {
        $label = __('License', 'seoforge');
        if (SEOFORGE_License::is_free()) {
            $label .= ' <span class="awaiting-mod update-plugins" style="background:#d63638;"><span class="pending-count">!</span></span>';
        }
        add_submenu_page(
            'seoforge',
            __('License & Upgrade', 'seoforge'),
            $label,
            'manage_options',
            'seoforge-license',
            [$this, 'render_page']
        );

        if (SEOFORGE_License::is_free()) {
            $this->add_pro_badges_to_menu();
        }
    }

    private function add_pro_badges_to_menu() {
        global $submenu;

        if (empty($submenu['seoforge'])) {
            return;
        }

        $pro_slugs = [
            'seoforge-redirects',
            'seoforge-rankings',
            'seoforge-decay',
            'seoforge-local',
            'seoforge-brief',
            'seoforge-broken',
            'seoforge-audit',
        ];

        // Canonical Forge Suite sidebar PRO badge — thin orange chip.
        // Same shape across all 4 plugins (FieldForge / FormForge /
        // LangForge / SEOForge) so the visual language stays consistent.
        $badge = ' <span style="display:inline-block;background:#fff4e5;color:#b45309;border:1px solid #fcd9a8;border-radius:3px;font-size:10px;font-weight:700;padding:1px 5px;letter-spacing:.4px;text-transform:uppercase;line-height:1;vertical-align:middle;margin-left:4px;">PRO</span>';

        foreach ($submenu['seoforge'] as &$item) {
            if (isset($item[2]) && in_array($item[2], $pro_slugs, true)) {
                $item[0] .= $badge;
            }
        }
    }

    // FC-63 v2: manual license-key activation removed — Connect to Avakode is the only activation path.

    public function render_page() {
        // FC-63 v2: manual license-key activation removed — Connect to Avakode is the only activation path.
        // the Testing-Tools "Reset License" tool was also removed.

        $plan      = SEOFORGE_License::get_plan();
        $plan_name = SEOFORGE_License::get_plan_name();
        $is_free   = SEOFORGE_License::is_free();
        ?>
        <div class="wrap sf-license-page" style="max-width:860px;">

            <h1 style="display:flex;align-items:center;gap:10px;margin-bottom:20px;padding-bottom:14px;border-bottom:2px solid #FF6B35;font-size:22px;font-weight:700;">
                <span class="dashicons dashicons-admin-network" style="color:#FF6B35;font-size:24px;width:24px;height:24px;"></span>
                <?php esc_html_e('License & Upgrade', 'seoforge'); ?>
            </h1>

            <!-- Current Plan card -->
            <div class="sf-lp-card">
                <div class="sf-lp-card-head">
                    <span class="dashicons dashicons-shield"></span>
                    <h2><?php esc_html_e('Current Plan', 'seoforge'); ?></h2>
                </div>
                <div class="sf-lp-card-body">
                    <div class="sf-lp-plan-row">
                        <div>
                            <span class="sf-lp-plan-label"><?php esc_html_e('Plan', 'seoforge'); ?></span>
                            <span class="sf-lp-plan-value">
                                <?php echo esc_html($plan_name); ?>
                                <?php if ($plan === 'pro'): ?>
                                    <span class="sf-lp-status sf-lp-status--active"><?php esc_html_e('Active', 'seoforge'); ?></span>
                                <?php elseif ($plan === 'trial'): ?>
                                    <span class="sf-lp-status sf-lp-status--trial"><?php esc_html_e('Trial', 'seoforge'); ?></span>
                                <?php else: ?>
                                    <span class="sf-lp-status sf-lp-status--free"><?php esc_html_e('Free', 'seoforge'); ?></span>
                                <?php endif; ?>
                            </span>
                        </div>
                    </div>
                    <?php if ($plan !== 'free') : ?>
                        <p style="margin-top:12px;">
                            <?php
                            // link out to avakode dashboard instead of the Freemius
                            // Account page. The Freemius Account submenu is hidden via
                            // 'account' => false, but visiting its URL directly would
                            // re-register the submenu for the rest of the request.
                            printf(
                                /* translators: %s: URL to the Avakode licenses dashboard */
                                __('Manage your license on <a href="%s" target="_blank" rel="noopener">Avakode</a>.', 'seoforge'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted string literal with intentional anchor markup; URL arg is esc_url
                                esc_url(
                                    (class_exists('Forge_Connect') ? Forge_Connect::avakode_base() : 'https://avakode.com')
                                    . '/dashboard/licenses/'
                                )
                            );
                            ?>
                        </p>
                    <?php endif; ?>
                </div>
            </div>

            <?php // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation. ?>
            <?php if (isset($_GET['activated'])) : ?>
                <div class="notice notice-success"><p><?php esc_html_e('License activated successfully! Pro features are now available.', 'seoforge'); ?></p></div>
            <?php endif; ?>

            <?php // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation. ?>
            <?php if (!empty($_GET['forge_connect_success'])) : ?>
                <div class="notice notice-success"><p><?php esc_html_e('Connected to Avakode successfully! Your license is active.', 'seoforge'); ?></p></div>
            <?php endif; ?>
            <?php
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation.
            if (!empty($_GET['forge_connect_error'])) :
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Read-only admin notice; value escaped via esc_html for display.
                $fc_err      = esc_html(sanitize_text_field(wp_unslash($_GET['forge_connect_error'])));
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation.
                $fc_code     = !empty($_GET['forge_connect_code']) ? sanitize_text_field(wp_unslash($_GET['forge_connect_code'])) : '';
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation.
                $fc_move_url = !empty($_GET['forge_connect_move_url']) ? esc_url_raw(wp_unslash($_GET['forge_connect_move_url'])) : '';
            ?>
                <div class="notice notice-error">
                    <?php /* translators: %s: connection error message returned by the server */ ?>
                    <p><?php printf(esc_html__('Connect failed: %s', 'seoforge'), esc_html( $fc_err )); ?></p>
                    <?php if ($fc_code === 'SITE_MISMATCH' && $fc_move_url) : ?>
                        <p>
                            <a href="<?php echo esc_url($fc_move_url); ?>" class="button button-primary" target="_blank" rel="noopener">
                                <?php esc_html_e('Move license to this site →', 'seoforge'); ?>
                            </a>
                            <em style="margin-left:8px;"><?php esc_html_e('Opens your Avakode dashboard in a new tab.', 'seoforge'); ?></em>
                        </p>
                    <?php endif; ?>
            <?php
            // Surface any activate_in_freemius failure from the latest
            // Connect. Stored by Forge_Connect::record_sync_error;
            // cleared on next successful sync.
            $sync_errors = get_option('forge_connect_sync_errors', []);
            if (!empty($sync_errors['seoforge'])):
                $_se = $sync_errors['seoforge'];
            ?>
                <div class="notice notice-warning is-dismissible">
                    <p><strong><?php esc_html_e('License sync failed', 'seoforge'); ?></strong></p>
                    <p><?php echo esc_html($_se['msg']); ?>
                    <em>(<?php echo esc_html($_se['class'] ?? ''); ?><?php if (!empty($_se['file'])): ?> in <?php echo esc_html($_se['file'] . ':' . ($_se['line'] ?? '?')); ?><?php endif; ?><?php if (!empty($_se['ts'])): ?>, <?php echo esc_html(human_time_diff((int)$_se['ts'])); ?> <?php esc_html_e('ago', 'seoforge'); ?><?php endif; ?>)</em></p>
                    <p><?php esc_html_e('Your license is active via Avakode — the plugin works normally. To clear any leftover license banners, open Forge Suite dashboard and click Deactivate → Connect again.', 'seoforge'); ?></p>
                </div>
            <?php endif; ?>
                </div>
            <?php endif; ?>

            <!-- Forge Connect (SSO) -->
            <?php if (class_exists('Forge_Connect')) {
                Forge_Connect::render_button('seoforge', '#FF6B35', 'license');
            } ?>

            <!-- Install SEO Forge Pro guidance (FC-63 v2: manual key entry removed) -->
            <?php if ($is_free && !(function_exists('sf_freemius') && sf_freemius())) : ?>
                <div class="sf-lp-card" style="border-left:4px solid #FF6B35;background:#fff7f3;">
                    <div class="sf-lp-card-head">
                        <span class="dashicons dashicons-admin-network" style="color:#FF6B35;"></span>
                        <h2><?php esc_html_e('Install SEO Forge Pro to activate license', 'seoforge'); ?></h2>
                    </div>
                    <div class="sf-lp-card-body">
                        <p style="color:#475569;font-size:14px;margin:0 0 16px;"><?php esc_html_e('License activation lives inside the SEO Forge Pro add-on. Install Pro first — then return here, or your license will activate automatically once the Pro add-on connects to your Avakode dashboard.', 'seoforge'); ?></p>
                        <?php // flex row so the two CTAs share a baseline and even
                        // height instead of sitting crookedly as inline buttons in a <p>. ?>
                        <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
                            <a href="https://seoforgewp.com/" target="_blank" rel="noopener" class="button button-primary" style="background:#FF6B35;border-color:#FF6B35;display:inline-flex;align-items:center;">
                                <?php esc_html_e('Get SEO Forge Pro', 'seoforge'); ?> &rarr;
                            </a>
                            <a href="https://avakode.com/dashboard/" target="_blank" rel="noopener" class="button" style="display:inline-flex;align-items:center;">
                                <?php esc_html_e('Already purchased? Open dashboard', 'seoforge'); ?>
                            </a>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Feature Comparison — only rendered for Free users who
 haven't upgraded yet. Pro users don't need the table taking
 up half the page; their license section already says everything. -->
            <?php if ($is_free): ?>
            <div class="sf-lp-card">
                <div class="sf-lp-card-head">
                    <span class="dashicons dashicons-editor-table"></span>
                    <h2><?php esc_html_e('Feature Comparison', 'seoforge'); ?></h2>
                </div>
                <div class="sf-lp-card-body">
                    <?php echo SEOFORGE_Upgrade_Prompt::instance()->feature_comparison_table(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted pre-built markup from render helper ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Upgrade CTA -->
            <?php if ($is_free): ?>
            <div class="sf-lp-upgrade-cta">
                <h3><?php esc_html_e('Unlock all SEOForge Pro features', 'seoforge'); ?></h3>
                <p><?php esc_html_e('Get AI Meta Generation, Google Search Console, Site Audit, Content Optimizer, Internal Links, A/B Testing, and Broken Links.', 'seoforge'); ?></p>
                <a href="<?php echo esc_url(SEOFORGE_License::upgrade_url()); ?>" class="sf-lp-btn sf-lp-btn--primary sf-lp-btn--lg" target="_blank">
                    <?php esc_html_e('Upgrade to Pro', 'seoforge'); ?>
                </a>
            </div>
            <?php endif; ?>

        </div>

        <style>
.sf-license-page .sf-lp-card { background:#fff;border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,0.06);margin-bottom:20px; }
        .sf-license-page .sf-lp-card-head { display:flex;align-items:center;gap:10px;padding:16px 20px;border-bottom:1px solid #e2e8f0;background:#f8fafc; }
        .sf-license-page .sf-lp-card-head .dashicons { color:#FF6B35;font-size:18px;width:18px;height:18px; }
        .sf-license-page .sf-lp-card-head h2 { margin:0;font-size:15px;font-weight:600; }
        .sf-license-page .sf-lp-card-body { padding:20px; }
        .sf-license-page .sf-lp-plan-row { display:flex;gap:40px; }
        .sf-license-page .sf-lp-plan-label { display:block;font-size:14px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:0.4px;margin-bottom:4px; }
        .sf-license-page .sf-lp-plan-value { display:flex;align-items:center;gap:8px;font-size:16px;font-weight:700;color:#1e293b; }
        .sf-license-page .sf-lp-status { display:inline-block;font-size:14px;font-weight:600;padding:2px 8px;border-radius:4px;text-transform:uppercase;letter-spacing:0.4px; }
        .sf-license-page .sf-lp-status--active { background:#dcfce7;color:#166534; }
        .sf-license-page .sf-lp-status--trial { background:#FFF7ED;color:#9a3412; }
        .sf-license-page .sf-lp-status--free { background:#f1f5f9;color:#64748b; }
        .sf-license-page .sf-lp-btn { display:inline-block;border:none;border-radius:8px;padding:9px 20px;font-size:14px;font-weight:600;cursor:pointer;text-decoration:none;transition:all 0.15s;line-height:1.4; }
        /* admin.css sets `.sf-admin .wrap a { color: var(--accent) }`
 (orange) at specificity (0,2,1) — higher than this button rule (0,2,0).
 That painted the CTA text the same orange as its background → invisible.
 Force white with !important so the global link color can never win. */
        .sf-license-page .sf-lp-btn--primary { background:#FF6B35;color:#fff !important;box-shadow:0 2px 8px rgba(255,107,53,0.2); }
        .sf-license-page .sf-lp-btn--primary:hover { background:#F05E28;color:#fff !important;transform:translateY(-1px);box-shadow:0 4px 16px rgba(255,107,53,0.3); }
        .sf-license-page .sf-lp-btn--lg { padding:12px 32px;font-size:15px;border-radius:10px; }
        .sf-license-page .sf-lp-upgrade-cta { text-align:center;background:linear-gradient(135deg,#FFF7ED,#FFEDD5);border:1px solid #FED7AA;border-radius:12px;padding:32px 24px;margin-bottom:20px; }
        .sf-license-page .sf-lp-upgrade-cta h3 { margin:0 0 8px;font-size:18px;font-weight:700;color:#1e293b; }
        .sf-license-page .sf-lp-upgrade-cta p { margin:0 0 20px;font-size:14px;color:#64748b; }
        </style>
        <?php
    }
}
