<?php
/**
 * CargoHub Uninstall Script
 * 
 * This file is executed when the plugin is deleted via WordPress admin.
 * It cleans up all plugin data from the database.
 * 
 * @package CargoHubFree
 * @author RomiTeT Creative
 * @copyright 2025 RomiTeT Creative
 * @license GPL-2.0-or-later
 */

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

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Clean up plugin data on uninstall
 */
function cargohub_free_uninstall_cleanup() {
    global $wpdb;
    
    // Only proceed if user has proper capabilities
    if (!current_user_can('activate_plugins')) {
        return;
    }
    
    // Uninstall process started
    
    try {
        // 1. Drop plugin database table
        $table_name = $wpdb->prefix . 'cargohub_free_tracking';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Controlled uninstall-time schema change
        $wpdb->query("DROP TABLE IF EXISTS {$table_name}");
        
        // 2. Delete plugin options
        $options_to_delete = array(
            'cargohub_free_custom_carriers',
            'cargohub_free_activation_date',
            'cargohub_free_notice_dismissed',
            'cargohub_free_version',
            'cargohub_free_db_version',
            'cargohub_free_settings',
            'cargohub_free_email_settings',
            'cargohub_free_sms_settings'
        );
        
        foreach ($options_to_delete as $option) {
            delete_option($option);
        }
        
        // 3. Delete plugin transients
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query(
            "DELETE FROM {$wpdb->options} 
             WHERE option_name LIKE '_transient_cargohub_free_%' 
             OR option_name LIKE '_transient_timeout_cargohub_free_%'"
        );
        
        // 4. Delete plugin user meta data
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query(
            "DELETE FROM {$wpdb->usermeta} 
             WHERE meta_key LIKE 'cargohub_free_%'"
        );
        
        // 5. Delete plugin post meta data (if any)
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query(
            "DELETE FROM {$wpdb->postmeta} 
             WHERE meta_key LIKE 'cargohub_free_%'"
        );
        
        // 6. Clear scheduled hooks
        wp_clear_scheduled_hook('cargohub_free_cleanup');
        
        // 7. Delete uploaded files (logos)
        $upload_dir = wp_upload_dir();
        $plugin_upload_dirs = array(
            $upload_dir['basedir'] . '/cargohub-free-logos',
            $upload_dir['basedir'] . '/cargohub-free-logs'
        );
        
        foreach ($plugin_upload_dirs as $dir) {
            if (is_dir($dir)) {
                cargohub_free_delete_directory($dir);
            }
        }
        
        // 8. Clear any cached data
        if (function_exists('wp_cache_flush')) {
            wp_cache_flush();
        }
        
        // Force garbage collection
        if (function_exists('gc_collect_cycles')) {
            gc_collect_cycles();
        }
        
        // Uninstall cleanup completed
        
    } catch (Exception $e) {
        // Swallow uninstall exceptions silently to avoid fatal in removal
    }
}

/**
 * Recursively delete a directory and its contents
 * 
 * @param string $dir Directory path to delete
 * @return bool True on success, false on failure
 */
function cargohub_free_delete_directory($dir) {
    require_once ABSPATH . 'wp-admin/includes/file.php';
    global $wp_filesystem;
    if (empty($wp_filesystem)) {
        WP_Filesystem();
    }
    if (!$wp_filesystem) {
        return false;
    }
    if (!$wp_filesystem->is_dir($dir)) {
        return false;
    }
    // Recursively delete directory using WP_Filesystem API
    return (bool) $wp_filesystem->delete($dir, true);
}

/**
 * Ask user for confirmation before data deletion (optional)
 * This is handled by WordPress core, but we can add custom logic if needed
 */
function cargohub_free_uninstall_confirmation() {
    // WordPress already handles the confirmation dialog
    // This function can be used for additional custom confirmation logic if needed
    return true;
}

// Execute the cleanup
if (cargohub_free_uninstall_confirmation()) {
    cargohub_free_uninstall_cleanup();
}
