<?php
/**
 * Tam Rank Freemium Manager
 *
 * Manages feature access for free and pro tiers
 *
 * @package TamRank
 * @since 6.4.0
 */

namespace TamRank;

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

/**
 * Feature registry and tier metadata for the free/PRO split.
 *
 * WordPress.org compliance note: the 'pro'-tier entries in this map are
 * display/upsell METADATA only (labels, descriptions, categories) that tell the
 * user which capabilities the separate TamRank PRO add-on provides. No PRO
 * feature code ships in this free plugin. can_use_feature() only hides UI for
 * capabilities whose implementation is absent from the free build (guarded
 * elsewhere by class_exists() / TAMRANK_PRO_VERSION) or that require an external
 * service; it never withholds functionality that runs locally. Every free-tier
 * feature is always fully functional.
 */
class FreemiumManager
{

    /**
     * Singleton instance
     *
     * @var FreemiumManager|null
     */
    private static $instance = null;

    /**
     * Feature definitions with tier assignments
     *
     * @var array
     */
    private $features = [];

    /**
     * Upgrade URL
     *
     * @var string
     */
    private $upgrade_url = 'https://tamrank.com/pro/';

    /**
     * Get singleton instance
     *
     * @return FreemiumManager
     */
    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct()
    {
        $this->define_features();
    }

