<?php
/**
 * Aysa Plugin Updater - Simplified Version
 * Based on Adverlink's successful update system
 */

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

class Aysa_Updater {
    
    private $plugin_slug;
    private $version;
    private $api_url;
    private $plugin_file;
    private $cache_key;
    
    /**
     * Constructor
     */
    public function __construct($plugin_file, $api_url = '') {
        $this->plugin_file = $plugin_file;
        $this->plugin_slug = plugin_basename($plugin_file);
        $this->version = AYSA_VERSION;
        $this->api_url = $api_url;
        $this->cache_key = 'aysa_update_check';
        
        $this->init();
    }
    
    /**
     * Initialize hooks - WordPress standard approach
     */
    private function init() {
        // Main update check filters - use both for compatibility
        add_filter('pre_set_site_transient_update_plugins', array($this, 'check_for_plugin_update'));
        add_filter('site_transient_update_plugins', array($this, 'check_for_plugin_update'));
        
        // Plugin information filter  
        add_filter('plugins_api', array($this, 'plugin_update_information'), 10, 3);
        
        // Update process hooks - Fixed order and conflicts
        add_filter('upgrader_pre_install', array($this, 'pre_update'), 10, 2);
        add_filter('upgrader_post_install', array($this, 'after_update'), 10, 3);
        add_action('upgrader_process_complete', array($this, 'upgrade_completed'), 10, 2);
        
        // Enhanced cleanup hooks - with better timing
        add_filter('upgrader_pre_download', array($this, 'pre_download_cleanup'), 10, 3);
        add_action('upgrader_process_complete', array($this, 'post_update_cleanup'), 20, 2);
        
        // CRITICAL: Aggressive cleanup before any WordPress update process starts
        add_action('upgrader_process_complete', array($this, 'final_cleanup'), 30, 2);
        
        // Additional safety cleanup hooks
        add_action('wp_ajax_update-plugin', array($this, 'ajax_update_cleanup'), 1);
        add_action('admin_init', array($this, 'maybe_prepare_update_request'), 1);
        
        // Daily cleanup cron
        add_action('wp', array($this, 'schedule_temp_cleanup'));
        add_action('aysa_cleanup_temp_directories', array($this, 'cleanup_old_temp_directories'));
    }

    /**
     * Prepare cleanup before WordPress starts a plugin update request.
     * This prevents the "first click fails, second click works" pattern caused by stale backup folders.
     */
    public function maybe_prepare_update_request() {
        if (!is_admin() || !current_user_can('update_plugins')) {
            return;
        }

        $plugin = isset($_REQUEST['plugin']) ? sanitize_text_field(wp_unslash((string) $_REQUEST['plugin'])) : '';
        $action = isset($_REQUEST['action']) ? sanitize_key((string) $_REQUEST['action']) : '';
        $bulk_plugins = isset($_REQUEST['plugins']) ? (array) wp_unslash($_REQUEST['plugins']) : array();
        $bulk_plugins = array_map('sanitize_text_field', $bulk_plugins);

        $is_target_plugin = ($plugin === $this->plugin_slug) || in_array($this->plugin_slug, $bulk_plugins, true);
        $is_update_action = in_array($action, array('upgrade-plugin', 'update-plugin', 'update-selected', 'upload-plugin'), true);

        if (!$is_target_plugin || !$is_update_action) {
            return;
        }

        aysa_debug_log('Aysa Update: Pre-request cleanup started for action ' . $action);
        $this->ensure_wordpress_upgrade_directories();
        $this->cleanup_plugin_temp_directories();
        $this->fix_empty_backup_directories();
        $this->aggressive_backup_cleanup();
        $this->ensure_wordpress_upgrade_directories();
        aysa_debug_log('Aysa Update: Pre-request cleanup completed for action ' . $action);
    }
    
    /**
     * Check for plugin updates - WordPress standard approach
     */
    public function check_for_plugin_update($transient) {
        // Basic checks
        if (empty($transient->checked)) {
            return $transient;
        }
        
        if (!isset($transient->checked[$this->plugin_slug])) {
            return $transient;
        }
        
        aysa_debug_log('Aysa: Starting update check');
        
        // Get remote version
        $remote_info = $this->get_plugin_metadata_from_api();
        
        if (!$remote_info) {
            return $transient;
        }
        
        // Check version and add to update queue if newer
        if (version_compare($this->version, $remote_info->new_version, '<')) {
            $transient->response[$this->plugin_slug] = (object) array(
                'slug' => dirname($this->plugin_slug),
                'plugin' => $this->plugin_slug,
                'new_version' => $remote_info->new_version,
                'url' => isset($remote_info->homepage) ? $remote_info->homepage : '',
                'package' => $remote_info->package,
                'tested' => isset($remote_info->tested) ? $remote_info->tested : '',
                'requires' => isset($remote_info->requires) ? $remote_info->requires : '',
                'compatibility' => isset($remote_info->compatibility) ? $remote_info->compatibility : new stdClass()
            );
            
            aysa_debug_log('Aysa: Update found - version ' . $remote_info->new_version . ' available');
        }
        
        return $transient;
    }
    
