<?php
/**
 * Addon Cleanup Helper Functions
 *
 * Provides centralized cleanup functionality for addon deactivation
 *
 * @package ExploreXR_Premium
 */

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Delete all meta keys for a specific addon from all ExploreXR models
 *
 * @param string $addon_prefix The meta key prefix to delete (e.g., '_explorexr_animation_')
 * @return int Number of meta keys deleted
 */
function explorexr_cleanup_addon_meta($addon_prefix) {
    global $wpdb;
    
    // Validate prefix
    if (empty($addon_prefix) || !is_string($addon_prefix)) {
        return 0;
    }
    
    // Get all explorexr_model posts
    $models = get_posts(array(
        'post_type' => 'explorexr_model',
        'post_status' => 'any',
        'posts_per_page' => -1,
        'fields' => 'ids',
    ));
    
    if (empty($models)) {
        return 0;
    }
    
    $deleted_count = 0;
    
    // Delete meta for each model
    foreach ($models as $model_id) {
        // Get all meta keys for this model
        $all_meta = get_post_meta($model_id);
        
        foreach ($all_meta as $meta_key => $meta_value) {
            // Check if meta key starts with addon prefix
            if (strpos($meta_key, $addon_prefix) === 0) {
                delete_post_meta($model_id, $meta_key);
                $deleted_count++;
            }
        }
    }
    
    return $deleted_count;
}

/**
 * Delete specific addon options from WordPress options table
 *
 * @param string $option_prefix The option prefix to delete (e.g., 'explorexr_animation_')
 * @return int Number of options deleted
 */
function explorexr_cleanup_addon_options($option_prefix) {
    global $wpdb;
    
    // Validate prefix
    if (empty($option_prefix) || !is_string($option_prefix)) {
        return 0;
    }
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for bulk deletion with LIKE pattern
    $deleted = $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
            $wpdb->esc_like($option_prefix) . '%'
        )
    );
    
    return $deleted ? (int) $deleted : 0;
}

/**
 * Log addon cleanup for debugging
 *
 * @param string $addon_name Human-readable addon name
 * @param int    $meta_count Number of meta keys deleted
 * @param int    $option_count Number of options deleted
 */
function explorexr_log_addon_cleanup($addon_name, $meta_count, $option_count) {
    if (defined('WP_DEBUG') && WP_DEBUG) {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Intentional debug logging
        error_log(sprintf(
            'ExploreXR: %s addon deactivated. Cleaned up %d meta keys and %d options.',
            $addon_name,
            $meta_count,
            $option_count
        ));
    }
}
