<?php
/**
 * PC Changelog Manager - Uninstall Cleanup
 *
 * Cleans up all plugin data when plugin is deleted.
 *
 * @package PCChangelogManager
 */

// Prevent direct access to file.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

// Check if this is the correct plugin being uninstalled.
if ( false === strpos( WP_UNINSTALL_PLUGIN, 'pc-changelog-manager-abc123' ) ) {
	exit;
}

// Use direct SQL queries for reliable cleanup during uninstall.
global $wpdb;

// Add error logging for debugging.
function pc_clm_log_error( $message ) {
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		error_log( 'PC Changelog Uninstall Error: ' . $message );
	}
}

// Delete post meta for pc_changelog posts.
try {
	$wpdb->query(
		"DELETE FROM {$wpdb->postmeta} WHERE post_id IN (SELECT ID FROM {$wpdb->posts} WHERE post_type = 'pc_changelog')"
	);
} catch ( Exception $e ) {
	pc_clm_log_error( 'Failed to delete post meta: ' . $e->getMessage() );
	// Continue with cleanup despite error
}

// Delete pc_changelog posts.
try {
	$wpdb->query(
		"DELETE FROM {$wpdb->posts} WHERE post_type = 'pc_changelog'"
	);
} catch ( Exception $e ) {
	pc_clm_log_error( 'Failed to delete posts: ' . $e->getMessage() );
	// Continue with cleanup despite error
}

// Delete upvote transients (use wildcard for better cleanup).
try {
	$wpdb->query(
		"DELETE FROM {$wpdb->options} WHERE option_name LIKE 'transient_timeout_pc_clm_%' OR option_name LIKE '_transient_timeout_pc_clm_%'"
	);
} catch ( Exception $e ) {
	pc_clm_log_error( 'Failed to delete transients: ' . $e->getMessage() );
	// Continue with cleanup despite error
}

// Delete vote tracking transients.
try {
	$wpdb->query(
		"DELETE FROM {$wpdb->options} WHERE option_name LIKE 'pc_clm_voted_%'"
	);
} catch ( Exception $e ) {
	pc_clm_log_error( 'Failed to delete vote tracking: ' . $e->getMessage() );
	// Continue with cleanup despite error
}

// Delete all transients with our prefix.
try {
	$wpdb->query(
		"DELETE FROM {$wpdb->options} WHERE option_name LIKE 'pc_clm_%'"
	);
} catch ( Exception $e ) {
	pc_clm_log_error( 'Failed to delete all transients: ' . $e->getMessage() );
	// Continue with cleanup despite error
}

// Delete our plugin options.
try {
	delete_option( 'pc_clm_rewrite_rules_flushed' );
} catch ( Exception $e ) {
	pc_clm_log_error( 'Failed to delete plugin options: ' . $e->getMessage() );
	// Continue with cleanup despite error
}

// Clear any remaining plugin cache.
if ( function_exists( 'wp_cache_flush' ) ) {
	wp_cache_flush();
}