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

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

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- LF_ is the established plugin class prefix
class LF_License_Admin {

    private static $instance = null;

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

    private function __construct() {
        $this->init_hooks();
    }

    private function init_hooks() {
        add_action('admin_menu', [$this, 'add_submenu_page'], 99);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_styles']);
    }

    
    // Menu registration
    

    public function add_submenu_page() {
        // When the plugin is on Free plan, visually hint that License page
        // is the activation entry-point (Connect to Avakode) with a red
        // bubble counter — same UX affordance WP uses for plugin updates.
        $label = __('License', 'langforge');
        if (LF_License::is_free()) {
            $label .= ' <span class="awaiting-mod update-plugins" style="background:#d63638;"><span class="pending-count">!</span></span>';
        }
        add_submenu_page(
            'lf-settings',
            __('License & Upgrade', 'langforge'),
            $label,
            'manage_options',
            'langforge-license',
            [$this, 'render_page']
        );

        $this->add_pro_badges_to_menu();
    }

    private function add_pro_badges_to_menu() {
        global $submenu;

        if (!LF_License::is_free()) {
            return;
        }

        if (empty($submenu['lf-settings'])) {
            return;
        }

        // (2026-05-05): after the hub-restructure the sub-tab
        // slugs (lf-editor, lf-glossary, lf-tm, lf-analytics,
        // lf-import-export) are HIDDEN from the sidebar entirely —
        // their PRO badges live inside the hub tab strip now. Keep
        // the legacy `langforge-*` slugs for back-compat in case any
        // installation still has them. Adding `lf-tm` for the same
        // reason (the rassyhron the tester flagged in sidebar
        // showed Free, tabs showed [PRO]). Even though the slug is
        // hidden today, the badge being correct future-proofs against
        // a future revert.
        $pro_slugs = [
            'langforge-visual-editor',
            'langforge-translation-memory',
            'langforge-glossary',
            'langforge-analytics',
            'langforge-import-export',
            'lf-editor',
            'lf-glossary',
            'lf-tm',
            'lf-analytics',
            'lf-import-export',
        ];

        // Canonical Forge Suite sidebar PRO badge — thin orange chip.
        // Same shape across all 4 plugins so the visual language stays
        // consistent regardless of plugin accent. Was previously
        // LF_Upgrade_Prompt::pro_badge (bright teal) — that style stays
        // for in-page banners / hub headers, but the sidebar uses this
        // subtle chip to match FieldForge / FormForge / SEOForge.
        $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['lf-settings'] as &$item) {
            if (in_array($item[2], $pro_slugs, true)) {
                // Idempotency: avoid double-inject if admin_menu fires twice.
                // The canonical background colour #fff4e5 is a stable marker.
                if (strpos($item[0], '#fff4e5') === false && strpos($item[0], 'lf-pro-badge') === false) {
                    $item[0] .= $badge;
                }
            }
        }
    }

    
    // Inline styles
    

    public function enqueue_styles($hook) {
        if (strpos($hook, 'langforge-license') === false) {
            return;
        }

        $css = '
        .lf-license-page {
            max-width: 800px;
            margin-top: 20px;
        }
        .lf-license-page .lf-card {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 24px 28px;
            margin-bottom: 24px;
        }
        .lf-license-page .lf-card h2 {
            margin-top: 0;
            font-size: 18px;
        }
        .lf-license-page .lf-plan-name {
            font-size: 28px;
            font-weight: 700;
            color: #1d2327;
        }
        .lf-license-page .lf-status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            text-transform: uppercase;
            margin-left: 10px;
            vertical-align: middle;
        }
        .lf-license-page .lf-status-badge.active {
            background: rgba(14,196,158,.12);
            color: #0EC49E;
        }
        .lf-license-page .lf-status-badge.free {
            background: #f0f0f0;
            color: #666;
        }
        .lf-license-page .lf-status-badge.trial {
            background: #fff3cd;
            color: #856404;
        }
        .lf-license-page .lf-cta-wrap {
            text-align: center;
            padding: 20px 0;
        }
        .lf-license-page .lf-cta-button {
            display: inline-block;
            background: #0EC49E;
            color: #fff;
            font-size: 16px;
            font-weight: 600;
            padding: 14px 40px;
            border-radius: 6px;
            text-decoration: none;
            transition: background .2s;
        }
        .lf-license-page .lf-cta-button:hover {
            background: #0ba882;
            color: #fff;
        }
        ';

        wp_add_inline_style('lf-admin', $css);
    }

    
    // Page rendering
    

    public function render_page() {
        // FC-63 v2: manual license-key activation is removed — Connect to Avakode
        // (Forge_Connect::render_button below) is the only activation path. The
        // old manual license POST handler + process_license_activation are
        // gone with it. the Testing-Tools "Reset License" tool was also
        // removed (no reset form / handler / notice).

        $plan      = LF_License::get_plan();
        $plan_name = LF_License::get_plan_name();
        $is_free   = LF_License::is_free();
        ?>
        <div class="wrap lf-license-page">
            <h1><?php esc_html_e('License & Upgrade', 'langforge'); ?></h1>

            <!-- Current Plan -->
            <div class="lf-card">
                <h2><?php esc_html_e('Current Plan', 'langforge'); ?></h2>
                <span class="lf-plan-name"><?php echo esc_html($plan_name); ?></span>
                <?php
                $badge_class = 'free';
                if ($plan === 'pro') {
                    $badge_class = 'active';
                } elseif ($plan === 'trial') {
                    $badge_class = 'trial';
                }
                ?>
                <span class="lf-status-badge <?php echo esc_attr($badge_class); ?>">
                    <?php echo esc_html(ucfirst($plan)); ?>
                </span>

                <?php if ($plan !== 'free') :
                    // (2026-04-30): point to Avakode dashboard, not
                    // the broken `langforge-account` admin slug. Freemius
                    // doesn't actually register that page in the bundle
                    // setup (only the parent plugin gets `*-account`), so
                    // the link returned "Sorry, you are not allowed to
                    // access this page". Avakode is the canonical place
                    // to manage subscriptions for the Forge Suite anyway.
                    $account_url = defined('FORGE_CONNECT_BASE_URL') && FORGE_CONNECT_BASE_URL
                        ? rtrim(FORGE_CONNECT_BASE_URL, '/') . '/dashboard/'
                        : 'https://avakode.com/dashboard/';
                ?>
                    <p style="margin-top:12px;">
                        <?php
                        printf(
                            /* translators: %s: Avakode dashboard URL */
                            __('Manage your license on the <a href="%s" target="_blank" rel="noopener">Avakode account page</a>.', 'langforge'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted pre-built markup
                            esc_url($account_url)
                        );
                        ?>
                    </p>
                <?php endif; ?>
            </div>

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

            <?php if (!empty($_GET['forge_connect_success'])) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation. ?>
                <div class="notice notice-success"><p><?php esc_html_e('Connected to Avakode successfully! Your license is active.', 'langforge'); ?></p></div>
            <?php endif; ?>
            <?php if (!empty($_GET['forge_connect_error'])) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation.
                $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'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation.
            ?>
                <div class="notice notice-error">
                    <p><?php /* translators: %s: the error message returned by the Connect/license activation flow. */ printf(esc_html__('Connect failed: %s', 'langforge'), $fc_err); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $fc_err already escaped via esc_html above ?></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 →', 'langforge'); ?>
                            </a>
                            <em style="margin-left:8px;"><?php esc_html_e('Opens your Avakode dashboard in a new tab.', 'langforge'); ?></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['langforge'])):
                $_se = $sync_errors['langforge'];
            ?>
                <div class="notice notice-warning is-dismissible">
                    <p><strong><?php esc_html_e('License sync failed', 'langforge'); ?></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', 'langforge'); ?><?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.', 'langforge'); ?></p>
                </div>
            <?php endif; ?>
                </div>
            <?php endif; ?>

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

            <!-- Get Pro (shown only when the Pro add-on isn't installed yet) -->
            <?php if ($is_free && !(function_exists('lf_freemius') && lf_freemius())) : ?>
                <div class="lf-card" style="border-left:4px solid #0EC49E;background:#f0fdf9;">
                    <h2><?php esc_html_e('Install Lang Forge Pro to activate your license', 'langforge'); ?></h2>
                    <p style="color:#475569;font-size:14px;margin-bottom:16px;"><?php esc_html_e('Pro features and license activation live in the Lang Forge Pro add-on. Install Pro, then connect this site to your Avakode account — your license activates automatically.', 'langforge'); ?></p>
                    <p style="margin:0;">
                        <a href="https://langforgewp.com/" target="_blank" rel="noopener" class="button button-primary" style="background:#0EC49E;border-color:#0EC49E;">
                            <?php esc_html_e('Get Lang Forge Pro', 'langforge'); ?> &rarr;
                        </a>
                        <a href="https://avakode.com/dashboard/" target="_blank" rel="noopener" class="button" style="margin-left:8px;">
                            <?php esc_html_e('Already purchased? Open dashboard', 'langforge'); ?>
                        </a>
                    </p>
                </div>
            <?php endif; ?>

            <!-- Feature Comparison -->
            <div class="lf-card">
                <h2><?php esc_html_e('Feature Comparison', 'langforge'); ?></h2>
                <?php LF_Upgrade_Prompt::feature_comparison_table(); ?>
            </div>

            <!-- Upgrade CTA -->
            <?php if ($is_free) : ?>
                <div class="lf-card lf-cta-wrap">
                    <a href="<?php echo esc_url(LF_License::upgrade_url()); ?>" class="lf-cta-button" target="_blank">
                        <?php esc_html_e('Upgrade to Pro', 'langforge'); ?>
                    </a>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }
}
