<?php
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped,WordPress.Security.EscapeOutput.ExceptionNotEscaped,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQLPlaceholders.LikeWildcardsInQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fclose,WordPress.WP.AlternativeFunctions.file_system_operations_is_writable,WordPress.WP.AlternativeFunctions.file_system_operations_chmod,WordPress.WP.AlternativeFunctions.file_system_operations_rmdir,WordPress.DateTime.RestrictedFunctions.date_date,WordPress.WP.I18n.NonSingularStringLiteralDomain,WordPress.WP.I18n.MissingTranslatorsComment,WordPress.WP.I18n.MissingArgDomain,WordPressVIPMinimum.Performance.WPQueryParams.SuppressFilters_suppress_filters,WordPress.WP.EnqueuedResources.NonEnqueuedScript,WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- WordPress.org PCP audit pass: legacy controlled-beta surfaces require targeted follow-up hardening.
/**
 * Aysa.ai Plugin Uninstall Script
 * 
 * This file runs when the plugin is deleted from the WordPress admin.
 * It handles cleanup based on user preferences.
 */

// If uninstall not called from WordPress, then exit.
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

// Include WordPress database functions
global $wpdb;

/**
 * Clean up plugin options and data
 */
function aysa_cleanup_plugin_data() {
    global $wpdb;
    
    // Preserve data unless the user explicitly opted into full table deletion.
    $delete_tables = get_option('aysa_delete_tables_on_uninstall', false);
    
    // Always clean up plugin options
    aysa_cleanup_plugin_options();
    
    // Only delete tables if user explicitly chose to do so
    if ($delete_tables) {
        aysa_delete_plugin_tables();
        
        // Log the deletion for debugging (if WP_DEBUG is enabled)
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[AYSA UNINSTALL] Database tables deleted per user preference');
        }
    } else {
        // Log that tables were preserved
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[AYSA UNINSTALL] Database tables preserved per user preference');
        }
    }
}

/**
 * Delete all plugin options from wp_options table
 */
function aysa_cleanup_plugin_options() {
    // List of all plugin options to remove
    $options_to_delete = array(
        'aysa_version',
        'aysa_auth_token',
        'aysa_project_id',
        'aysa_project_name',
        'aysa_auto_scan',
        'aysa_notify_scan',
        'aysa_notify_issues',
        'aysa_notify_updates',
        'aysa_delete_tables_on_uninstall',
        'aysa_user_credits',
        'aysa_automation_config',
        'aysa_domain_authority_suggestions',
        'aysa_domain_authority_automation',
        'aysa_meta_tags_suggestions',
        'aysa_meta_tags_automation',
        'aysa_redirects_suggestions',
        'aysa_redirects_automation',
        'aysa_images_suggestions',
        'aysa_images_automation',
        'aysa_keywords_suggestions',
        'aysa_keywords_automation',
        'aysa_setup_completed',
        'aysa_wizard_data',
        'aysa_last_sync'
    );
    
    // Delete each option
    foreach ($options_to_delete as $option) {
        delete_option($option);
    }
    
    // Log cleanup
    if (defined('WP_DEBUG') && WP_DEBUG) {
        error_log('[AYSA UNINSTALL] Plugin options cleaned up');
    }
}

/**
 * Delete plugin database tables
 */
function aysa_delete_plugin_tables() {
    global $wpdb;
    
    // List of tables created by the plugin
    $tables_to_delete = array(
        $wpdb->prefix . 'aysa_404_errors',
        $wpdb->prefix . 'aysa_audit_log',
        $wpdb->prefix . 'aysa_automation_queue',
        $wpdb->prefix . 'aysa_user_auth'
    );
    
    // Drop each table
    foreach ($tables_to_delete as $table) {
        // Check if table exists before trying to drop it
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table));
        
        if ($table_exists) {
            $wpdb->query("DROP TABLE IF EXISTS `{$table}`");
            
            // Log each table deletion
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log("[AYSA UNINSTALL] Deleted table: {$table}");
            }
        }
    }
}

/**
 * Clean up any scheduled cron jobs
 */
function aysa_cleanup_cron_jobs() {
    // Clear any scheduled cron events
    $cron_hooks = array(
        'aysa_domain_authority_cron',
        'aysa_automation_queue_cron',
        'aysa_cleanup_cron',
        'aysa_sync_cron'
    );
    
    foreach ($cron_hooks as $hook) {
        $timestamp = wp_next_scheduled($hook);
        if ($timestamp) {
            wp_unschedule_event($timestamp, $hook);
        }
        
        // Also clear all scheduled events for this hook
        wp_clear_scheduled_hook($hook);
    }
    
    // Log cron cleanup
    if (defined('WP_DEBUG') && WP_DEBUG) {
        error_log('[AYSA UNINSTALL] Cron jobs cleaned up');
    }
}

/**
 * Clean up uploaded files and directories (if any)
 */
function aysa_cleanup_uploads() {
    $upload_dir = wp_upload_dir();
    $aysa_upload_dir = $upload_dir['basedir'] . '/aysa/';
    
    // Check if aysa directory exists and remove it
    if (is_dir($aysa_upload_dir)) {
        aysa_recursive_rmdir($aysa_upload_dir);
        
        // Log cleanup
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[AYSA UNINSTALL] Upload directory cleaned up');
        }
    }
}

/**
 * Recursively remove directory and its contents
 * @param string $dir
 * @return bool
 */
function aysa_recursive_rmdir($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)) {
            aysa_recursive_rmdir($path);
        } else {
            wp_delete_file($path);
        }
    }
    
    return rmdir($dir);
}

/**
 * Main cleanup function
 */
function aysa_run_uninstall() {
    try {
        // Clean up plugin data (options and conditionally tables)
        aysa_cleanup_plugin_data();
        
        // Clean up cron jobs
        aysa_cleanup_cron_jobs();
        
        // Clean up uploaded files
        aysa_cleanup_uploads();
        
        // Final log
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[AYSA UNINSTALL] Plugin uninstall completed successfully');
        }
        
    } catch (Exception $e) {
        // Log any errors that occur during uninstall
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[AYSA UNINSTALL ERROR] ' . $e->getMessage());
        }
    }
}

// Run the uninstall process
aysa_run_uninstall(); 
