<?php
declare(strict_types=1);


/**
 * Extension Manager
 *
 * @package ProRank\Core
 */

namespace ProRank\SEO\Core;

use ProRank\SEO\Plugin;

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


/**
 * Manages plugin extensions
 */


class ExtensionManager {
    
    /**
     * Extension directory path
     *
     * @var string
     */
    private string $extension_dir;
    
    /**
     * Loaded extensions
     *
     * @var array
     */
    private array $extensions = [];
    
    /**
     * License manager instance
     *
     * @var LicenseManager
     */
    private LicenseManager $license;
    
    /**
     * API base URL
     *
     * @var string
     */
    private string $api_url = 'https://prorank.io/api/wp/extensions';
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->extension_dir = WP_CONTENT_DIR . '/prorank-extensions';
        $this->ensure_extension_directory();
    }
    
    /**
     * Initialize the extension manager
     */
    public function init(): void {
        // Get plugin instance to access license manager
        $plugin = Plugin::get_instance();
        $this->license = $plugin->license();
        
        // Load installed extensions
        $this->load_extensions();
        
        // Register hooks
        add_action('wp_ajax_prorank_get_extensions', [$this, 'ajax_get_extensions']);
        add_action('wp_ajax_prorank_install_extension', [$this, 'ajax_install_extension']);
        add_action('wp_ajax_prorank_remove_extension', [$this, 'ajax_remove_extension']);
    }
    
    /**
     * Ensure extension directory exists
     */
    private function ensure_extension_directory(): void {
        if (!file_exists($this->extension_dir)) {
            wp_mkdir_p($this->extension_dir);
            
            // Add .htaccess for security
            $htaccess = $this->extension_dir . '/.htaccess';
            if (!file_exists($htaccess)) {
                file_put_contents($htaccess, "Options -Indexes\nDeny from all");
            }
        }
    }
    
    /**
     * Load installed extensions
     */
    public function load_extensions(): void {
        if (!is_dir($this->extension_dir)) {
            return;
        }
        
        $extension_folders = glob($this->extension_dir . '/*', GLOB_ONLYDIR);
        
        foreach ($extension_folders as $folder) {
            $manifest_file = $folder . '/extension.json';
            if (file_exists($manifest_file)) {
                $manifest = json_decode(file_get_contents($manifest_file), true);
                if ($manifest) {
                    $extension_id = basename($folder);
                    $this->extensions[$extension_id] = $manifest;
                    
                    // Extensions are loaded later after all core modules
                    // to prevent conflicts
                }
            }
        }
    }
    
    /**
     * Initialize extension modules after core modules are loaded
     */
    public function init_extension_modules(): void {
        foreach ($this->extensions as $extension_id => $manifest) {
            $folder = $this->extension_dir . '/' . $extension_id;
            $this->load_extension_modules($extension_id, $folder);
        }
    }
    
    /**
     * Load modules from an extension
     */
    private function load_extension_modules(string $extension_id, string $path): void {
        // Extension modules are loaded via bootstrap.php
        // which handles proper loading order and prevents duplicates
        $bootstrap = $path . '/bootstrap.php';
        if (file_exists($bootstrap)) {
            require_once $bootstrap;
        }
    }
    
    /**
     * Get available extensions from API
     */
    public function get_available_extensions(): array {
        try {
            $domain = wp_parse_url(home_url(), PHP_URL_HOST);
            
            // Extensions are free to list and install - no license required
            $response = wp_remote_get($this->api_url . '/list', [
                'headers' => [
                    'X-Domain' => $domain,
                    'X-Plugin-Version' => PRORANK_VERSION,
                ],
                'timeout' => 15,
            ]);
            
            if (is_wp_error($response)) {
                prorank_log('[ProRank SEO] Failed to fetch extensions: ' . $response->get_error_message());
                return [];
            }
            
            $response_code = wp_remote_retrieve_response_code($response);
            if ($response_code !== 200) {
                prorank_log('[ProRank SEO] Extensions API returned code ' . $response_code);
                prorank_log('[ProRank SEO] Response body: ' . wp_remote_retrieve_body($response));
                return [];
            }
            
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                prorank_log('[ProRank SEO] Failed to parse extensions response: ' . json_last_error_msg());
                return [];
            }
            
            $extensions = $data['extensions'] ?? [];
            
            return $extensions;
        } catch (\Exception $e) {
            prorank_log('[ProRank SEO] Exception fetching extensions: ' . $e->getMessage());
            return [];
        }
    }
    
    
    
    
    /**
     * Get installed extensions
     */
    public function get_installed_extensions(): array {
        return $this->extensions;
    }
    
    /**
     * Check if extension is installed
     */
    public function is_installed(string $extension_id): bool {
        return isset($this->extensions[$extension_id]);
    }
    
    /**
     * Install an extension
     */
    public function install_extension(string $extension_id): bool {
        try {
            $domain = wp_parse_url(home_url(), PHP_URL_HOST);
            
            // Request download URL from API - no license required for installation
            $response = wp_remote_get($this->api_url . '/download/' . $extension_id, [
                'headers' => [
                    'X-Domain' => $domain,
                    'X-Plugin-Version' => PRORANK_VERSION,
                ],
                'timeout' => 30,
            ]);
            
            if (is_wp_error($response)) {
                prorank_log('[ProRank SEO] Failed to get extension download URL: ' . $response->get_error_message());
                return false;
            }
            
            $response_code = wp_remote_retrieve_response_code($response);
            if ($response_code !== 200) {
                prorank_log('[ProRank SEO] Extension download API returned code ' . $response_code);
                return false;
            }
            
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            
            if (empty($data['download_url'])) {
                prorank_log('[ProRank SEO] No download URL received for extension');
                return false;
            }
            
            // Download extension
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            $temp_file = download_url($data['download_url']);
            if (is_wp_error($temp_file)) {
                prorank_log('[ProRank SEO] Failed to download extension: ' . $temp_file->get_error_message());
                return false;
            }
            
            // Extract to extensions directory
            WP_Filesystem();
            $result = unzip_file($temp_file, $this->extension_dir);
            \ProRank\SEO\Core\FilesystemHelper::delete_file($temp_file);
            
            if (is_wp_error($result)) {
                prorank_log('[ProRank SEO] Failed to extract extension: ' . $result->get_error_message());
                return false;
            }
            
            // Reload extensions
            $this->load_extensions();
            return true;
            
        } catch (\Exception $e) {
            prorank_log('[ProRank SEO] Exception installing extension: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Remove an extension
     */
    public function remove_extension(string $extension_id): bool {
        $extension_path = $this->extension_dir . '/' . $extension_id;
        
        if (!is_dir($extension_path)) {
            return false;
        }
        
        // Use WordPress filesystem API
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        WP_Filesystem();
        global $wp_filesystem;
        
        $result = $wp_filesystem->delete($extension_path, true);
        
        if ($result) {
            unset($this->extensions[$extension_id]);
        }
        
        return $result;
    }
    
    /**
     * AJAX handler: Get extensions list
     */
    public function ajax_get_extensions(): void {
        check_ajax_referer('prorank_ajax_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die();
        }
        
        $available = $this->get_available_extensions();
        $installed = $this->get_installed_extensions();
        
        wp_send_json_success([
            'available' => $available,
            'installed' => $installed,
        ]);
    }
    
    /**
     * AJAX handler: Install extension
     */
    public function ajax_install_extension(): void {
        check_ajax_referer('prorank_ajax_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die();
        }
        
        $extension_id = sanitize_text_field($_POST['extension_id'] ?? '');
        
        if (empty($extension_id)) {
            wp_send_json_error(__('Invalid extension ID', 'prorank-seo'));
        }
        
        $result = $this->install_extension($extension_id);
        
        if ($result) {
            wp_send_json_success(__('Extension installed successfully', 'prorank-seo'));
        } else {
            wp_send_json_error(__('Failed to install extension', 'prorank-seo'));
        }
    }
    
    /**
     * AJAX handler: Remove extension
     */
    public function ajax_remove_extension(): void {
        check_ajax_referer('prorank_ajax_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die();
        }
        
        $extension_id = sanitize_text_field($_POST['extension_id'] ?? '');
        
        if (empty($extension_id)) {
            wp_send_json_error(__('Invalid extension ID', 'prorank-seo'));
        }
        
        $result = $this->remove_extension($extension_id);
        
        if ($result) {
            wp_send_json_success(__('Extension removed successfully', 'prorank-seo'));
        } else {
            wp_send_json_error(__('Failed to remove extension', 'prorank-seo'));
        }
    }
}