<?php
/**
 * Tam Rank License & Feature Helper Functions (SaaS Edition)
 *
 * Read-only helper functions voor feature gating (UI only).
 * GEEN enforcement - backend beslist altijd.
 *
 * @package TamRank
 * @since 8.0.0 (SaaS refactor)
 */

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

/**
 * Global-scope aliases for the namespaced helpers in \TamRank\ (src/FreemiumManager.php).
 * Several legacy callers (redirect-manager.php, class-tamrank-index-checker.php, etc.)
 * invoke `tamrank_can_use()` / `tamrank_is_pro()` from global scope, which would
 * otherwise fatal since PHP does not fall back across namespaces for unqualified
 * function calls outside a namespace.
 */
if (!function_exists('tamrank_can_use')) {
    function tamrank_can_use($feature_id)
    {
        if (function_exists('\\TamRank\\tamrank_can_use')) {
            return \TamRank\tamrank_can_use($feature_id);
        }
        if (class_exists('\\TamRank\\FreemiumManager')) {
            return \TamRank\FreemiumManager::get_instance()->can_use_feature($feature_id);
        }
        return false;
    }
}

if (!function_exists('tamrank_is_pro')) {
    function tamrank_is_pro()
    {
        if (function_exists('\\TamRank\\tamrank_is_pro')) {
            return \TamRank\tamrank_is_pro();
        }
        // Guarded fallback: requires the PRO add-on present (TAMRANK_PRO_VERSION)
        // so a stale premium_active option alone cannot re-enable PRO.
        return (bool) tam_rank_cached_option('tam_rank_premium_active', false)
            && defined('TAMRANK_PRO_VERSION');
    }
}

if (!function_exists('tamrank_pro_addon_installed')) {
    /**
     * Whether the PRO add-on plugin is installed and loaded (regardless of
     * licence state). The add-on carries the licence activation form, so an
     * "Activate here" call-to-action only makes sense when this is true. On a
     * FREE-only install there is nothing to activate yet — the user must first
     * install the PRO add-on — so activate links should be hidden in favour of
     * the upgrade / install guidance.
     *
     * @return bool
     */
    function tamrank_pro_addon_installed()
    {
        return defined('TAMRANK_PRO_VERSION');
    }
}

/**
 * Check if site is active (voor UI GATING only, niet enforcement)
 *
 * BELANGRIJK:
 * - Gebruik ALLEEN voor UI gating (tonen/verbergen)
 * - NOOIT gebruiken om requests te blokkeren
 * - Backend doet altijd finale enforcement
 *
 * @return bool True if site is active (voor UI display)
 */
function tam_rank_license_active()
{
    // Delegates to the canonical reader (FreemiumManager::is_pro_active) so the
    // PRO presence-guard is enforced for every legacy global-scope caller.
    if (class_exists('\\TamRank\\FreemiumManager')) {
        return \TamRank\FreemiumManager::get_instance()->is_pro_active();
    }
    // Guarded fallback if the manager is somehow unavailable (load order).
    return (bool) tam_rank_cached_option('tam_rank_premium_active', false)
        && defined('TAMRANK_PRO_VERSION');
}


/**
 * Get license status (read-only, van backend)
 *
 * @return string License status (active, inactive, suspended)
 */
// tam_rank_get_license_status removed to enforce single source of truth



/**
 * Check if user can use a specific feature (voor UI GATING only)
 *
 * BELANGRIJK:
 * - Gebruik ALLEEN voor UI gating (buttons/secties tonen/verbergen)
 * - NOOIT gebruiken om requests te blokkeren
 * - Backend doet altijd finale enforcement
 *
 * @param string $feature_id Feature identifier (e.g., 'ai_meta', 'ai_images')
 * @return bool True if feature is accessible (voor UI display)
 */
function tam_rank_can_use_feature($feature_id)
{
    if (!class_exists('\\TamRank\\FreemiumManager')) {
        return false;
    }
    return \TamRank\FreemiumManager::get_instance()->can_use_feature($feature_id);
}




/**
 * Get upgrade URL
 *
 * Routes to a feature-specific showcase page on tamrank.com when the
 * source:campaign pair matches a known theme feature slug; falls back
 * to /pricing/ otherwise. UTM parameters are always appended for
 * analytics.
 *
 * @param string $utm_source Optional UTM source
 * @param string $utm_campaign Optional UTM campaign
 * @return string URL to upgrade
 */
function tam_rank_get_upgrade_url($utm_source = '', $utm_campaign = '')
{
    // Map source:campaign → theme feature slug (tamrank.com/features/{slug}/)
    $feature_map = array(
        'meta_ui:ai_meta'              => 'ai-seo-tools',
        'media_library:ai_alt_text'    => 'ai-seo-tools',
        'meta_box:ai_meta_generator'   => 'ai-seo-tools',
        'settings:gsc_integration'     => 'search-console',
        'dashboard:gsc_widget'         => 'search-console',
        'dashboard:page_insights'      => 'search-console',
        'dashboard:gsc_history'        => 'search-console',
        'plugin:index_status_column'   => 'search-console',
        'plugin:auto_index_bulk_scan'  => 'search-console',
        'settings:pagespeed'           => 'pagespeed',
        'redirects:suggestions'        => '404-redirects',
        'auto_redirect:post_deleted'   => '404-redirects',
    );

    $key  = $utm_source . ':' . $utm_campaign;
    $slug = isset($feature_map[$key]) ? $feature_map[$key] : null;

    $url = $slug
        ? 'https://tamrank.com/features/' . $slug . '/'
        : 'https://tamrank.com/pricing/';

    $params = array();
    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 HTML
 *
 * @param bool $small Use small variant
 * @return string HTML for PRO badge
 */
function tam_rank_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));
}


/**
 * Display upgrade message (voor admin pages)
 *
 * @param string $feature_name Optional feature name
 * @param string $feature_id Optional feature ID for tracking
 */
function tam_rank_show_upgrade_message($feature_name = '', $feature_id = '')
{
    $message = $feature_name
        ? $feature_name
        : __('PRO Feature', 'tam-rank');

    $description = $feature_name
        /* translators: %s: name of the PRO feature the user tried to access */
        ? sprintf(__('%s is available with TamRank PRO.', 'tam-rank'), $feature_name)
        : __('This feature is available with TamRank PRO.', 'tam-rank');

    ?>
    <div class="tamrank-upgrade-card">
        <div class="tamrank-upgrade-card__icon">
            <svg width="20" height="20" 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>
        <h3 class="tamrank-upgrade-card__title">
            <?php echo esc_html($message); ?>
            <?php echo wp_kses_post(tam_rank_pro_badge()); ?>
        </h3>
        <p class="tamrank-upgrade-card__desc">
            <?php echo esc_html($description); ?>
        </p>
        <div class="tamrank-upgrade-card__actions">
            <a href="<?php echo esc_url(tam_rank_get_upgrade_url('upgrade_message', $feature_id)); ?>"
                class="tr-btn tr-btn--secondary" target="_blank" rel="noopener">
                <?php esc_html_e('View PRO', 'tam-rank'); ?> &rarr;
            </a>
            <?php if (tamrank_pro_addon_installed()): ?>
                <span class="tamrank-license-link-wrap">
                    <?php esc_html_e('Already have a license?', 'tam-rank'); ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=tam-rank-settings#license')); ?>" class="tamrank-license-link">
                        <?php esc_html_e('Activate here', 'tam-rank'); ?>
                    </a>
                </span>
            <?php endif; ?>
        </div>
    </div>
    <?php
}