    /**
     * Get plugin information for update details
     */
    public function plugin_update_information($result, $action, $args) {
        $plugin_dir = dirname($this->plugin_slug);
        
        if ($action !== 'plugin_information' || 
            !isset($args->slug) || 
            $args->slug !== $plugin_dir) {
            return $result;
        }
        
        $plugin_info = $this->get_plugin_metadata_from_api();
        
        if (!$plugin_info) {
            return $result;
        }
        
        return (object) array(
            'name' => isset($plugin_info->name) ? $plugin_info->name : 'Aysa.ai - Research & Analysis',
            'slug' => $plugin_dir,
            'version' => $plugin_info->new_version,
            'tested' => isset($plugin_info->tested) ? $plugin_info->tested : '',
            'requires' => isset($plugin_info->requires) ? $plugin_info->requires : '',
            'author' => 'Aysa.ai',
            'download_link' => $plugin_info->package,
            'sections' => isset($plugin_info->sections) ? (array) $plugin_info->sections : array()
        );
    }
    
    /**
     * Get plugin metadata from API - Simplified
     */
    public function get_plugin_metadata_from_api() {
        global $wp_version;
        
        $request_data = array(
            'slug' => dirname($this->plugin_slug),
            'version' => $this->version,
            'site_url' => get_site_url(),
            'wp_version' => $wp_version,
            'php_version' => PHP_VERSION
        );
        
        aysa_debug_log('Aysa Update: API request to ' . $this->api_url);
        aysa_debug_log('Aysa Update: Request data - ' . json_encode($request_data));
        
        $response = wp_remote_post($this->api_url, array(
            'method' => 'POST',
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ),
            'body' => json_encode($request_data)
        ));
        
        if (is_wp_error($response)) {
            aysa_debug_log('Aysa Update: API Error - ' . $response->get_error_message());
            return false;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        
        if ($response_code !== 200) {
            aysa_debug_log('Aysa Update: HTTP Error ' . $response_code . ' - ' . $body);
            return false;
        }
        
        $data = json_decode($body);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            aysa_debug_log('Aysa Update: JSON Error - ' . json_last_error_msg());
            return false;
        }
        
        aysa_debug_log('Aysa Update: API Response - ' . print_r($data, true));
        
