<?php
/**
 * ExploreXR Premium Helper Functions
 * 
 * Global helper functions used by addons and core plugin
 * 
 * @package ExploreXR_Premium
 * @since 1.0.0
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Check if ExploreXR Premium plugin is active
 * This function is called by addons to verify premium is installed
 * 
 * @return boolean True if premium is active, false otherwise
 */
function explorexr_premium_is_active() {
    // Check if the license handler class exists
    return class_exists('ExploreXR_License_Handler');
}

/**
 * Check if a specific addon is licensed for the current installation
 * This is the main function that addons call to check their license status
 * 
 * @param string $addon_slug The addon slug (e.g., 'annotations', 'ar', 'camera')
 * @return boolean True if addon is licensed, false otherwise
 */
function explorexr_premium_is_addon_licensed($addon_slug) {
    // Get the license handler instance
    if (!class_exists('ExploreXR_License_Handler')) {
        // WordPress.org compliance: Use do_action for debugging instead of error_log
        do_action('explorexr_premium_debug', "License Check [{$addon_slug}]: License handler class not found");
        return false;
    }
    
    $license_handler = ExploreXR_License_Handler::instance();
    if (!$license_handler) {
        // WordPress.org compliance: Use do_action for debugging instead of error_log
        do_action('explorexr_premium_debug', "License Check [{$addon_slug}]: License handler instance not available");
        return false;
    }
    
    // Check if license is active
    $is_active = $license_handler->is_license_active();
    if (!$is_active) {
        // WordPress.org compliance: Use do_action for debugging instead of error_log
        do_action('explorexr_premium_debug', "License Check [{$addon_slug}]: License is NOT active");
        return false;
    }
    
    // Get license tier
    $tier = $license_handler->get_license_tier();
    // WordPress.org compliance: Use do_action for debugging instead of error_log
    do_action('explorexr_premium_debug', "License Check [{$addon_slug}]: License tier = {$tier}, License active = " . ($is_active ? 'YES' : 'NO'));
    
    // Ultra tier gets all addons automatically
    if ($tier === 'ultra') {
        do_action('explorexr_premium_debug', "License Check [{$addon_slug}]: LICENSED (Ultra tier - all addons included)");
        return true;
    }

    // Pro, Plus, and Trial tiers enforce an addon slot limit
    // Trial behaves identically to Plus (4 slots) but is time-limited
    if (in_array($tier, array('pro', 'plus', 'trial'), true)) {
        $max_addons = $license_handler->get_max_addons();
        $selected_addons = $license_handler->get_selected_addons();

        // If the addon is explicitly in the selected addons list, allow it
        if (in_array($addon_slug, $selected_addons, true)) {
            do_action('explorexr_premium_debug', "License Check [{$addon_slug}]: LICENSED ({$tier} tier - addon is in selected list)");
            return true;
        }

        // If the selected list hasn't reached the limit yet, allow (supports activation flow)
        if (count($selected_addons) < $max_addons) {
            do_action('explorexr_premium_debug', "License Check [{$addon_slug}]: LICENSED ({$tier} tier - addon slots available: " . count($selected_addons) . "/{$max_addons})");
            return true;
        }

        // Addon is not in selected list and limit is reached
        do_action('explorexr_premium_debug', "License Check [{$addon_slug}]: NOT LICENSED ({$tier} tier - addon limit reached: {$max_addons})");
        return false;
    }
    
    // Free tier or invalid tier - no addons allowed
    // WordPress.org compliance: Use do_action for debugging instead of error_log
    do_action('explorexr_premium_debug', "License Check [{$addon_slug}]: NOT LICENSED (tier: {$tier} does not support addons)");
    return false;
}

/**
 * Get current license tier
 * 
 * @return string License tier ('free', 'pro', 'plus', 'ultra')
 */
function explorexr_premium_get_license_tier() {
    if (!class_exists('ExploreXR_License_Handler')) {
        return 'free';
    }
    
    $license_handler = ExploreXR_License_Handler::instance();
    return $license_handler ? $license_handler->get_license_tier() : 'free';
}

/**
 * Check if license is active
 * 
 * @return boolean True if license is active
 */
function explorexr_premium_is_license_active() {
    if (!class_exists('ExploreXR_License_Handler')) {
        return false;
    }
    
    $license_handler = ExploreXR_License_Handler::instance();
    return $license_handler ? $license_handler->is_license_active() : false;
}

/**
 * Get maximum addons allowed by current license
 * 
 * @return int Maximum number of addons (-1 for unlimited)
 */
function explorexr_premium_get_max_addons() {
    if (!class_exists('ExploreXR_License_Handler')) {
        return 0;
    }
    
    $license_handler = ExploreXR_License_Handler::instance();
    return $license_handler ? $license_handler->get_max_addons() : 0;
}

