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

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

class RANKFORGE_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', 'rankforge');
        if (RANKFORGE_License::is_free()) {
            $label .= ' <span class="awaiting-mod update-plugins" style="background:#d63638;"><span class="pending-count">!</span></span>';
        }
        add_submenu_page(
            'rankforge',
            __('License & Upgrade', 'rankforge'),
            $label,
            'manage_options',
            'rankforge-license',
            [$this, 'render_page']
        );

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

    private function add_pro_badges_to_menu() {
        global $submenu;

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

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

        // Canonical Forge Suite sidebar PRO badge — thin orange chip.
        // Same shape across all 4 plugins (FieldForge / FormForge /
        // LangForge / RankForge) 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['rankforge'] 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      = RANKFORGE_License::get_plan();
        $plan_name = RANKFORGE_License::get_plan_name();
        $is_free   = RANKFORGE_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', 'rankforge'); ?>
            </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', 'rankforge'); ?></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', 'rankforge'); ?></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', 'rankforge'); ?></span>
                                <?php elseif ($plan === 'trial'): ?>
                                    <span class="sf-lp-status sf-lp-status--trial"><?php esc_html_e('Trial', 'rankforge'); ?></span>
                                <?php else: ?>
                                    <span class="sf-lp-status sf-lp-status--free"><?php esc_html_e('Free', 'rankforge'); ?></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(
                                wp_kses(
                                    /* translators: %s: URL to the Avakode licenses dashboard */
                                    __('Manage your license on <a href="%s" target="_blank" rel="noopener">Avakode</a>.', 'rankforge'),
                                    ['a' => ['href' => [], 'target' => [], 'rel' => []]]
                                ),
                                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.', 'rankforge'); ?></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.', 'rankforge'); ?></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', 'rankforge'), 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 →', 'rankforge'); ?>
                            </a>
                            <em style="margin-left:8px;"><?php esc_html_e('Opens your Avakode dashboard in a new tab.', 'rankforge'); ?></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['rankforge'])):
                $_se = $sync_errors['rankforge'];
            ?>
                <div class="notice notice-warning is-dismissible">
                    <p><strong><?php esc_html_e('License sync failed', 'rankforge'); ?></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', 'rankforge'); ?><?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.', 'rankforge'); ?></p>
                </div>
            <?php endif; ?>
                </div>
            <?php endif; ?>

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

            <!-- Install Rank 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 Rank Forge Pro to activate license', 'rankforge'); ?></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 Rank 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.', 'rankforge'); ?></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://rankforgewp.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 Rank Forge Pro', 'rankforge'); ?> &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', 'rankforge'); ?>
                            </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', 'rankforge'); ?></h2>
                </div>
                <div class="sf-lp-card-body">
                    <?php echo wp_kses_post( RANKFORGE_Upgrade_Prompt::instance()->feature_comparison_table() ); ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Upgrade CTA -->
            <?php if ($is_free): ?>
            <div class="sf-lp-upgrade-cta">
                <h3><?php esc_html_e('Unlock all RankForge Pro features', 'rankforge'); ?></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.', 'rankforge'); ?></p>
                <a href="<?php echo esc_url(RANKFORGE_License::upgrade_url()); ?>" class="sf-lp-btn sf-lp-btn--primary sf-lp-btn--lg" target="_blank">
                    <?php esc_html_e('Upgrade to Pro', 'rankforge'); ?>
                </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
    }
}
