<?php
/**
 * ExploreXR Addon Lifecycle Handler
 * 
 * Handles addon activation and deactivation lifecycle events
 */

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

class ExploreXR_Addon_Lifecycle_Handler {
    
    private $addon_manager;
    
    public function __construct($addon_manager) {
        $this->addon_manager = $addon_manager;
    }
    
    /**
     * Initialize lifecycle handling hooks
     */
    public function init() {
        add_action('activated_plugin', array($this, 'on_addon_activated'), 10, 2);
        add_action('deactivated_plugin', array($this, 'on_addon_deactivated'), 10, 1);
    }
    
    /**
     * Handle addon activation
     */
    public function on_addon_activated($plugin_file, $network_wide) {
        try {
            // Ensure WordPress functions are available
            if (!function_exists('plugin_basename')) {
                // Load WordPress plugin functions if not available
                if (defined('ABSPATH') && file_exists(ABSPATH . 'wp-admin/includes/plugin.php')) {
                    require_once ABSPATH . 'wp-admin/includes/plugin.php';
                } else {
                    // Defer activation to later when WordPress is fully loaded
                    add_action('init', function() use ($plugin_file, $network_wide) {
                        $this->on_addon_activated($plugin_file, $network_wide);
                    }, 20);
                    return;
                }
            }
            
            // Find which addon was activated
            foreach ($this->addon_manager->get_registered_addons() as $slug => $addon) {
                // Compare with plugin basename - use safe basename comparison
                $addon_basename = isset($addon['file']) ? plugin_basename($addon['file']) : '';
                if ($addon_basename === $plugin_file) {
                    
                    // Check license requirements
                    if (!$this->validate_addon_license_on_activation($slug, $addon, $plugin_file)) {
                        return; // License validation failed, addon was deactivated
                    }
                    
                    // Update addon options
                    $options_manager = $this->addon_manager->get_options_manager();
                    if ($options_manager) {
                        $options_manager->ensure_addon_options_active($slug);
                        
                        // Restore any previously disabled settings for this addon
                        $options_manager->restore_addon_settings($slug);
                    }
                    
                    // Update license selections if within limits
                    $this->update_license_selections($slug);
                    
                    // Mark this addon as recently activated to prevent immediate deactivation
                    set_transient('explorexr_recently_activated_' . $slug, true, 60); // 60 seconds
                    
                    // Notify admin about successful activation
                    add_action('admin_notices', function() use ($addon) {
                        ?>
                        <div class="notice notice-info is-dismissible">
                            <p>
                                <strong><?php echo esc_html($addon['name']); ?> has been activated.</strong> 
                                Any previously disabled settings have been restored.
                            </p>
                        </div>
                        <?php
                    });
                    
                    break;
                }
            }
        } catch (Error $e) {
            
            // Add admin notice about the error
            add_action('admin_notices', function() use ($e) {
                ?>
                <div class="notice notice-error is-dismissible">
                    <p>
                        <strong>ExploreXR Addon Activation Error:</strong> 
                        <?php echo esc_html($e->getMessage()); ?>
                        Please check the error logs for more details.
                    </p>
                </div>
                <?php
            });
        } catch (Exception $e) {
            // Add admin notice about the error
            add_action('admin_notices', function() use ($e) {
                ?>
                <div class="notice notice-error is-dismissible">
                    <p>
                        <strong>ExploreXR Addon Activation Error:</strong> 
                        <?php echo esc_html($e->getMessage()); ?>
                        Please check the error logs for more details.
                    </p>
                </div>
                <?php
            });
        }
    }
    
    /**
     * Validate addon license requirements on activation
     * 
     * @param string $slug
     * @param array $addon
     * @param string $plugin_file
     * @return bool True if validation passed, false if addon was deactivated
     */
    private function validate_addon_license_on_activation($slug, $addon, $plugin_file) {
        // Get license validator
        $license_validator = $this->addon_manager->get_license_validator();
        if (!$license_validator) {
            // No license validator means no license validation - deactivate addon
            deactivate_plugins($plugin_file);
            add_action('admin_notices', function() use ($addon) {
                ?>
                <div class="notice notice-error is-dismissible">
                    <p>
                        <strong><?php echo esc_html($addon['name']); ?> has been deactivated.</strong> 
                        A valid license is required to use ExploreXR add-ons.
                        <a href="<?php echo esc_url(admin_url('admin.php?page=explorexr-license')); ?>">Enter your license key</a> to use add-ons.
                    </p>
                </div>
                <?php
            });
            return false;
        }
        
        // Delegate to license validator
        return $license_validator->validate_addon_license_on_activation($slug, $addon, $plugin_file);
    }
    
