<?php
/**
 * Image Boost Uninstall Handler
 * Removes all plugin data when uninstalled (only if user opted in).
 */

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

global $wpdb;

// Respect user's data retention preference
				// No silent data destruction
if (!get_option('imgboost_remove_data_on_uninstall', 0)) {
    return;
}

function imgboost_cleanup_site() {
    global $wpdb;

    // Drop custom table
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
    $wpdb->query("DROP TABLE IF EXISTS " . esc_sql($wpdb->prefix . 'imgboost_log'));

    // Remove all options safely
    $options = [
        'imgboost_compression_level',
        'imgboost_auto_optimize',
        'imgboost_webp_enabled',
        'imgboost_avif_enabled',
        'imgboost_max_width',
        'imgboost_strip_metadata',
        'imgboost_keep_copyright',
        'imgboost_backup_enabled',
        'imgboost_backup_days',
        'imgboost_lazy_loading',
        'imgboost_convert_png',
        'imgboost_resize_enabled',
        'imgboost_batch_size',
        'imgboost_ignored_sizes',
        'imgboost_db_version',
        'imgboost_auto_queue',
        'imgboost_remove_data_on_uninstall',
        'imgboost_lifetime_count',
    ];
    foreach ($options as $opt) {
        delete_option($opt);
    }

    // Remove post meta safely (chunked to prevent DB Table Locks)
    $meta_keys = [
        '_imgboost_status',
        '_imgboost_original_size',
        '_imgboost_new_size',
        '_imgboost_savings',
        '_imgboost_level',
        '_imgboost_optimized_size',
        '_imgboost_webp_path',
        '_imgboost_avif_path',
        '_imgboost_backup_path',
        '_imgboost_has_backup',
        '_imgboost_error',
    ];
    global $wpdb;
    foreach ($meta_keys as $key) {
        do {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $deleted = $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE meta_key = %s LIMIT 1000", $key));
        } while ($deleted > 0);
    }

    // Clear scheduled cron hooks
    wp_clear_scheduled_hook('imgboost_process_queue');
    wp_clear_scheduled_hook('imgboost_daily_cleanup');
}

if (is_multisite()) {
    if (!function_exists('wp_is_large_network') || !wp_is_large_network()) {
        $imgboost_sites = get_sites();
        foreach ($imgboost_sites as $imgboost_site) {
            switch_to_blog($imgboost_site->blog_id);
            imgboost_cleanup_site();
            restore_current_blog();
        }
    }
} else {
    imgboost_cleanup_site();
}

// Delete the backup directory
// Since the user explicitly opted to "remove data on uninstall", everything must go.
$imgboost_upload_dir = wp_get_upload_dir();
$imgboost_backup_dir = wp_normalize_path(trailingslashit($imgboost_upload_dir['basedir']) . 'imgboost-backups/');
if (file_exists($imgboost_backup_dir)) {
    require_once ABSPATH . 'wp-admin/includes/file.php';
    WP_Filesystem();
    global $wp_filesystem;
    if ($wp_filesystem) {
        $wp_filesystem->delete($imgboost_backup_dir, true, 'd');
    }
}