/**
 * Check if an ExploreXR addon is installed, active, and (optionally) licensed.
 * Centralizes detection to keep templates and integrations in sync.
 *
 * @param string $addon_slug Addon slug (e.g., 'camera', 'annotations').
 * @param bool   $require_license Whether to require an active license.
 * @return bool True when installed + active (+ licensed when requested).
 */
function explorexr_premium_is_addon_active($addon_slug, $require_license = true) {
    static $status_cache = array();

    $addon_slug = strtolower(trim($addon_slug));

    // Return cached status when available
    $cache_key = $require_license ? 'licensed' : 'no_license';
    if (isset($status_cache[$addon_slug][$cache_key])) {
        return $status_cache[$addon_slug][$cache_key];
    }

    // Ensure is_plugin_active() exists
    if (!function_exists('is_plugin_active')) {
        include_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    // Map of known addon plugin files
    $known_addons = array(
        'camera'          => 'explorexr-camera-addon/explorexr-camera-addon.php',
        'annotations'     => 'explorexr-annotations-addon/explorexr-annotations-addon.php',
        'animation'       => 'explorexr-animation-addon/explorexr-animation-addon.php',
        'materials'       => 'explorexr-materials-addon/explorexr-materials-addon.php',
        'ar'              => 'explorexr-ar-addon/explorexr-ar-addon.php',
        'loading'         => 'explorexr-loading-addon/explorexr-loading-addon.php',
        'morphing'        => 'explorexr-morphing-addon/explorexr-morphing-addon.php',
        'mouse3d'         => 'explorexr-mouse3d-addon/explorexr-mouse3d-addon.php',
        'post-processing' => 'explorexr-post-processing-addon/explorexr-post-processing-addon.php',
        'environment'     => 'explorexr-environment-addon/explorexr-environment-addon.php',
        'woocommerce'     => 'explorexr-woocommerce-addon/explorexr-woocommerce-addon.php',
        'draggable'       => 'explorexr-draggable-addon/explorexr-draggable-addon.php',
    );

    /**
     * Allow external code to adjust addon plugin file mappings.
     *
     * @param array $known_addons Map of addon_slug => plugin file.
     */
    $known_addons = apply_filters('explorexr_premium_known_addons', $known_addons);

    if (!isset($known_addons[$addon_slug])) {
        $status_cache[$addon_slug][$cache_key] = false;
        return false;
    }

    $plugin_file = $known_addons[$addon_slug];
    $is_installed = file_exists(WP_PLUGIN_DIR . '/' . $plugin_file);
    $is_active = $is_installed && is_plugin_active($plugin_file);

    if (!$is_active) {
        $status_cache[$addon_slug][$cache_key] = false;
        return false;
    }

    // License check (optional)
    if ($require_license && function_exists('explorexr_premium_is_addon_licensed')) {
        $licensed = explorexr_premium_is_addon_licensed($addon_slug);
        $status_cache[$addon_slug]['licensed'] = $licensed;
        $status_cache[$addon_slug]['no_license'] = true; // Active even if license check fails
        return $licensed;
    }

    $status_cache[$addon_slug]['licensed'] = true;
    $status_cache[$addon_slug]['no_license'] = true;
    return true;
}

/**
 * Get selected/activated addons for current license
 * 
 * @return array Array of addon slugs
 */
function explorexr_premium_get_selected_addons() {
    if (!class_exists('ExploreXR_License_Handler')) {
        return array();
    }
    
    $license_handler = ExploreXR_License_Handler::instance();
    return $license_handler ? $license_handler->get_selected_addons() : array();
}

/**
 * Check if current license is Pro or higher (includes Trial).
 * Trial grants the same feature access as Plus for its 14-day duration.
 *
 * @return boolean True if Trial, Pro, Plus, or Ultra
 */
function explorexr_premium_is_pro_or_higher() {
    if (!explorexr_premium_is_license_active()) {
        return false;
    }

    $tier = explorexr_premium_get_license_tier();
    return in_array($tier, array('trial', 'pro', 'plus', 'ultra'), true);
}

/**
 * Check if the current request likely contains ExploreXR model viewers.
 *
 * Used by addons to decide whether to enqueue frontend assets on a page.
 *
 * @param WP_Post|null $post Optional post object to inspect.
 * @return bool True when model viewers are likely present.
 */
function explorexr_premium_has_model_viewers($post = null) {
    // Allow shortcodes or templates that render outside the main post loop.
    if (!$post) {
        $post = get_post();
    }

    if (!$post instanceof WP_Post) {
        // When no post context exists, enqueue to be safe (widgets/builders/templates).
        return true;
    }

    // Always load on ExploreXR model posts.
    if (in_array($post->post_type, array('explorexr_model', 'explorexr_premium_model'), true)) {
        return true;
    }

    $content = (string) $post->post_content;

    // Check for ExploreXR shortcodes (primary + aliases).
    $shortcodes = array('explorexr_model', 'explorexr-premium', 'explorexr_premium_model', 'EXPLOREXR_model');
    foreach ($shortcodes as $shortcode) {
        if (has_shortcode($content, $shortcode)) {
            return true;
        }
    }

    // Fallback: detect shortcodes inside block content or builders.
    if (strpos($content, 'explorexr_model') !== false || strpos($content, 'explorexr-premium') !== false) {
        return true;
    }

    // WooCommerce products linked to models.
    if (function_exists('is_product') && is_product()) {
        $product_id = get_the_ID();
        $model_id = get_post_meta($product_id, '_explorexr_premium_model_id', true);
        if ($model_id) {
            return true;
        }
    }

    return false;
}

/**
 * Display addon license notice when addon is not licensed
 * Used by addons to show consistent licensing messages
 * 
 * @param string $addon_name The display name of the addon
 * @param string $addon_slug The addon slug
 */
function explorexr_premium_addon_license_notice($addon_name, $addon_slug = '') {
    $tier = explorexr_premium_get_license_tier();
    $is_active = explorexr_premium_is_license_active();
    
    if (!$is_active) {
        // No license activated
        ?>
        <div class="notice notice-warning">
            <p>
                <strong><?php echo esc_html($addon_name); ?></strong> requires an active ExploreXR Premium license.
                <a href="<?php echo esc_url(admin_url('admin.php?page=explorexr-premium-license')); ?>" class="button button-primary">
                    Activate License
                </a>
            </p>
        </div>
        <?php
    } else {
        // License active but addon not selected
        $max_addons = explorexr_premium_get_max_addons();
        $selected_addons = explorexr_premium_get_selected_addons();
        $selected_count = count($selected_addons);
        
        if ($tier === 'ultra') {
            // This shouldn't happen for Ultra, but just in case
            ?>
            <div class="notice notice-info">
                <p>
                    <strong><?php echo esc_html($addon_name); ?></strong> is included with your Ultra license but not yet activated.
                    Please contact support if this persists.
                </p>
            </div>
            <?php
        } elseif ($selected_count >= $max_addons) {
            // All addon slots are used
            ?>
            <div class="notice notice-warning">
                <p>
                    <strong><?php echo esc_html($addon_name); ?></strong> is not included in your current addon selection.
                    Your <?php echo esc_html(ucfirst($tier)); ?> license allows <?php echo (int)$max_addons; ?> addon(s).
                    <a href="<?php echo esc_url(admin_url('admin.php?page=explorexr-premium-addons')); ?>" class="button button-secondary">
                        Manage Add-ons
                    </a>
                    or
                    <a href="<?php echo esc_url(admin_url('admin.php?page=explorexr-premium-license')); ?>" class="button button-primary">
                        Upgrade License
                    </a>
                </p>
            </div>
            <?php
        } else {
            // Has available addon slots
            ?>
            <div class="notice notice-info">
                <p>
                    <strong><?php echo esc_html($addon_name); ?></strong> is available with your <?php echo esc_html(ucfirst($tier)); ?> license.
                    <a href="<?php echo esc_url(admin_url('admin.php?page=explorexr-premium-addons')); ?>" class="button button-primary">
                        Select This Add-on
                    </a>
                </p>
            </div>
            <?php
        }
    }
}

/**
 * Sanitize hex color value
 * 
 * Ensures color values are valid hex colors with # prefix
 * Fallback to default if invalid
 * 
 * NOTE: PHP function names are case-insensitive, so we only need one version
 * This function can be called as explorexr_sanitize_hex_color() or ExploreXR_sanitize_hex_color()
 * 
 * @param string $color Color value to sanitize
 * @param string $default Default color if validation fails
 * @return string Sanitized hex color
 */
if (!function_exists('explorexr_sanitize_hex_color')) {
    function explorexr_sanitize_hex_color($color, $default = '#000000') {
        // Remove any whitespace
        $color = trim($color);
        
        // If empty, return default
        if (empty($color)) {
            return $default;
        }
        
        // Add # prefix if missing
        if (substr($color, 0, 1) !== '#') {
            $color = '#' . $color;
        }
        
        // Validate hex color format (3 or 6 digits)
        if (preg_match('/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/', $color)) {
            return $color;
        }
        
        // Invalid format, return default
        return $default;
    }
}