    /**
     * Update license selections for activated addon
     * 
     * @param string $slug
     */
    private function update_license_selections($slug) {
        $license_handler = $this->get_license_handler_safely();
        if (!$license_handler) {
            return;
        }
        
        $max_addons = $license_handler->get_max_addons();
        
        // Count currently active addons
        $active_count = 0;
        foreach ($this->addon_manager->get_registered_addons() as $other_slug => $other_addon) {
            if ($other_slug !== $slug && $this->addon_manager->is_addon_active($other_slug)) {
                $active_count++;
            }
        }
        
        // Add to included addons if within limit
        if ($max_addons < 0 || ($active_count + 1) <= $max_addons) {
            $included_addons = $license_handler->get_included_addons();
            if (!in_array($slug, $included_addons)) {
                $included_addons[] = $slug;
                $license_handler->select_addons($included_addons);
            }
        }
    }
    
    /**
     * Handle addon deactivation
     * 
     * This method is called when an addon is deactivated to ensure all its
     * settings and options are properly deactivated for both frontend and backend security.
     * 
     * @param string $plugin_file The path to the plugin file being deactivated
     */
    public function on_addon_deactivated($plugin_file) {
        // Find which addon was deactivated
        $addon_slug = null;
        $addon_data = null;
        
        foreach ($this->addon_manager->get_registered_addons() as $slug => $addon) {
            // Compare with plugin basename
            if (isset($addon['file']) && plugin_basename($addon['file']) === $plugin_file) {
                $addon_slug = $slug;
                $addon_data = $addon;
                break;
            }
        }
        
        // If this isn't one of our addons, do nothing
        if ($addon_slug === null) {
            return;
        }
        
        // Clear any recently activated transient
        delete_transient('explorexr_recently_activated_' . $addon_slug);
        
        // 1. Disable addon in the addon list (if it's in the included addons)
        $license_handler = $this->get_license_handler_safely();
        if ($license_handler) {
            $included_addons = $license_handler->get_included_addons();
            if (in_array($addon_slug, $included_addons)) {
                $updated_addons = array_diff($included_addons, array($addon_slug));
                $license_handler->select_addons($updated_addons);
            }
        }
        
        // 2. Disable settings specific to this addon
        $options_manager = $this->addon_manager->get_options_manager();
        if ($options_manager) {
            $options_manager->disable_addon_settings($addon_slug);
        }
        
        // 3. Run cleanup hook for other plugins to hook into
        do_action('explorexr_premium_addon_deactivated', $addon_slug, $addon_data);
        
        // 4. Notify admin about the deactivation and security measures
        add_action('admin_notices', function() use ($addon_slug, $addon_data) {
            $addon_name = isset($addon_data['name']) ? $addon_data['name'] : ucfirst($addon_slug);
            ?>
            <div class="notice notice-info is-dismissible">
                <p>
                    <strong><?php echo esc_html($addon_name); ?> has been deactivated.</strong> 
                    All related settings and options have been disabled for security. 
                    The settings data is preserved and will be reactivated if you enable the addon again.
                </p>
            </div>
            <?php
        });
    }
    
    /**
     * Safely get license handler instance with proper error handling
     * 
     * @return explorexr_premium_License_Handler|null
     */
    private function get_license_handler_safely() {
        try {
            // Check if class exists
            if (!class_exists('ExploreXR_License_Handler')) {
                // Try to load the license handler
                $license_handler_paths = array(
                    EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/licensing/license-handler.php',
                    EXPLOREXR_PREMIUM_PLUGIN_DIR . 'includes/security/licensing/license-handler.php'
                );
                
                foreach ($license_handler_paths as $path) {
                    if (file_exists($path)) {
                        require_once $path;
                        break;
                    }
                }
                
                // If still not available, return null
                if (!class_exists('ExploreXR_License_Handler')) {
                    return null;
                }
            }
            
            // Use singleton instance instead of creating new instance
            return ExploreXR_License_Handler::instance();
            
        } catch (Error $e) {
            return null;
        } catch (Exception $e) {
            return null;
        }
    }
}
