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

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

class FORMFORGE_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_submenu'], 99);
        add_action('admin_menu', [$this, 'add_pro_badges'], 999);
    }

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

    public function add_pro_badges() {
        global $submenu;

        if (empty($submenu['formforge']) || !FORMFORGE_License::instance()->is_free()) {
            return;
        }

        $pro_slugs = [];

        // Canonical Forge Suite sidebar PRO badge — thin orange chip.
        // Same shape across all 4 plugins. Matches inline version in
        // class-core.php where Analytics submenu gets its badge.
        $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['formforge'] as &$item) {
            if (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.

        $license   = FORMFORGE_License::instance();
        $plan      = $license->get_plan();
        $plan_name = $license->get_plan_name();
        $is_pro    = $license->is_pro();

        $this->render_inline_css();
        ?>
        <div class="wrap ff-license-page" style="max-width:800px;">
            <h1 style="display:flex;align-items:center;gap:8px;margin-bottom:24px;font-size:22px;font-weight:700;">
                <span class="dashicons dashicons-admin-network" style="color:#3B82F6;font-size:24px;width:24px;height:24px;"></span>
                <?php esc_html_e('License & Upgrade', 'formforge'); ?>
            </h1>

            <!-- Current Plan Card -->
            <div class="ff-license-card">
                <h2 class="ff-license-card-title"><?php esc_html_e('Current Plan', 'formforge'); ?></h2>
                <div class="ff-plan-row">
                    <span class="ff-plan-badge ff-plan-badge--<?php echo esc_attr($plan); ?>">
                        <?php echo esc_html($plan_name); ?>
                    </span>
                    <?php if ($is_pro): ?>
                        <span class="ff-plan-status ff-plan-status--active"><?php esc_html_e('Active', 'formforge'); ?></span>
                    <?php elseif ($plan === 'trial'): ?>
                        <span class="ff-plan-status ff-plan-status--trial"><?php esc_html_e('Trial', 'formforge'); ?></span>
                    <?php else: ?>
                        <span class="ff-plan-status ff-plan-status--free"><?php esc_html_e('Limited features', 'formforge'); ?></span>
                    <?php endif; ?>
                </div>
                <?php if ($plan !== 'free') : ?>
                    <p style="margin-top:12px;">
                        <?php
                        printf(
                            wp_kses(
                                /* translators: %s: URL to the Avakode licenses dashboard */
                                __('Manage your license on <a href="%s" target="_blank" rel="noopener">Avakode</a>.', 'formforge'),
                                array( 'a' => array( 'href' => array(), 'target' => array(), 'rel' => array() ) )
                            ),
                            esc_url(
                                (class_exists('Forge_Connect') ? Forge_Connect::avakode_base() : 'https://avakode.com')
                                . '/dashboard/licenses/'
                            )
                        );
                        ?>
                    </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.', 'formforge'); ?></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.', 'formforge'); ?></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">
                    <?php /* translators: %s: error message returned by the Connect flow */ ?>
                    <p><?php printf(esc_html__('Connect failed: %s', 'formforge'), $fc_err); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $fc_err already esc_html'd at assignment ?></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 →', 'formforge'); ?>
                            </a>
                            <em style="margin-left:8px;"><?php esc_html_e('Opens your Avakode dashboard in a new tab.', 'formforge'); ?></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['formforge'])):
                $_se = $sync_errors['formforge'];
            ?>
                <div class="notice notice-warning is-dismissible">
                    <p><strong><?php esc_html_e('License sync failed', 'formforge'); ?></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', 'formforge'); ?><?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.', 'formforge'); ?></p>
                </div>
            <?php endif; ?>
                </div>
            <?php endif; ?>

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

            <!-- Install Pro guidance (no manual key entry — FC-63 v2) -->
            <?php if (!$is_pro && $plan !== 'trial' && !(function_exists('ff_freemius') && ff_freemius())) : ?>
                <div class="ff-license-card" style="border-left:4px solid #3B82F6;background:#f0f7ff;">
                    <h2 class="ff-license-card-title"><?php esc_html_e('Install Form Forge Pro', 'formforge'); ?></h2>
                    <p style="color:#475569;font-size:14px;margin:0 0 16px;"><?php esc_html_e('Pro features live inside the Form 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.', 'formforge'); ?></p>
                    <p style="margin:0;">
                        <a href="https://formforgewp.com/" target="_blank" rel="noopener" class="button button-primary" style="background:#3B82F6;border-color:#3B82F6;">
                            <?php esc_html_e('Get Form Forge Pro', 'formforge'); ?> &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', 'formforge'); ?>
                        </a>
                    </p>
                </div>
            <?php endif; ?>

            <!-- Feature Comparison -->
            <div class="ff-license-card">
                <h2 class="ff-license-card-title"><?php esc_html_e('Feature Comparison', 'formforge'); ?></h2>
                <?php echo FORMFORGE_Upgrade_Prompt::instance()->feature_comparison_table(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted pre-built markup ?>
            </div>

            <!-- Upgrade CTA -->
            <?php if (!$is_pro): ?>
            <div class="ff-upgrade-cta">
                <h2><?php esc_html_e('Unlock all Pro features', 'formforge'); ?></h2>
                <p><?php esc_html_e('Get AI generation, multi-step forms, payment fields, advanced analytics, and branded integrations.', 'formforge'); ?></p>
                <a href="<?php echo esc_url($license->upgrade_url()); ?>" target="_blank" class="ff-btn-upgrade">
                    <?php esc_html_e('Upgrade to Pro', 'formforge'); ?> &rarr;
                </a>
            </div>
            <?php endif; ?>
        </div>
        <?php
    }

    private function render_inline_css() {
        ?>
        <style>
            .ff-license-page .ff-license-card { background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:24px;margin-bottom:20px; }
            .ff-license-page .ff-license-card-title { margin:0 0 16px;font-size:15px;font-weight:600;color:#1e293b; }
            .ff-license-page .ff-plan-row { display:flex;align-items:center;gap:12px; }
            .ff-license-page .ff-plan-badge { display:inline-block;padding:4px 14px;border-radius:6px;font-size:14px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px; }
            .ff-license-page .ff-plan-badge--free { background:#f1f5f9;color:#64748b; }
            .ff-license-page .ff-plan-badge--pro { background:#3B82F6;color:#fff; }
            .ff-license-page .ff-plan-badge--trial { background:#fef3c7;color:#92400e; }
            .ff-license-page .ff-plan-status { font-size:14px;font-weight:500; }
            .ff-license-page .ff-plan-status--active { color:#16a34a; }
            .ff-license-page .ff-plan-status--trial { color:#d97706; }
            .ff-license-page .ff-plan-status--free { color:#94a3b8; }
            .ff-license-page .ff-upgrade-cta { background:linear-gradient(135deg,#3B82F6,#2563eb);border-radius:10px;padding:32px;text-align:center;color:#fff;margin-bottom:20px; }
            .ff-license-page .ff-upgrade-cta h2 { color:#fff;margin:0 0 8px;font-size:20px; }
            .ff-license-page .ff-upgrade-cta p { margin:0 0 20px;opacity:0.9;font-size:14px; }
            .ff-license-page .ff-btn-upgrade { display:inline-block;background:#fff;color:#3B82F6;text-decoration:none;padding:10px 28px;border-radius:8px;font-size:14px;font-weight:700;transition:all 0.15s; }
            .ff-license-page .ff-btn-upgrade:hover { background:#f0f4ff;color:#2563eb; }
        </style>
        <?php
    }
}
