<?php
if (!defined('ABSPATH')) exit;

class SEOFORGE_Upgrade_Prompt {
    private static $instance = null;

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

    private function __construct() {
        add_action('admin_enqueue_scripts', [$this, 'enqueue_styles']);
    }

    /**
 * Enqueue inline styles only on SEOForge admin pages.
 */
    public function enqueue_styles($hook) {
        $screen = get_current_screen();
        if (!$screen || strpos($screen->id, 'seoforge') === false) {
            return;
        }

        add_action('admin_head', [$this, 'render_inline_css']);
    }

    /**
 * Render scoped inline CSS for upgrade prompts.
 */
    public function render_inline_css() {
        ?>
        <style>
        .sf-admin .sf-upgrade-overlay {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 400px;
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            text-align: center;
            padding: 48px 24px;
        }
        .sf-admin .sf-upgrade-overlay-inner {
            max-width: 480px;
        }
        .sf-admin .sf-upgrade-lock-icon {
            font-size: 48px;
            color: #94a3b8;
            margin-bottom: 16px;
        }
        .sf-admin .sf-upgrade-overlay h2 {
            font-size: 24px;
            font-weight: 700;
            color: #1e293b;
            margin: 0 0 8px;
        }
        .sf-admin .sf-upgrade-overlay p {
            font-size: 15px;
            color: #64748b;
            line-height: 1.6;
            margin: 0 0 24px;
        }
        .sf-admin .sf-upgrade-cta {
            display: inline-block;
            background: linear-gradient(135deg, #FF6B35, #E05520);
            color: #fff !important;
            font-size: 15px;
            font-weight: 600;
            padding: 12px 32px;
            border-radius: 8px;
            text-decoration: none !important;
            transition: transform 0.15s, box-shadow 0.15s;
            box-shadow: 0 2px 8px rgba(255, 107, 53, 0.3);
        }
        .sf-admin .sf-upgrade-cta:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 16px rgba(255, 107, 53, 0.4);
        }
        .sf-admin .sf-upgrade-inline-lock {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            position: relative;
            cursor: default;
        }
        .sf-admin .sf-upgrade-inline-badge {
            display: inline-flex;
            align-items: center;
            gap: 3px;
            background: #f1f5f9;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            padding: 2px 8px;
            font-size: 14px;
            font-weight: 600;
            color: #94a3b8;
        }
        .sf-admin .sf-upgrade-inline-badge .dashicons {
            font-size: 14px;
            width: 12px;
            height: 12px;
            line-height: 12px;
        }
        .sf-admin .sf-upgrade-inline-tooltip {
            display: none;
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background: #1e293b;
            color: #fff;
            font-size: 14px;
            font-weight: 400;
            padding: 6px 12px;
            border-radius: 6px;
            white-space: nowrap;
            margin-bottom: 6px;
            z-index: 100;
        }
        .sf-admin .sf-upgrade-inline-tooltip::after {
            content: '';
            position: absolute;
            top: 100%;
            left: 50%;
            transform: translateX(-50%);
            border: 5px solid transparent;
            border-top-color: #1e293b;
        }
        .sf-admin .sf-upgrade-inline-lock:hover .sf-upgrade-inline-tooltip {
            display: block;
        }
        .sf-admin .sf-upgrade-comparison-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            overflow: hidden;
        }
        .sf-admin .sf-upgrade-comparison-table th,
        .sf-admin .sf-upgrade-comparison-table td {
            padding: 12px 16px;
            text-align: left;
            border-bottom: 1px solid #e2e8f0;
        }
        .sf-admin .sf-upgrade-comparison-table thead th {
            background: #f8fafc;
            font-weight: 700;
            color: #1e293b;
        }
        .sf-admin .sf-upgrade-comparison-table thead th:nth-child(2),
        .sf-admin .sf-upgrade-comparison-table thead th:nth-child(3) {
            text-align: center;
            width: 100px;
        }
        .sf-admin .sf-upgrade-comparison-table td:nth-child(2),
        .sf-admin .sf-upgrade-comparison-table td:nth-child(3) {
            text-align: center;
        }
        .sf-admin .sf-upgrade-check {
            color: #22c55e;
            font-weight: 700;
        }
        .sf-admin .sf-upgrade-cross {
            color: #cbd5e1;
        }
        .sf-admin .sf-pro-badge {
            display: inline-block;
            background: linear-gradient(135deg, #FF6B35, #E05520);
            color: #fff;
            font-size: 14px;
            font-weight: 700;
            padding: 2px 6px;
            border-radius: 4px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            line-height: 1.4;
            vertical-align: middle;
        }
        .sf-admin .sf-upgrade-trial-banner {
            background: linear-gradient(135deg, #FFF7ED, #FFEDD5);
            border: 1px solid #FED7AA;
            border-radius: 8px;
            padding: 12px 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 16px;
        }
        .sf-admin .sf-upgrade-trial-banner-text {
            font-size: 14px;
            color: #9a3412;
            font-weight: 500;
        }
        .sf-admin .sf-upgrade-trial-banner-text strong {
            font-weight: 700;
        }
        .sf-admin .sf-upgrade-trial-dismiss {
            background: none;
            border: none;
            color: #c2410c;
            cursor: pointer;
            font-size: 18px;
            padding: 0 4px;
            line-height: 1;
        }
        .sf-admin .sf-upgrade-trial-dismiss:hover {
            color: #7c2d12;
        }
        </style>
        <?php
    }

    /**
 * Get feature label and description from slug.
 */
    private function get_feature_info($feature_slug) {
        $features = [
            'meta_generator'   => [
                'name'        => __('Meta Generator', 'seoforge'),
                'description' => __('Automatically generate optimized meta titles, descriptions, and Open Graph tags powered by AI.', 'seoforge'),
            ],
            'schema_builder'   => [
                'name'        => __('Schema Builder', 'seoforge'),
                'description' => __('Generate rich schema markup with template-based detection for Articles, FAQ, Product, HowTo, and more, plus optional AI detection.', 'seoforge'),
            ],
            'internal_links'   => [
                'name'        => __('Internal Link Suggestions', 'seoforge'),
                'description' => __('Get AI-powered internal link suggestions to improve site structure and boost SEO.', 'seoforge'),
            ],
            'auto_links'       => [
                'name'        => __('Auto Internal Links', 'seoforge'),
                'description' => __('Automatically insert contextual internal links when publishing new content.', 'seoforge'),
            ],
            'site_audit'       => [
                'name'        => __('Site Audit', 'seoforge'),
                'description' => __('Run comprehensive site-wide SEO audits with AI-powered prioritized action plans.', 'seoforge'),
            ],
            'content_optimizer' => [
                'name'        => __('Content Optimizer', 'seoforge'),
                'description' => __('Get AI-driven suggestions to improve content depth, structure, and keyword optimization.', 'seoforge'),
            ],
            'image_seo'       => [
                'name'        => __('Image SEO', 'seoforge'),
                'description' => __('Auto-generate alt text, clean filenames, and optimize images for search engines.', 'seoforge'),
            ],
            'gsc'              => [
                'name'        => __('Google Search Console', 'seoforge'),
                'description' => __('Track keyword rankings, detect content decay, and sync data from Google Search Console.', 'seoforge'),
            ],
            'local_seo'       => [
                'name'        => __('Local SEO', 'seoforge'),
                'description' => __('Add LocalBusiness schema, manage business info, and improve local search visibility.', 'seoforge'),
            ],
            'ab_testing'       => [
                'name'        => __('A/B Testing', 'seoforge'),
                'description' => __('Test different meta titles and descriptions to find the best performing variants.', 'seoforge'),
            ],
            'redirects'        => [
                'name'        => __('Redirect Manager', 'seoforge'),
                'description' => __('Manage 301/302 redirects, auto-redirect on slug changes, and track 404 errors.', 'seoforge'),
            ],
        ];

        return $features[$feature_slug] ?? [
            'name'        => ucwords(str_replace('_', ' ', $feature_slug)),
            'description' => __('This feature requires SEOForge Pro.', 'seoforge'),
        ];
    }

    /**
 * Render a full-page lock overlay for a gated feature.
 *
 * @param string $feature_slug
 */
    public function locked_page($feature_slug) {
        $info = $this->get_feature_info($feature_slug);
        $upgrade_url = SEOFORGE_License::instance()->upgrade_url();
        ?>
        <div class="wrap sf-admin">
        <?php if (class_exists('SEOFORGE_Admin_Tabs')) { SEOFORGE_Admin_Tabs::render(); } ?>
        <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:400px;padding:48px 24px;text-align:center;background:linear-gradient(135deg,#f8fafc 0%,#f1f5f9 100%);border:1px solid #e2e8f0;border-radius:16px;max-width:580px;margin:40px auto;">
            <div style="font-size:48px;color:#94a3b8;margin-bottom:16px;"><span class="dashicons dashicons-lock" style="font-size:48px;width:48px;height:48px;"></span></div>
            <h2 style="margin:0 0 8px;font-size:24px;font-weight:700;color:#1e293b;"><?php echo esc_html($info['name']); ?> <?php echo $this->pro_badge(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted pre-built markup from render helper ?></h2>
            <p style="margin:0 0 24px;font-size:15px;color:#64748b;line-height:1.6;max-width:440px;"><?php echo esc_html($info['description']); ?></p>
            <a href="<?php echo esc_url($upgrade_url); ?>" target="_blank" style="display:inline-block;padding:12px 32px;background:linear-gradient(135deg,#FF6B35,#E05520);color:#fff !important;text-decoration:none !important;border-radius:12px;font-size:15px;font-weight:600;box-shadow:0 2px 8px rgba(255,107,53,0.3);transition:transform 0.15s,box-shadow 0.15s;">
                <?php esc_html_e('Upgrade to Pro', 'seoforge'); ?>
            </a>
        </div>
        </div><?php /* .wrap */ ?>
        <?php
    }

    /**
 * Return inline lock badge + tooltip HTML for a gated feature.
 *
 * @param string $feature_slug
 * @return string
 */
    public function inline_lock($feature_slug) {
        $info = $this->get_feature_info($feature_slug);
        $upgrade_url = SEOFORGE_License::instance()->upgrade_url();

        $html  = '<span class="sf-upgrade-inline-lock">';
        $html .= '<span class="sf-upgrade-inline-badge">';
        $html .= '<span class="dashicons dashicons-lock"></span> ';
        $html .= esc_html__('PRO', 'seoforge');
        $html .= '</span>';
        $html .= '<span class="sf-upgrade-inline-tooltip">';
        $html .= esc_html($info['name']) . ' &mdash; ';
        $html .= '<a href="' . esc_url($upgrade_url) . '" style="color:#FF6B35;">' . esc_html__('Upgrade', 'seoforge') . '</a>';
        $html .= '</span>';
        $html .= '</span>';

        return $html;
    }

    /**
 * Render a Free vs Pro feature comparison table.
 *
 * @return string
 */
    public function feature_comparison_table() {
        $features = SEOFORGE_License::instance()->get_features();

        $html  = '<div class="sf-admin">';
        $html .= '<table class="sf-upgrade-comparison-table">';
        $html .= '<thead><tr>';
        $html .= '<th>' . esc_html__('Feature', 'seoforge') . '</th>';
        $html .= '<th>' . esc_html__('Free', 'seoforge') . '</th>';
        $html .= '<th>' . esc_html__('Pro', 'seoforge') . '</th>';
        $html .= '</tr></thead>';
        $html .= '<tbody>';

        foreach ($features as $feature) {
            $name = esc_html($feature['label'] ?? $feature['name'] ?? $feature['slug'] ?? '');
            $plans = $feature['plans'] ?? [];
            $in_free = in_array('free', $plans, true);
            $in_pro  = in_array('pro', $plans, true) || in_array('trial', $plans, true) || true; // all features are in pro

            $free_mark = $in_free
                ? '<span class="sf-upgrade-check">&#10003;</span>'
                : '<span class="sf-upgrade-cross">&mdash;</span>';
            $pro_mark = '<span class="sf-upgrade-check">&#10003;</span>';

            $html .= '<tr>';
            $html .= '<td>' . $name . '</td>';
            $html .= '<td>' . $free_mark . '</td>';
            $html .= '<td>' . $pro_mark . '</td>';
            $html .= '</tr>';
        }

        $html .= '</tbody></table>';
        $html .= '</div>';

        return $html;
    }

    /**
 * Return a PRO badge span.
 *
 * @return string
 */
    public function pro_badge() {
        return '<span class="sf-pro-badge">PRO</span>';
    }

    /**
 * Render a dismissible trial days-remaining banner.
 */
    public function maybe_show_trial_banner() {
        $license = SEOFORGE_License::instance();

        if (!method_exists($license, 'is_trial') || !$license->is_trial()) {
            return;
        }

        $days_remaining = method_exists($license, 'trial_days_remaining')
            ? (int) $license->trial_days_remaining()
            : 0;

        if ($days_remaining <= 0) {
            return;
        }

        $dismiss_key = 'seoforge_trial_banner_dismissed';
        if (get_user_meta(get_current_user_id(), $dismiss_key, true)) {
            return;
        }

        $upgrade_url = $license->upgrade_url();
        ?>
        <div class="sf-admin">
            <div class="sf-upgrade-trial-banner" id="sf-trial-banner">
                <span class="sf-upgrade-trial-banner-text">
                    <?php
                    printf(
                        /* translators: %1$d: number of days remaining, %2$s: opening anchor tag, %3$s: closing anchor tag */
                        esc_html__('Your SEOForge Pro trial ends in %1$d days. %2$sUpgrade now%3$s to keep all features.', 'seoforge'),
                        (int) $days_remaining,
                        '<a href="' . esc_url($upgrade_url) . '" style="color:#c2410c;font-weight:700;">',
                        '</a>'
                    );
                    ?>
                </span>
                <button type="button" class="sf-upgrade-trial-dismiss" id="sf-trial-dismiss" title="<?php esc_attr_e('Dismiss', 'seoforge'); ?>">&times;</button>
            </div>
        </div>
        <script>
        (function() {
            var btn = document.getElementById('sf-trial-dismiss');
            if (btn) {
                btn.addEventListener('click', function() {
                    document.getElementById('sf-trial-banner').style.display = 'none';
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', '<?php echo esc_url(admin_url('admin-ajax.php')); ?>');
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.send('action=seoforge_dismiss_trial_banner&nonce=<?php echo esc_js( wp_create_nonce('seoforge_dismiss_trial') ); ?>');
                });
            }
        })();
        </script>
        <?php
    }
}
