<?php
/**
 * Helper functions for Softech Addons for Elementor
 * These are in global namespace so they can be called from anywhere
 * 
 * @package Softech_Addons_for_Elementor
 * @since 1.0.0
 */

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

/**
 * Check if Pro version is active
 * 
 * @return bool
 */
function sits_ea_is_pro_active() {  // Changed from sits_elementor_addons_is_pro_active
    return apply_filters('sits_elementor_addons_is_pro_active', false);
}

/**
 * Get Pro widgets information by scanning locked-widgets folder
 * Uses WordPress object cache for better performance
 * 
 * @return array Array of widget metadata
 */
function sits_get_pro_widgets_info() {
    // ✅ Check persistent cache first
    $cache_key = 'sits_pro_widgets_cache';
    $cached_widgets = wp_cache_get($cache_key);
    
    if (false !== $cached_widgets) {
        return is_array($cached_widgets) ? $cached_widgets : [];
    }
    
    $pro_widgets = [];
    $locked_widgets_dir = SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'locked-widgets/';
    
    // Check if directory exists
    if (!is_dir($locked_widgets_dir)) {
        // ✅ Cache empty result (1 hour)
        wp_cache_set($cache_key, [], '', 3600);
        return [];
    }
    
    // Only scan if Elementor is loaded
    if (!did_action('elementor/loaded')) {
        wp_cache_set($cache_key, [], '', 3600);
        return [];
    }
    
    // ✅ Use scandir() instead of glob() - more efficient
    $files = @scandir($locked_widgets_dir);
    
    if (empty($files) || !is_array($files)) {
        wp_cache_set($cache_key, [], '', 3600);
        return [];
    }
    
    // ✅ Filter for PHP files only
    $php_files = array_filter($files, function($file) {
        return substr($file, -4) === '.php' && $file[0] !== '.';
    });
    
    if (empty($php_files)) {
        wp_cache_set($cache_key, [], '', 3600);
        return [];
    }
    
    // Process each widget file
    foreach ($php_files as $file) {
        $file_path = $locked_widgets_dir . $file;
        $widget_info = sits_extract_widget_metadata($file_path);
        
        if (!empty($widget_info)) {
            $pro_widgets[] = $widget_info;
        }
    }
    
    // ✅ Cache for 1 hour (3600 seconds)
    wp_cache_set($cache_key, $pro_widgets, '', 3600);
    
    return $pro_widgets;
}

/**
 * Clear Pro widgets cache when plugin is updated
 * Call this on plugin upgrade/deactivation
 */
function sits_clear_pro_widgets_cache() {
    wp_cache_delete('sits_pro_widgets_cache');
}

/**
 * Extract widget metadata from file
 * 
 * @param string $file_path Full path to widget file
 * @return array|null Widget metadata or null if extraction fails
 */
function sits_extract_widget_metadata($file_path) {
    if (!file_exists($file_path)) {
        return null;
    }
    
    // Get file contents
    $file_contents = file_get_contents($file_path);
    
    if (false === $file_contents) {
        return null;
    }
    
    // Extract class name
    $class_name = sits_extract_class_name($file_contents);
    
    if (empty($class_name)) {
        return null;
    }
    
    // Load Base_Locked_Widget if not already loaded
    $base_widget_file = SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/Base_Locked_Widget.php';
    if (file_exists($base_widget_file) && !class_exists('\\Softech_Addons_for_Elementor\\Widgets\\Base_Locked_Widget')) {
        // Check if Elementor is loaded before loading Base_Locked_Widget
        if (!did_action('elementor/loaded')) {
            return null;
        }
        require_once $base_widget_file;
    }
    
    // Require the file
    require_once $file_path;
    
    // Build full class name with namespace
    $full_class_name = '\\Softech_Addons_for_Elementor\\Widgets\\' . $class_name;
    
    if (!class_exists($full_class_name)) {
        return null;
    }
    
    // Try to instantiate and get metadata
    try {
        $temp_instance = new $full_class_name();
        
        // Get metadata from the widget
        $metadata = method_exists($temp_instance, 'get_widget_metadata') 
            ? $temp_instance->get_widget_metadata() 
            : [];
        
        // Build widget info array
        $widget_info = [
            'name' => method_exists($temp_instance, 'get_name') ? $temp_instance->get_name() : $class_name,
            'title' => isset($metadata['title']) ? $metadata['title'] : $class_name,
            'description' => isset($metadata['description']) ? $metadata['description'] : '',
            'icon' => isset($metadata['icon']) ? $metadata['icon'] : 'eicon-lock',
            'categories' => isset($metadata['categories']) ? $metadata['categories'] : ['sits-category'],
            'keywords' => isset($metadata['keywords']) ? $metadata['keywords'] : [],
            'file' => basename($file_path),
            'class' => $class_name,
            'is_locked' => true,
        ];
        
        return $widget_info;
        
    } catch (\Exception $e) {
        return null;
    }
}