        return $data;
    }
    
    /**
     * Pre-update hook - Save plugin state and aggressive cleanup
     */
    public function pre_update($return, $args) {
        if (isset($args['plugin']) && $args['plugin'] === $this->plugin_slug) {
            aysa_debug_log('Aysa Update: Pre-update started');
            $this->ensure_wordpress_upgrade_directories();
            
            // Save activation state
            $was_active = is_plugin_active($this->plugin_slug);
            update_option('aysa_was_active', $was_active);
            
            // CRITICAL: Aggressive cleanup before update
            $this->cleanup_plugin_temp_directories();
            $this->fix_empty_backup_directories();
            $this->aggressive_backup_cleanup();
            $this->ensure_wordpress_upgrade_directories();
            
            aysa_debug_log('Aysa Update: Pre-update completed - Plugin was ' . ($was_active ? 'active' : 'inactive'));
        }
        return $return;
    }
    
    /**
     * Post-update hook - Reactivate if needed like Adverlink
     */
    public function after_update($return, $hook_extra, $result) {
        if (isset($hook_extra['plugin']) && $hook_extra['plugin'] === $this->plugin_slug) {
            if (get_option('aysa_was_active')) {
                // Reactivate plugin
                $activate_result = activate_plugin($this->plugin_slug);
                
                if (!is_wp_error($activate_result)) {
                    delete_option('aysa_was_active');
                    aysa_debug_log('Aysa Update: Successfully reactivated after update');
                } else {
                    aysa_debug_log('Aysa Update: Failed to reactivate - ' . $activate_result->get_error_message());
                }
            }
        }
        return $return;
    }
    
    /**
     * Upgrade completed hook - Final check and cleanup
     */
    public function upgrade_completed($upgrader_object, $options) {
        if ($options['action'] === 'update' && $options['type'] === 'plugin') {
            if (isset($options['plugins'])) {
                foreach ($options['plugins'] as $plugin) {
                    if ($plugin === $this->plugin_slug) {
                        aysa_debug_log('Aysa Update: Upgrade completed hook started');
                        
                        // Final activation check
                        if (get_option('aysa_was_active') && !is_plugin_active($plugin)) {
                            activate_plugin($plugin);
                            delete_option('aysa_was_active');
                            aysa_debug_log('Aysa Update: Final activation check completed');
                        }
                        
                        // CRITICAL: Final cleanup to prevent future issues
                        $this->cleanup_plugin_temp_directories();
                        $this->fix_empty_backup_directories();
                        $this->aggressive_backup_cleanup();
                        
                        // Clear update cache
                        delete_transient($this->cache_key);
                        delete_option('aysa_last_update_check');
                        
                        aysa_debug_log('Aysa Update: Upgrade completed hook finished');
                        break;
                    }
                }
            }
        }
    }
    
    /**
     * Clean plugin temporary directories - Enhanced to fix backup issues
     */
    public function cleanup_plugin_temp_directories() {
        $cleanup_paths = array(
            WP_CONTENT_DIR . '/plugins/aysaaiseo-tmp',
            WP_CONTENT_DIR . '/plugins/aysaaiseo.tmp',
            WP_CONTENT_DIR . '/upgrade-temp-backup/plugins/aysaaiseo',
            WP_CONTENT_DIR . '/upgrade/aysaaiseo',
            ABSPATH . 'wp-content/upgrade-temp-backup/plugins/aysaaiseo',
            ABSPATH . 'wp-content/upgrade/aysaaiseo'
        );
        
        foreach ($cleanup_paths as $path) {
            if (is_dir($path)) {
                aysa_debug_log('Aysa Update: Attempting to clean - ' . $path);
                
                // AGGRESSIVE CLEANUP - Try multiple methods
                $success = false;
                
                // Method 1: Standard recursive removal
                if ($this->remove_directory_recursive($path)) {
                    aysa_debug_log('Aysa Update: SUCCESS - Standard removal - ' . $path);
                    $success = true;
                } 
                // Method 2: Force removal with WP_Filesystem
                else if ($this->force_remove_directory($path)) {
                    aysa_debug_log('Aysa Update: SUCCESS - Force removal - ' . $path);
                    $success = true;
                }
                // Method 3: Permission fix and retry
                else {
                    aysa_debug_log('Aysa Update: Trying permission fix - ' . $path);
                    if ($this->fix_permissions_and_remove($path)) {
                        aysa_debug_log('Aysa Update: SUCCESS - Permission fix removal - ' . $path);
                        $success = true;
                    }
                }
                
                if (!$success) {
                    aysa_debug_log('Aysa Update: FAILED ALL METHODS - ' . $path);
                }
            }
        }
        
        // Special handling for the backup issue
        $this->aggressive_backup_cleanup();
        $this->ensure_wordpress_upgrade_directories();
    }
    
    /**
     * Force remove directory using alternative methods
     */
    private function force_remove_directory($path) {
        if (!is_dir($path)) {
            return true;
        }
        
        try {
            // Try WordPress filesystem API first
            if (!function_exists('WP_Filesystem')) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
            }
            
            if (WP_Filesystem(false)) {
                global $wp_filesystem;
                if (method_exists($wp_filesystem, 'rmdir')) {
                    $result = $wp_filesystem->rmdir($path, true);
                    if ($result) {
                        aysa_debug_log('Aysa Update: Force removed directory with WP_Filesystem - ' . $path);
                        return true;
                    }
                }
            }
        } catch (Exception $e) {
            aysa_debug_log('Aysa Update: WP_Filesystem failed - ' . $e->getMessage());
        }
        
        // Last fallback: native recursive delete, without shell execution.
        return $this->remove_directory_recursive($path);
    }
    
    /**
     * Remove directory recursively
     */
    private function remove_directory_recursive($dir) {
        if (!is_dir($dir)) {
            return false;
        }
        
        $files = array_diff(scandir($dir), array('.', '..'));
        foreach ($files as $file) {
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            if (is_dir($path)) {
                $this->remove_directory_recursive($path);
            } else {
                unlink($path);
            }
        }
        return rmdir($dir);
    }
    
    /**
     * Schedule temp cleanup
     */
    public function schedule_temp_cleanup() {
        if (!wp_next_scheduled('aysa_cleanup_temp_directories')) {
            wp_schedule_event(time(), 'daily', 'aysa_cleanup_temp_directories');
        }
    }
    
    /**
     * Cleanup old temp directories (cron job)
     */
    public function cleanup_old_temp_directories() {
        $this->cleanup_plugin_temp_directories();
        aysa_debug_log('Aysa Update: Daily temp directory cleanup completed');
    }
    
    /**
     * Force update check
     */
    public function force_update_check() {
        delete_option('aysa_last_update_check');
        delete_transient($this->cache_key);
        delete_site_transient('update_plugins');
        wp_cache_flush();
        wp_update_plugins();
        aysa_debug_log('Aysa Update: Forced update check');
    }
    
    /**
     * Clear update cache
     */
    public function clear_update_cache() {
        delete_transient($this->cache_key);
        delete_site_transient('update_plugins');
        delete_option('aysa_last_update_check');
        aysa_debug_log('Aysa Update: Update cache cleared');
    }
    

    
    /**
     * Pre-download cleanup to prevent conflicts
     */
    public function pre_download_cleanup($pre_download, $url, $upgrader) {
        // Check if this is our plugin update
        if (isset($upgrader->skin->plugin) && $upgrader->skin->plugin === $this->plugin_slug) {
            aysa_debug_log('Aysa Update: Pre-download cleanup started');
            $this->ensure_wordpress_upgrade_directories();
            $this->cleanup_plugin_temp_directories();
            $this->fix_empty_backup_directories();
            $this->aggressive_backup_cleanup();
            $this->ensure_wordpress_upgrade_directories();
            aysa_debug_log('Aysa Update: Pre-download cleanup completed');
        }
        return $pre_download;
    }
    
    /**
     * Post-update cleanup - runs after the upgrade is complete
     */
    public function post_update_cleanup($upgrader_object, $options) {
        if ($options['action'] === 'update' && $options['type'] === 'plugin') {
            if (isset($options['plugins'])) {
                foreach ($options['plugins'] as $plugin) {
                    if ($plugin === $this->plugin_slug) {
                        aysa_debug_log('Aysa Update: Post-update cleanup started');
                        
                        // CRITICAL: Aggressive cleanup after successful update
                        $this->cleanup_plugin_temp_directories();
                        $this->fix_empty_backup_directories();
                        $this->aggressive_backup_cleanup();
                        
                        aysa_debug_log('Aysa Update: Post-update cleanup completed');
                        break;
                    }
                }
            }
        }
    }
    
    /**
     * Fix empty backup directories that prevent subsequent updates
     */
    public function fix_empty_backup_directories() {
        $backup_paths = array(
            WP_CONTENT_DIR . '/upgrade-temp-backup/plugins/aysaaiseo'
        );
        
        foreach ($backup_paths as $path) {
            if (is_dir($path)) {
                // Check if directory is empty or contains only empty subdirectories
                if ($this->is_directory_empty($path)) {
                    aysa_debug_log('Aysa Update: Removing empty backup directory - ' . $path);
                    $this->remove_directory_recursive($path);
                } else {
                    // Force remove our plugin's backup directory specifically
                    if (strpos($path, 'aysaaiseo') !== false) {
                        aysa_debug_log('Aysa Update: Force removing plugin backup directory - ' . $path);
                        $this->remove_directory_recursive($path);
                    }
                }
            }
        }
    }
    
    /**
     * Check if directory is empty or contains only empty subdirectories
     */
    private function is_directory_empty($dir) {
        if (!is_dir($dir)) {
            return true;
        }
        
        $files = array_diff(scandir($dir), array('.', '..'));
        
        if (empty($files)) {
            return true;
        }
        
        // Check if all items are empty directories
        foreach ($files as $file) {
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            if (is_file($path)) {
                return false; // Has files, not empty
            }
            if (is_dir($path) && !$this->is_directory_empty($path)) {
                return false; // Has non-empty subdirectory
            }
        }
        
        return true; // All subdirectories are empty
    }
    
    /**
     * Fix permissions and remove directory - NEW METHOD
     */
    private function fix_permissions_and_remove($path) {
        if (!is_dir($path)) {
            return true;
        }
        
        try {
            // Try to fix permissions recursively
            $this->fix_directory_permissions($path);
            
            // Wait a moment for filesystem to update
            usleep(100000); // 0.1 seconds
            
            // Try removal again
            return $this->remove_directory_recursive($path);
        } catch (Exception $e) {
            aysa_debug_log('Aysa Update: Permission fix failed - ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Fix directory permissions recursively
     */
    private function fix_directory_permissions($dir) {
        if (!is_dir($dir)) {
            return;
        }
        
        // Set directory to writable
        @chmod($dir, 0755);
        
        $files = array_diff(scandir($dir), array('.', '..'));
        foreach ($files as $file) {
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            if (is_dir($path)) {
                $this->fix_directory_permissions($path);
            } else {
                @chmod($path, 0644);
            }
        }
    }
    
    /**
     * Aggressive backup cleanup - CRITICAL for fixing update issues
     */
    private function aggressive_backup_cleanup() {
        aysa_debug_log('Aysa Update: Starting aggressive backup cleanup');
        
        $backup_base = WP_CONTENT_DIR . '/upgrade-temp-backup';
        
        // Step 1: Remove plugin-specific backup
        $plugin_backup = $backup_base . '/plugins/aysaaiseo';
        if (is_dir($plugin_backup)) {
            aysa_debug_log('Aysa Update: Removing plugin backup - ' . $plugin_backup);
            $this->nuclear_remove_directory($plugin_backup);
        }
        
        aysa_debug_log('Aysa Update: Aggressive backup cleanup completed');
    }

    /**
     * Ensure WordPress core upgrade directories exist.
     * Prevents "directory could not be read" failures during plugin updates.
     */
    private function ensure_wordpress_upgrade_directories() {
        $required_dirs = array(
            WP_CONTENT_DIR . '/upgrade',
            WP_CONTENT_DIR . '/upgrade-temp-backup',
            WP_CONTENT_DIR . '/upgrade-temp-backup/plugins',
        );

        foreach ($required_dirs as $dir) {
            if (!is_dir($dir)) {
                wp_mkdir_p($dir);
            }
            if (is_dir($dir) && !is_writable($dir)) {
                @chmod($dir, 0755);
            }
        }
    }
    
    /**
     * Nuclear directory removal - last resort method
     */
    private function nuclear_remove_directory($path) {
        if (!is_dir($path)) {
            return true;
        }
        
        aysa_debug_log('Aysa Update: Nuclear removal attempt - ' . $path);
        
        // Method 1: Standard
        if ($this->remove_directory_recursive($path)) {
            aysa_debug_log('Aysa Update: Nuclear - Standard method worked');
            return true;
        }
        
        // Method 2: Permission fix + removal
        $this->fix_directory_permissions($path);
        usleep(200000); // 0.2 seconds wait
        if ($this->remove_directory_recursive($path)) {
            aysa_debug_log('Aysa Update: Nuclear - Permission fix worked');
            return true;
        }
        
        // Method 3: Force removal
        if ($this->force_remove_directory($path)) {
            aysa_debug_log('Aysa Update: Nuclear - Force removal worked');
            return true;
        }
        
        aysa_debug_log('Aysa Update: Nuclear removal FAILED - ' . $path);
        return false;
    }
    
    /**
     * Final cleanup - runs after the upgrade is complete
     */
    public function final_cleanup($upgrader_object, $options) {
        if ($options['action'] === 'update' && $options['type'] === 'plugin') {
            if (isset($options['plugins'])) {
                foreach ($options['plugins'] as $plugin) {
                    if ($plugin === $this->plugin_slug) {
                        aysa_debug_log('Aysa Update: Final cleanup started');
                        
                        // Clean up after successful update
                        $this->cleanup_plugin_temp_directories();
                        $this->fix_empty_backup_directories();
                        
                        aysa_debug_log('Aysa Update: Final cleanup completed');
                        break;
                    }
                }
            }
        }
    }
    
    /**
     * AJAX cleanup - runs when a plugin update is initiated
     */
    public function ajax_update_cleanup() {
        if (!current_user_can('update_plugins')) {
            return;
        }

        $nonce = isset($_REQUEST['_ajax_nonce']) ? sanitize_text_field(wp_unslash((string) $_REQUEST['_ajax_nonce'])) : '';
        if ($nonce === '' || !wp_verify_nonce($nonce, 'updates')) {
            return;
        }

        aysa_debug_log('Aysa Update: AJAX cleanup started');
        $this->cleanup_plugin_temp_directories();
        $this->fix_empty_backup_directories();
        aysa_debug_log('Aysa Update: AJAX cleanup completed');
    }
}
