<?php
/**
 * 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) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Release-reviewed diagnostic only; the message contains no credentials or request payloads and runs only in opt-in debugging or the administrative uninstall lifecycle.
            error_log('[AYSA UNINSTALL] Database tables deleted per user preference');
        }
    } else {
        // Log that tables were preserved
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Release-reviewed diagnostic only; the message contains no credentials or request payloads and runs only in opt-in debugging or the administrative uninstall lifecycle.
            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_active_access_key',
        'aysa_user_secret_key',
        'aysa_user_id',
        'aysa_auth_domain',
        'aysa_website_id',
        'aysa_wallet_app_internal_secret',
        'aysa_wallet_app_internal_secret_version',
        'aysa_wallet_app_internal_secret_scope',
        'aysa_oauth_broker_key_secret',
        'aysa_error_center_ingest_secret',
        'aysa_api_key',
        'aysa_adverlink_api_key',
        'aysa_pagespeed_api_key',
        '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_internal_linking_workspace_db_version',
        '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) {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Release-reviewed diagnostic only; the message contains no credentials or request payloads and runs only in opt-in debugging or the administrative uninstall lifecycle.
        error_log('[AYSA UNINSTALL] Plugin options cleaned up');
    }
}

/**
 * Remove the current site's authentication binding without deleting retained
 * operational tables. This mirrors the canonical disconnect flow so deleting
 * the plugin cannot leave a reusable site credential behind.
 */
function aysa_cleanup_site_auth_binding() {
    global $wpdb;

    $domain = (string) wp_parse_url(home_url('/'), PHP_URL_HOST);
    $domain = strtolower((string) preg_replace('/^www\./', '', trim($domain)));
    if ($domain === '') {
        return;
    }

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
    $wpdb->delete(
        $wpdb->prefix . 'aysa_user_auth',
        array('domain' => $domain),
        array('%s')
    );
}

/**
 * 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
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table));
        
        if ($table_exists) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Explicit uninstall policy removes only the fixed AYSA table allowlist after confirming each table exists. Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
            $wpdb->query("DROP TABLE IF EXISTS `{$table}`");
            
            // Log each table deletion
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Release-reviewed diagnostic only; the message contains no credentials or request payloads and runs only in opt-in debugging or the administrative uninstall lifecycle.
                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) {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Release-reviewed diagnostic only; the message contains no credentials or request payloads and runs only in opt-in debugging or the administrative uninstall lifecycle.
        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) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Release-reviewed diagnostic only; the message contains no credentials or request payloads and runs only in opt-in debugging or the administrative uninstall lifecycle.
            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);
        }
    }
    
    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- Removes only the plugin-owned cache directory after every child path has been deleted.
    return rmdir($dir);
}

/**
 * Main cleanup function
 */
function aysa_run_uninstall() {
    try {
        // Clean up plugin data (options and conditionally tables)
        aysa_cleanup_plugin_data();

        // Credentials must not survive deletion even when operational tables do.
        aysa_cleanup_site_auth_binding();
        
        // Clean up cron jobs
        aysa_cleanup_cron_jobs();
        
        // Clean up uploaded files
        aysa_cleanup_uploads();
        
        // Final log
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Release-reviewed diagnostic only; the message contains no credentials or request payloads and runs only in opt-in debugging or the administrative uninstall lifecycle.
            error_log('[AYSA UNINSTALL] Plugin uninstall completed successfully');
        }
        
    } catch (Exception $e) {
        // Log any errors that occur during uninstall
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Release-reviewed diagnostic only; the message contains no credentials or request payloads and runs only in opt-in debugging or the administrative uninstall lifecycle.
            error_log('[AYSA UNINSTALL ERROR] ' . $e->getMessage());
        }
    }
}

// Run the uninstall process
aysa_run_uninstall(); 
