<?php
/**
 * ==========================
 * 🔐 IGNY8 FILE RULE HEADER
 * ==========================
 * @file         : uninstall.php
 * @location     : /uninstall.php
 * @type         : Function Library
 * @scope        : Global
 * @allowed      : Plugin uninstallation, database cleanup, data removal
 * @reusability  : Single Use
 * @notes        : Plugin uninstallation and cleanup procedures
 */

// Prevent direct access - only allow WordPress uninstall
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

/**
 * Uninstall Igny8 Compact Plugin
 * 
 * Removes all plugin data including database tables, options,
 * user meta, and any other data created by the plugin.
 */
function igny8_uninstall() {
    global $wpdb;
    
    // Log uninstallation start
    error_log('Igny8 Compact Plugin: Starting uninstallation...');
    
    // Remove database tables
    igny8_remove_database_tables();
    
    // Remove plugin options
    igny8_remove_plugin_options();
    
    // Remove user meta data
    igny8_remove_user_meta();
    
    // Remove taxonomies and terms
    igny8_remove_taxonomies();
    
    // Remove post meta data
    igny8_remove_post_meta();
    
    // Clear any cached data
    igny8_clear_cache();
    
    // Log successful uninstallation
    error_log('Igny8 Compact Plugin: Uninstallation completed successfully');
}

/**
 * Remove all plugin database tables
 */
function igny8_remove_database_tables() {
    global $wpdb;
    
    // List of all plugin tables
    $tables = [
        'igny8_keywords',
        'igny8_tasks',
        'igny8_variations',
        'igny8_rankings',
        'igny8_suggestions',
        'igny8_campaigns',
        'igny8_content_ideas',
        'igny8_clusters',
        'igny8_sites',
        'igny8_backlinks',
        'igny8_mapping',
        'igny8_prompts',
        'igny8_detected_fields',
        'igny8_logs'
    ];
    
    // Drop each table
    foreach ($tables as $table) {
        $table_name = $wpdb->prefix . $table;
        $wpdb->query("DROP TABLE IF EXISTS $table_name");
        error_log("Igny8 Compact: Dropped table $table_name");
    }
}

/**
 * Remove all plugin options
 */
function igny8_remove_plugin_options() {
    // List of plugin options
    $options = [
        'igny8_version',
        'igny8_installed',
        'igny8_activated',
        'igny8_status',
        'igny8_settings',
        'igny8_last_update',
        'igny8_notifications',
        'igny8_cache_version',
        'igny8_license_key',
        'igny8_license_status'
    ];
    
    // Remove each option
    foreach ($options as $option) {
        delete_option($option);
        error_log("Igny8 Compact: Removed option $option");
    }
    
    // Remove any transients
    delete_transient('igny8_cache_data');
    delete_transient('igny8_api_data');
    delete_transient('igny8_stats_cache');
}

/**
 * Remove user meta data related to the plugin
 */
function igny8_remove_user_meta() {
    global $wpdb;
    
    // Remove user meta keys that start with igny8_
    $wpdb->query(
        "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE 'igny8_%'"
    );
    
    error_log('Igny8 Compact: Removed user meta data');
}

/**
 * Remove custom taxonomies and their terms
 */
function igny8_remove_taxonomies() {
    // Get all terms for our custom taxonomies
    $taxonomies = ['sectors', 'clusters'];
    
    foreach ($taxonomies as $taxonomy) {
        // Get all terms
        $terms = get_terms([
            'taxonomy' => $taxonomy,
            'hide_empty' => false
        ]);
        
        // Delete each term
        foreach ($terms as $term) {
            wp_delete_term($term->term_id, $taxonomy);
        }
        
        // Unregister taxonomy
        unregister_taxonomy($taxonomy);
        
        error_log("Igny8 Compact: Removed taxonomy $taxonomy");
    }
}

/**
 * Remove post meta data related to the plugin
 */
function igny8_remove_post_meta() {
    global $wpdb;
    
    // List of post meta keys to remove
    $meta_keys = [
        '_igny8_cluster_id',
        '_igny8_keyword_ids',
        '_igny8_task_id',
        '_igny8_campaign_ids',
        '_igny8_backlink_count',
        '_igny8_last_optimized',
        '_igny8_seo_score',
        '_igny8_optimization_status',
        '_igny8_content_score',
        '_igny8_readability_score'
    ];
    
    // Remove each meta key
    foreach ($meta_keys as $meta_key) {
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->postmeta} WHERE meta_key = %s",
                $meta_key
            )
        );
    }
    
    error_log('Igny8 Compact: Removed post meta data');
}

/**
 * Clear any cached data
 */
function igny8_clear_cache() {
    // Clear WordPress object cache
    wp_cache_flush();
    
    // Clear any plugin-specific cache
    if (function_exists('wp_cache_delete_group')) {
        wp_cache_delete_group('igny8');
    }
    
    // Clear rewrite rules
    flush_rewrite_rules();
    
    error_log('Igny8 Compact: Cleared cache and rewrite rules');
}

// Run the uninstallation
igny8_uninstall();
