<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.WP.EnqueuedResourceParameters
// phpcs:disable WordPress.PHP.DevelopmentFunctions
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum

/**
 * GT BOGO ENGINE – Hard Uninstall Cleanup
 *
 * Removes all plugin options, transients, and cached data
 * when the plugin is uninstalled via WordPress.
 *
 * WordPress.org–compliant uninstall handler.
 */

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

global $wpdb;

/**
 * ---------------------------------------------------------
 * DATA PRESERVATION GUARD (default: KEEP all data)
 * ---------------------------------------------------------
 * Only wipe plugin data if the store owner explicitly opted in
 * via Settings -> "Remove all data on uninstall" (gtbogo_uninstall_data).
 * Default is OFF: a customer who uninstalls and reinstalls keeps every
 * rule, setting, superpower toggle, license status, and customer loyalty
 * tier intact. This matches the documented behaviour.
 *
 * IMPORTANT: read this flag BEFORE any deletion runs, because the flag
 * itself matches the gtbogo_% delete pattern below.
 */
$gtbogo_should_delete = (bool) get_option( 'gtbogo_uninstall_data', false );

// Multisite: also honour a network-level opt-in if present.
if ( ! $gtbogo_should_delete && is_multisite() && function_exists( 'get_site_option' ) ) {
    $gtbogo_should_delete = (bool) get_site_option( 'gtbogo_uninstall_data', false );
}

if ( ! $gtbogo_should_delete ) {
    // Store owner has NOT opted into data removal. Preserve everything.
    return;
}


/**
 * ---------------------------------------------------------
 * Helper: delete options by LIKE pattern
 * ---------------------------------------------------------
 */
function gtbogo_delete_options_like( $table, $pattern ) {
    global $wpdb;
    $table_name = esc_sql( $table );
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared
    $wpdb->query( $wpdb->prepare( "DELETE FROM `{$table_name}` WHERE option_name LIKE %s", $pattern ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
}

/**
 * ---------------------------------------------------------
 * Single-site cleanup
 * ---------------------------------------------------------
 */
gtbogo_delete_options_like( $wpdb->options, 'gt_bogo_%' );
gtbogo_delete_options_like( $wpdb->options, 'gt_bogo_engine_%' );
gtbogo_delete_options_like( $wpdb->options, 'gtbogo_%' );

gtbogo_delete_options_like( $wpdb->options, '_transient_gt_bogo_%' );
gtbogo_delete_options_like( $wpdb->options, '_transient_timeout_gt_bogo_%' );

gtbogo_delete_options_like( $wpdb->options, '_site_transient_gt_bogo_%' );
gtbogo_delete_options_like( $wpdb->options, '_site_transient_timeout_gt_bogo_%' );

$wpdb->delete( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
    $wpdb->options,
    [ 'option_name' => 'gt_bogo_engine_installed_version' ],
    [ '%s' ]
);

/**
 * ---------------------------------------------------------
 * Multisite cleanup
 * ---------------------------------------------------------
 */
if ( is_multisite() && isset( $wpdb->sitemeta ) ) {

    $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
        $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
            "DELETE FROM {$wpdb->sitemeta} WHERE meta_key LIKE %s",
            'gt_bogo_%'
        )
    );

    $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
        $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
            "DELETE FROM {$wpdb->sitemeta} WHERE meta_key LIKE %s",
            'gt_bogo_engine_%'
        )
    );

    $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
        $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
            "DELETE FROM {$wpdb->sitemeta} WHERE meta_key LIKE %s",
            '_site_transient_gt_bogo_%'
        )
    );

    $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
        $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
            "DELETE FROM {$wpdb->sitemeta} WHERE meta_key LIKE %s",
            '_site_transient_timeout_gt_bogo_%'
        )
    );
}


/**
 * ---------------------------------------------------------
 * Drop all plugin database tables
 * ---------------------------------------------------------
 */
$gtbogo_tables = $wpdb->get_col(
	$wpdb->prepare(
		"SHOW TABLES LIKE %s",
		$wpdb->esc_like( $wpdb->prefix . 'gtbogo_' ) . '%'
	)
);
foreach ( $gtbogo_tables as $gtbogo_table ) {
	$safe_table = esc_sql( $gtbogo_table );
	$wpdb->query( "DROP TABLE IF EXISTS `{$safe_table}`" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
}

/**
 * ---------------------------------------------------------
 * Clean user meta
 * ---------------------------------------------------------
 */
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->prepare(
		"DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s",
		$wpdb->esc_like( '_gtbogo_' ) . '%'
	)
);
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->prepare(
		"DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s",
		$wpdb->esc_like( 'gtbogo_' ) . '%'
	)
);

/**
 * ---------------------------------------------------------
 * Clean order/post meta (BOGO-specific keys only)
 * ---------------------------------------------------------
 */
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->prepare(
		"DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s",
		$wpdb->esc_like( '_gtbogo_' ) . '%'
	)
);

/**
 * ---------------------------------------------------------
 * Clean WooCommerce order item meta
 * ---------------------------------------------------------
 */
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'woocommerce_order_itemmeta' ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
	$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->prepare(
			"DELETE FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE meta_key LIKE %s",
			$wpdb->esc_like( '_gtbogo_' ) . '%'
		)
	);
}

/**
 * ---------------------------------------------------------
 * Clear all plugin cron hooks
 * ---------------------------------------------------------
 */
$crons = _get_cron_array();
if ( is_array( $crons ) ) {
	foreach ( $crons as $timestamp => $cron_hooks ) {
		foreach ( $cron_hooks as $hook => $events ) {
			if ( strpos( $hook, 'gtbogo_' ) === 0 || strpos( $hook, 'gt_bogo_' ) === 0 ) {
				wp_clear_scheduled_hook( $hook );
			}
		}
	}
}

/**
 * ---------------------------------------------------------
 * Flush WordPress caches
 * ---------------------------------------------------------
 */
if ( function_exists( 'wp_cache_flush' ) ) {
    wp_cache_flush();
}

if ( function_exists( 'flush_rewrite_rules' ) ) {
    flush_rewrite_rules();
}

/**
 * ---------------------------------------------------------
 * Flush common caching plugins (safe, conditional)
 * ---------------------------------------------------------
 */
if ( function_exists( 'rocket_clean_domain' ) ) {
    rocket_clean_domain();
}

if ( function_exists( 'w3tc_flush_all' ) ) {
    w3tc_flush_all();
}

if ( function_exists( 'wp_cache_clear_cache' ) ) {
    wp_cache_clear_cache(); // WP Super Cache
}

if ( class_exists( 'LiteSpeed\Purge' ) ) {
    try {
        \LiteSpeed\Purge::purge_all();
    } catch ( \Throwable $e ) {}
}

if ( function_exists( 'sg_cachepress_purge_cache' ) ) {
    sg_cachepress_purge_cache();
}

if ( function_exists( 'cache_enabler_clear_total_cache' ) ) {
    cache_enabler_clear_total_cache();
}

/**
 * ---------------------------------------------------------
 * Opcache reset (if available)
 * ---------------------------------------------------------
 */
if ( function_exists( 'opcache_reset' ) ) {
    opcache_reset();
}