/**
 * Extract class name from PHP file contents
 * 
 * @param string $file_contents File contents
 * @return string|null Class name or null
 */
function sits_extract_class_name($file_contents) {
    // Pattern to match class declaration
    $pattern = '/class\s+([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/';
    
    if (preg_match($pattern, $file_contents, $matches)) {
        return isset($matches[1]) ? $matches[1] : null;
    }
    
    return null;
}

/**
 * Get default option value
 * 
 * @param string $key Option key
 * @param mixed $default Default value
 * @return mixed Option value or default
 */
function sits_get_option($key, $default = '') {
    $options = get_option('sits_elementor_addons_options', []);
    return isset($options[$key]) ? $options[$key] : $default;
}

/**
 * Check if widget is locked (Pro only)
 * 
 * @param string $widget_name Widget name/identifier
 * @return bool True if locked, false otherwise
 */
function sits_is_widget_locked($widget_name) {
    if (sits_ea_is_pro_active()) {
        return false;
    }
    
    $pro_widgets_info = sits_get_pro_widgets_info();
    
    foreach ($pro_widgets_info as $widget) {
        if (isset($widget['name']) && $widget['name'] === $widget_name) {
            return true;
        }
    }
    
    return false;
}

/**
 * Get all registered SITS widgets
 * 
 * @return array Array of widget information
 */
function sits_get_all_widgets() {
    $widgets = [];
    
    if (!class_exists('\Elementor\Plugin')) {
        return $widgets;
    }
    
    $elementor = \Elementor\Plugin::instance();
    
    if (!$elementor || !isset($elementor->widgets_manager)) {
        return $widgets;
    }
    
    $manager = $elementor->widgets_manager;
    $registered_widgets = method_exists($manager, 'get_widget_types') ? $manager->get_widget_types() : [];
    
    foreach ($registered_widgets as $widget_name => $widget_obj) {
        if (!is_object($widget_obj)) {
            continue;
        }
        
        $widget_name = method_exists($widget_obj, 'get_name') ? $widget_obj->get_name() : $widget_name;
        $widget_class = get_class($widget_obj);
        
        // Check if it's a SITS widget
        $is_sits_widget = (
            strpos($widget_name, 'sitsel') === 0 ||
            strpos($widget_name, 'sits_') === 0 ||
            strpos($widget_name, 'sits-') === 0 ||
            strpos($widget_class, 'sitsel') !== false ||
            strpos($widget_class, 'SITS') !== false
        );
        
        if ($is_sits_widget) {
            $widget_data = [
                'name' => $widget_name,
                'title' => method_exists($widget_obj, 'get_title') ? $widget_obj->get_title() : $widget_name,
                'class' => $widget_class,
                'is_locked' => sits_is_widget_locked($widget_name),
            ];
            
            if (method_exists($widget_obj, 'get_categories')) {
                $widget_data['categories'] = $widget_obj->get_categories();
            }
            
            if (method_exists($widget_obj, 'get_description')) {
                $widget_data['description'] = $widget_obj->get_description();
            }
            
            $widgets[] = $widget_data;
        }
    }
    
    return $widgets;
}

/**
 * Sanitize hex color
 * 
 * @param string $color Hex color value
 * @return string Sanitized hex color
 */
function sits_sanitize_hex_color($color) {
    if (empty($color)) {
        return '';
    }
    
    // Remove # if present
    $color = ltrim($color, '#');
    
    // Check if valid hex
    if (preg_match('/^[a-f0-9]{6}$/i', $color)) {
        return '#' . $color;
    }
    
    // Check if valid short hex
    if (preg_match('/^[a-f0-9]{3}$/i', $color)) {
        return '#' . $color;
    }
    
    return '';
}

/**
 * Get plugin version
 * 
 * @return string Plugin version
 */
function sits_get_plugin_version() {
    return defined('SITS_ELEMENTOR_ADDONS_VERSION') ? SITS_ELEMENTOR_ADDONS_VERSION : '1.2.4';
}

/**
 * Check if Elementor is active
 * 
 * @return bool
 */
function sits_is_elementor_active() {
    return did_action('elementor/loaded');
}

/**
 * Get upgrade URL
 * 
 * @return string Upgrade page URL
 */
function sits_get_upgrade_url() {
    return admin_url('admin.php?page=softech-addons-for-elementor&tab=pro');
}