    /**
     * Define all features and their tier assignments
     *
     * Free features: Basic SEO tools accessible without license
     * Pro features: Advanced AI and automation features requiring license
     */
    private function define_features()
    {
        $this->features = [
            // ========================================
            // FREE FEATURES
            // ========================================

            // SEO Basis
            'seo_score' => [
                'tier' => 'free',
                'name' => tamrank__('feature_seo_score_name', 'SEO Score'),
                'description' => tamrank__('feature_seo_score_desc', 'View the SEO score of your pages'),
                'category' => 'seo_basis',
            ],
            'meta_analysis' => [
                'tier' => 'free',
                'name' => tamrank__('feature_meta_analysis_name', 'Meta Analysis'),
                'description' => tamrank__('feature_meta_analysis_desc', 'Analysis of meta title and description'),
                'category' => 'seo_basis',
            ],
            'content_analysis' => [
                'tier' => 'free',
                'name' => tamrank__('feature_content_analysis_name', 'Content Analysis'),
                'description' => tamrank__('feature_content_analysis_desc', 'Analysis of your content for SEO'),
                'category' => 'seo_basis',
            ],
            'focus_keyword' => [
                'tier' => 'free',
                'name' => tamrank__('feature_focus_keyword_name', 'Focus Keyword'),
                'description' => tamrank__('feature_focus_keyword_desc', 'Set a focus keyword per page'),
                'category' => 'seo_basis',
            ],
            'secondary_keywords' => [
                'tier' => 'free',
                'name' => tamrank__('feature_secondary_keywords_name', 'Secondary Keywords'),
                'description' => tamrank__('feature_secondary_keywords_desc', 'Up to 4 secondary keywords per page'),
                'category' => 'seo_basis',
            ],
            'meta_title' => [
                'tier' => 'free',
                'name' => tamrank__('feature_meta_title_name', 'Meta Title'),
                'description' => tamrank__('feature_meta_title_desc', 'Customize the meta title'),
                'category' => 'seo_basis',
            ],
            'meta_description' => [
                'tier' => 'free',
                'name' => tamrank__('feature_meta_description_name', 'Meta Description'),
                'description' => tamrank__('feature_meta_description_desc', 'Customize the meta description'),
                'category' => 'seo_basis',
            ],
            'heading_structure' => [
                'tier' => 'free',
                'name' => tamrank__('feature_heading_structure_name', 'Heading Structure'),
                'description' => tamrank__('feature_heading_structure_desc', 'Analyze the H1-H6 structure'),
                'category' => 'seo_basis',
            ],
            'robots_meta' => [
                'tier' => 'free',
                'name' => tamrank__('feature_robots_meta_name', 'Robots Meta'),
                'description' => tamrank__('feature_robots_meta_desc', 'Noindex/nofollow settings per page'),
                'category' => 'seo_basis',
            ],
            'robots_directives' => [
                'tier' => 'free',
                'name' => tamrank__('feature_robots_directives_name', 'Robots Directives'),
                'description' => tamrank__('feature_robots_directives_desc', 'Noarchive, nosnippet, noimageindex, notranslate and preview limits per page'),
                'category' => 'seo_basis',
            ],
            // Two FREE features that shipped without a registry entry (REG-02,
            // 1.3.8). Both run unconditionally in the free plugin: the social
            // tags on wp_head (tam-rank.php:1332-1344) and the term fields on
            // every public taxonomy (admin/class-tamrank-taxonomy-meta.php:26).
            'social_meta' => [
                'tier' => 'free',
                'name' => tamrank__('feature_social_meta_name', 'Open Graph and Twitter Cards'),
                'description' => tamrank__('feature_social_meta_desc', 'Social title, description and image per page and per taxonomy term, sent out as Open Graph and Twitter Card tags with the featured image as fallback'),
                'category' => 'seo_basis',
            ],
            'taxonomy_seo_meta' => [
                'tier' => 'free',
                'name' => tamrank__('feature_taxonomy_seo_meta_name', 'Taxonomy SEO Fields'),
                'description' => tamrank__('feature_taxonomy_seo_meta_desc', 'The same SEO and social fields on categories, tags and custom taxonomy terms as on a post, including the search preview'),
                'category' => 'seo_basis',
            ],
            'archive_noindex' => [
                'tier' => 'free',
                'name' => tamrank__('feature_archive_noindex_name', 'Archive Indexing'),
                'description' => tamrank__('feature_archive_noindex_desc', 'Set date, author and search result archives to noindex from one place, so listing pages do not compete with the posts they repeat'),
                'category' => 'seo_basis',
            ],

            // Technisch
            'robots_txt' => [
                'tier' => 'free',
                'name' => tamrank__('feature_robots_txt_name', 'Robots.txt Editor'),
                'description' => tamrank__('feature_robots_txt_desc', 'Customize your robots.txt'),
                'category' => 'technisch',
            ],
            'xml_sitemap' => [
                'tier' => 'free',
                'name' => tamrank__('feature_xml_sitemap_name', 'XML Sitemap'),
                'description' => tamrank__('feature_xml_sitemap_desc', 'Automatic XML sitemap generation'),
                'category' => 'technisch',
            ],
            'redirect_checker' => [
                'tier' => 'free',
                'name' => tamrank__('feature_redirect_checker_name', 'Redirect Checker'),
                'description' => tamrank__('feature_redirect_checker_desc', 'Basic redirect management'),
                'category' => 'technisch',
            ],
            'redirect_suggestions_basic' => [
                'tier' => 'free',
                'name' => tamrank__('feature_redirect_suggestions_basic_name', 'Auto Redirect Suggestions (Basic)'),
                'description' => tamrank__('feature_redirect_suggestions_basic_desc', 'Basic automatic redirect suggestions'),
                'category' => 'technisch',
            ],
            'auto_redirect_on_delete' => [
                'tier' => 'free',
                'name' => tamrank__('feature_auto_redirect_on_delete_name', 'Auto-redirect on delete'),
                'description' => tamrank__('feature_auto_redirect_on_delete_desc', 'Prompt to create a 301 redirect when deleting a post or page'),
                'category' => 'technisch',
            ],
            '404_monitor' => [
                'tier' => 'free',
                'name' => tamrank__('feature_404_monitor_name', '404 Monitor'),
                'description' => tamrank__('feature_404_monitor_desc', 'Monitor 404 errors'),
                'category' => 'technisch',
            ],
            'canonical_url' => [
                'tier' => 'free',
                'name' => tamrank__('feature_canonical_url_name', 'Canonical URL'),
                'description' => tamrank__('feature_canonical_url_desc', 'Set canonical URLs'),
                'category' => 'technisch',
            ],
            'rss_optimization' => [
                'tier' => 'free',
                'name' => tamrank__('feature_rss_optimization_name', 'RSS Feed Optimisation'),
                'description' => tamrank__('feature_rss_optimization_desc', 'Text before and after every feed item, with a link back to the original'),
                'category' => 'technisch',
            ],
            'html_sitemap' => [
                'tier' => 'free',
                'name' => tamrank__('feature_html_sitemap_name', 'HTML Sitemap'),
                'description' => tamrank__('feature_html_sitemap_desc', 'A readable sitemap page via the [tamrank_sitemap] shortcode, with exactly the same links as the XML sitemap'),
                'category' => 'technisch',
            ],
            'breadcrumbs' => [
                'tier' => 'free',
                'name' => tamrank__('feature_breadcrumbs_name', 'Breadcrumbs'),
                'description' => tamrank__('feature_breadcrumbs_desc', 'Visible breadcrumb trail via the [tamrank_breadcrumb] shortcode, built from the same trail as the BreadcrumbList schema'),
                'category' => 'technisch',
            ],
            'htaccess_editor' => [
                'tier' => 'free',
                'name' => tamrank__('feature_htaccess_editor_name', '.htaccess Editor'),
                'description' => tamrank__('feature_htaccess_editor_desc', 'Edit the server rules in .htaccess from the admin, with rolling backups and an automatic restore when the site stops answering'),
                'category' => 'technisch',
            ],
            'migration_wizard' => [
                'tier' => 'free',
                'name' => tamrank__('feature_migration_wizard_name', 'Migration Wizard'),
                'description' => tamrank__('feature_migration_wizard_desc', 'Import meta data and redirects from Yoast or Rank Math during onboarding, with a rollback'),
                'category' => 'technisch',
            ],

            // Images
            'auto_alt_templates' => [
                'tier' => 'free',
                'name' => tamrank__('feature_auto_alt_templates_name', 'Automatic Alt Text'),
                'description' => tamrank__('feature_auto_alt_templates_desc', 'Fill alt text and media title of new uploads from a pattern, without ever overwriting'),
                'category' => 'images',
            ],
            'bulk_alt_existing_media' => [
                'tier' => 'free',
                'name' => tamrank__('feature_bulk_alt_existing_media_name', 'Bulk Alt Text for Existing Media'),
                'description' => tamrank__('feature_bulk_alt_existing_media_desc', 'Fill alt text across media already in the library in batches, behind its own switch, with a preview and an undo'),
                'category' => 'images',
            ],
            'webp_conversion' => [
                'tier' => 'free',
                'name' => tamrank__('feature_webp_conversion_name', 'WebP Conversion'),
                'description' => tamrank__('feature_webp_conversion_desc', 'Automatic WebP conversion with picture-tag output'),
                'category' => 'images',
            ],

            // Indexering (FREE)
            'auto_indexing' => [
                'tier' => 'free',
                'name' => tamrank__('feature_auto_indexing_name', 'Auto-Indexing on Publish'),
                'description' => tamrank__('feature_auto_indexing_desc', 'Indexing request to Google (Search Console) on publish and updates'),
                'category' => 'indexering',
            ],
            'manual_index_request' => [
                'tier' => 'free',
                'name' => tamrank__('feature_manual_index_request_name', 'Manual Request Indexing'),
                'description' => tamrank__('feature_manual_index_request_desc', 'Request indexing per page (24h cooldown)'),
                'category' => 'indexering',
            ],
            'indexnow' => [
                'tier' => 'free',
                'name' => tamrank__('feature_indexnow_name', 'IndexNow'),
                'description' => tamrank__('feature_indexnow_desc', 'Instant URL notification to the IndexNow engines (Bing, Yandex and others) on publish and updates'),
                'category' => 'indexering',
            ],

            // Analyse (FREE)
            'internal_link_graph' => [
                'tier' => 'free',
                'name' => tamrank__('feature_internal_link_graph_name', 'Internal Link Graph'),
                'description' => tamrank__('feature_internal_link_graph_desc', 'Site-wide scan of inbound internal links that flags orphan and weakly linked pages'),
                'category' => 'analyse',
            ],
            // Third REG-02 entry. The scanner and detector are unconditional
            // FREE code (includes/class-tamrank-outdated-scanner.php:44) and the
            // result is its own task group on the dashboard (dashboard.php:1019).
            'outdated_content' => [
                'tier' => 'free',
                'name' => tamrank__('feature_outdated_content_name', 'Outdated Content Detection'),
                'description' => tamrank__('feature_outdated_content_desc', 'Scans meta title, meta description, slug and headings for years that have passed, and groups the pages that need a refresh on the dashboard'),
                'category' => 'analyse',
            ],

            // Google Search Console (FREE tier)
            'gsc_connect' => [
                'tier' => 'free',
                'name' => tamrank__('feature_gsc_connect_name', 'Search Console Connect'),
                'description' => tamrank__('feature_gsc_connect_desc', 'Connect your Google Search Console property'),
                'category' => 'analyse',
            ],
            'gsc_dashboard_basic' => [
                'tier' => 'free',
                'name' => tamrank__('feature_gsc_dashboard_basic_name', 'Search Console Dashboard (7d/28d)'),
                'description' => tamrank__('feature_gsc_dashboard_basic_desc', 'Clicks, impressions and position for the last 7 and 28 days'),
                'category' => 'analyse',
            ],

            // ========================================
            // PRO FEATURES
            // ========================================

            // AI Features
            'ai_meta_generator' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_ai_meta_generator_name', 'AI Meta Generator'),
                'description' => tamrank__('feature_ai_meta_generator_desc', 'Generate meta titles and descriptions with AI'),
                'category' => 'ai',
            ],
            'ai_schema_suggestor' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_ai_schema_suggestor_name', 'AI Schema Suggestor'),
                'description' => tamrank__('feature_ai_schema_suggestor_desc', 'Automatic schema markup suggestions'),
                'category' => 'ai',
            ],
            'ai_internal_links' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_ai_internal_links_name', 'AI Internal Links'),
                'description' => tamrank__('feature_ai_internal_links_desc', 'AI-generated internal link suggestions aligned with Topical Authority'),
                'category' => 'ai',
            ],
            'vision_alt_text' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_vision_alt_text_name', 'Vision AI Alt Text'),
                'description' => tamrank__('feature_vision_alt_text_desc', 'Generate descriptive image alt text with Vision AI'),
                'category' => 'ai',
            ],
            'ai_brand_profile' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_ai_brand_profile_name', 'AI Brand Profile & Tone'),
                'description' => tamrank__('feature_ai_brand_profile_desc', 'Brand voice profile that steers all AI outputs'),
                'category' => 'ai',
            ],

            // Geavanceerde Redirects
            'smart_matching_v2' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_smart_matching_v2_name', 'Smart Matching v2'),
                'description' => tamrank__('feature_smart_matching_v2_desc', 'Advanced redirect suggestions with AI'),
                'category' => 'redirects',
            ],
            'redirect_learning_engine' => [
                'tier' => 'free',
                'name' => tamrank__('feature_redirect_learning_engine_name', 'Redirect Learning Engine'),
                'description' => tamrank__('feature_redirect_learning_engine_desc', 'Learn from manual redirects for better suggestions'),
                'category' => 'redirects',
            ],
            'regex_redirects' => [
                'tier' => 'free',
                'name' => tamrank__('feature_regex_redirects_name', 'Regex Redirects'),
                'description' => tamrank__('feature_regex_redirects_desc', 'Advanced regex-based redirects'),
                'category' => 'redirects',
            ],
            'redirect_chain_detector' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_redirect_chain_detector_name', 'Redirect Chain Detector & Auto-fix'),
                'description' => tamrank__('feature_redirect_chain_detector_desc', 'Detect redirect chains and automatically flatten them'),
                'category' => 'redirects',
            ],

            // Search Console — split in gsc_connect / gsc_dashboard_basic (FREE) and gsc_dashboard_extended / gsc_page_insights (PRO)
            'gsc_dashboard_extended' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_gsc_dashboard_extended_name', 'Search Console Extended Periods'),
                'description' => tamrank__('feature_gsc_dashboard_extended_desc', 'Trend analysis for 3, 6, 12 and 16 months'),
                'category' => 'analyse',
            ],
            'gsc_page_insights' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_gsc_page_insights_name', 'Page Insights'),
                'description' => tamrank__('feature_gsc_page_insights_desc', 'Keywords per page, CTR, Position Stability and Keyword Potential'),
                'category' => 'analyse',
            ],

            // Analyse
            'pagespeed_analysis' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_pagespeed_analysis_name', 'PageSpeed Analysis'),
                'description' => tamrank__('feature_pagespeed_analysis_desc', 'Comprehensive PageSpeed analysis and monitoring'),
                'category' => 'analyse',
            ],
            'seo_audit' => [
                'tier' => 'free',
                'name' => tamrank__('feature_seo_audit_name', 'SEO Audit'),
                'description' => tamrank__('feature_seo_audit_desc', 'Full site SEO audit'),
                'category' => 'analyse',
            ],
            'competitor_analysis' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_competitor_analysis_name', 'Competitor Analysis'),
                'description' => tamrank__('feature_competitor_analysis_desc', 'Compare your site with competitors'),
                'category' => 'analyse',
            ],
            'priority_actions' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_priority_actions_name', 'Priority Actions Dashboard'),
                'description' => tamrank__('feature_priority_actions_desc', 'Impact-ranked SEO tasks driven by GSC data'),
                'category' => 'analyse',
            ],
            'change_tracker' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_change_tracker_name', 'SEO Change Tracker'),
                'description' => tamrank__('feature_change_tracker_desc', 'Log on-page SEO changes and measure their GSC effect'),
                'category' => 'analyse',
            ],
            'position_stability' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_position_stability_name', 'Position Stability'),
                'description' => tamrank__('feature_position_stability_desc', 'Classify keyword ranking stability (stable/moderate/volatile)'),
                'category' => 'analyse',
            ],
            'keyword_potential' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_keyword_potential_name', 'Keyword Potential'),
                'description' => tamrank__('feature_keyword_potential_desc', 'Uplift potential per keyword based on CTR curve and impressions'),
                'category' => 'analyse',
            ],
            'crux_data' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_crux_data_name', 'CrUX Real User Data'),
                'description' => tamrank__('feature_crux_data_desc', 'Real-user Core Web Vitals from Chrome UX Report'),
                'category' => 'analyse',
            ],

            // Indexering (PRO)
            'index_status_column' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_index_status_column_name', 'Index Status Column'),
                'description' => tamrank__('feature_index_status_column_desc', 'Shows Google index state per post in the posts list'),
                'category' => 'indexering',
            ],
            'auto_index_bulk_scan' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_auto_index_bulk_scan_name', 'Auto Index Status Bulk Scan'),
                'description' => tamrank__('feature_auto_index_bulk_scan_desc', 'Daily automated bulk scan of index status via GSC + URL Inspection'),
                'category' => 'indexering',
            ],

            // REST API (PRO)
            'rest_api_unlimited_writes' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_rest_api_unlimited_writes_name', 'REST API Write Access'),
                'description' => tamrank__('feature_rest_api_unlimited_writes_desc', 'Update SEO fields programmatically via REST API'),
                'category' => 'api',
            ],
            'rest_api_batch' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_rest_api_batch_name', 'REST API Batch Writes'),
                'description' => tamrank__('feature_rest_api_batch_desc', 'Batch update up to 50 items per request'),
                'category' => 'api',
            ],

            // Topical Authority
            'topical_authority_map' => [
                'tier' => 'pro',
                'name' => tamrank__('feature_topical_authority_map_name', 'Topical Authority Map'),
                'description' => tamrank__('feature_topical_authority_map_desc', 'Visualize your content structure and discover gaps'),
                'category' => 'topical_authority',
            ],

            // Schema
            'schema_builder' => [
                'tier' => 'free',
                'name' => tamrank__('feature_schema_builder_name', 'Schema Builder'),
                'description' => tamrank__('feature_schema_builder_desc', 'Combine multiple schemas'),
                'category' => 'schema',
            ],
            'schema_templates' => [
                'tier' => 'free',
                'name' => tamrank__('feature_schema_templates_name', 'Schema Templates'),
                'description' => tamrank__('feature_schema_templates_desc', 'Reusable schema templates'),
                'category' => 'schema',
            ],
            'auto_schema_detection' => [
                'tier' => 'free',
                'name' => tamrank__('feature_auto_schema_detection_name', 'Auto Schema Detection'),
                'description' => tamrank__('feature_auto_schema_detection_desc', 'Automatic schema type detection'),
                'category' => 'schema',
            ],
            'merchant_schema' => [
                'tier' => 'free',
                'name' => tamrank__('feature_merchant_schema_name', 'Webshop listing'),
                'description' => tamrank__('feature_merchant_schema_desc', 'Shipping costs, return policy and product condition in the product markup, read from your WooCommerce shipping zones'),
                'category' => 'schema',
            ],
            'social_fallback_image' => [
                'tier' => 'free',
                'name' => tamrank__('feature_social_fallback_image_name', 'Fallback share image'),
                'description' => tamrank__('feature_social_fallback_image_desc', 'One site-wide image that Facebook, X and LinkedIn show for pages without an image of their own'),
                'category' => 'schema',
            ],

        ];
    }

    /**
     * Check if user can access a feature
     *
     * @param string $feature_id Feature identifier
     * @return bool True if feature is accessible
     */
    public function can_use_feature($feature_id)
    {
        // Feature doesn't exist - deny access
        if (!isset($this->features[$feature_id])) {
            return false;
        }

        $feature = $this->features[$feature_id];

        // Free features are always accessible
        if ($feature['tier'] === 'free') {
            return true;
        }

        // Pro features require active license
        return $this->is_pro_active();
    }

    /**
     * Check if Pro is active (license is valid)
     *
     * SINGLE SOURCE OF TRUTH for "is PRO active?". All other readers
     * (LicenseManager::is_license_active, tam_rank_license_active, tamrank_is_pro)
     * delegate here so the presence-guard below cannot be bypassed.
     *
     * Requires BOTH the persisted premium_active flag AND the PRO add-on to be
     * present: TAMRANK_PRO_VERSION is defined at file-scope in tam-rank-pro.php,
     * so a missing add-on means the constant is undefined. This guard means a
     * stale premium_active option on a FREE-only install (e.g. an ex-PRO
     * downgrade where the add-on was removed) can never re-enable PRO gates.
     * premium_active is PRO-owned; the constant is the FREE-side contract that
     * the owner exists. No fallbacks or API calls.
     *
     * @return bool
     */
    public function is_pro_active()
    {
        return (bool) tam_rank_cached_option('tam_rank_premium_active', false)
            && defined('TAMRANK_PRO_VERSION');
    }

    /**
     * Get feature info
     *
     * @param string $feature_id Feature identifier
     * @return array|null Feature info or null if not found
     */
    public function get_feature($feature_id)
    {
        return $this->features[$feature_id] ?? null;
    }

    /**
     * Get all features
     *
     * @return array
     */
    public function get_all_features()
    {
        return $this->features;
    }

    /**
     * Get features by tier
     *
     * @param string $tier 'free' or 'pro'
     * @return array
     */
    public function get_features_by_tier($tier)
    {
        return array_filter($this->features, function ($feature) use ($tier) {
            return $feature['tier'] === $tier;
        });
    }

    /**
     * Get features by category
     *
     * @param string $category Category name
     * @return array
     */
    public function get_features_by_category($category)
    {
        return array_filter($this->features, function ($feature) use ($category) {
            return $feature['category'] === $category;
        });
    }

    /**
     * Get upgrade URL
     *
     * @param string $utm_source Optional UTM source
     * @param string $utm_campaign Optional UTM campaign
     * @return string
     */
    public function get_upgrade_url($utm_source = '', $utm_campaign = '')
    {
        $url = $this->upgrade_url;

        $params = [];
        if ($utm_source) {
            $params['utm_source'] = $utm_source;
        }
        if ($utm_campaign) {
            $params['utm_campaign'] = $utm_campaign;
        }

        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }

        return $url;
    }

    /**
     * Render Pro badge
     *
     * @param bool $small Use small badge variant
     * @return string HTML for Pro badge
     */
    public function render_pro_badge($small = false)
    {
        $size_class = $small ? 'tamrank-pro-badge--sm' : '';

        return sprintf(
            '<span class="tamrank-pro-badge %s">PRO</span>',
            esc_attr($size_class)
        );
    }

    /**
     * Render upgrade button
     *
     * @param string $feature_id Optional feature ID for context
     * @param string $button_text Optional custom button text
     * @param string $utm_source Optional UTM source
     * @return string HTML for upgrade button
     */
    public function render_upgrade_button($feature_id = '', $button_text = '', $utm_source = 'plugin')
    {
        if (empty($button_text)) {
            $button_text = tamrank__('view_pro', 'View PRO');
        }

        $url = $this->get_upgrade_url($utm_source, $feature_id);

        return sprintf(
            '<a href="%s" class="tr-btn tr-btn--secondary tr-btn--sm" target="_blank" rel="noopener">%s &rarr;</a>',
            esc_url($url),
            esc_html($button_text)
        );
    }

    /**
     * Render locked feature overlay
     *
     * @param string $feature_id Feature identifier
     * @return string HTML for locked overlay
     */
    public function render_locked_overlay($feature_id)
    {
        $feature = $this->get_feature($feature_id);

        if (!$feature) {
            return '';
        }

        $license_url = admin_url('admin.php?page=tam-rank-settings#license');
        $upgrade_url = $this->get_upgrade_url('locked_overlay', $feature_id);

        return sprintf(
            '<div class="tamrank-locked-overlay">
                <div class="tamrank-locked-content">
                    <div class="tamrank-locked-icon">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
                        </svg>
                    </div>
                    <h4>%s %s</h4>
                    <p>%s</p>
                    <div class="tamrank-locked-actions">
                        <a href="%s" class="tr-btn tr-btn--secondary" target="_blank" rel="noopener">%s &rarr;</a>
                        <a href="%s" class="tamrank-license-link">%s</a>
                    </div>
                </div>
            </div>',
            esc_html($feature['name']),
            $this->render_pro_badge(),
            esc_html($feature['description']),
            esc_url($upgrade_url),
            esc_html(tamrank__('view_pro', 'View PRO')),
            esc_url($license_url),
            esc_html(tamrank__('have_license_already', 'I already have a license'))
        );
    }

    /**
     * Render feature card (for locked features in UI)
     *
     * @param string $feature_id Feature identifier
     * @param bool $show_full Show full card with description
     * @return string HTML for feature card
     */
    public function render_feature_card($feature_id, $show_full = true)
    {
        $feature = $this->get_feature($feature_id);

        if (!$feature) {
            return '';
        }

        $is_accessible = $this->can_use_feature($feature_id);
        $locked_class = !$is_accessible ? 'tamrank-feature-locked' : '';

        ob_start();
        ?>
        <div class="tamrank-feature-card <?php echo esc_attr($locked_class); ?>">
            <div class="tamrank-feature-header">
                <span class="tamrank-feature-name"><?php echo esc_html($feature['name']); ?></span>
                <?php if ($feature['tier'] === 'pro'): ?>
                    <?php echo wp_kses_post($this->render_pro_badge(true)); ?>
                <?php endif; ?>
            </div>
            <?php if ($show_full): ?>
                <p class="tamrank-feature-description"><?php echo esc_html($feature['description']); ?></p>
            <?php endif; ?>
            <?php if (!$is_accessible): ?>
                <div class="tamrank-feature-upgrade">
                    <?php echo wp_kses_post($this->render_upgrade_button($feature_id)); ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Render inline Pro lock message (for use in forms/fields)
     *
     * @param string $feature_id Feature identifier
     * @return string HTML
     */
    public function render_inline_lock($feature_id)
    {
        $feature = $this->get_feature($feature_id);
        $feature_name = $feature ? $feature['name'] : tamrank__('this_feature', 'This feature');

        return sprintf(
            '<div class="tamrank-inline-pro-lock">
                <span>%s ' . esc_html(tamrank__('available_with_pro', 'is available with TamRank PRO.')) . '</span>
                <a href="%s" target="_blank">%s &rarr;</a>
            </div>',
            esc_html($feature_name),
            esc_url($this->get_upgrade_url('inline_lock', $feature_id)),
            esc_html(tamrank__('discover_pro', 'Discover PRO'))
        );
    }
}

/**
 * Global function to get FreemiumManager instance
 *
 * @return FreemiumManager
 */
function tamrank_freemium()
{
    return FreemiumManager::get_instance();
}

/**
 * Helper function to check feature access
 *
 * @param string $feature_id Feature identifier
 * @return bool
 */
function tamrank_can_use($feature_id)
{
    return FreemiumManager::get_instance()->can_use_feature($feature_id);
}

/**
 * Helper function to check if Pro is active
 *
 * @return bool
 */
function tamrank_is_pro()
{
    return FreemiumManager::get_instance()->is_pro_active();
}
