<?php
/**
 * HJCyberX Checkout for Paddle Lite Uninstall
 *
 * Fired when the Lite plugin is deleted.
 * Only cleans up Lite-specific options and meta.
 * Does NOT touch Pro data so upgrades are seamless.
 *
 * @package PaddleKonnect_Lite
 */

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

// ──────────────────────────────────────────────.
// Only clean up if the Pro version is NOT active.
// This prevents data loss when user upgrades from Lite → Pro.
// ──────────────────────────────────────────────.

// Check if Pro version is active — if yes, skip cleanup entirely.
$paddlekonnect_lite_active_plugins = get_option( 'active_plugins', array() );
$paddlekonnect_lite_pro_active     = false;
foreach ( $paddlekonnect_lite_active_plugins as $paddlekonnect_lite_plugin ) {
	if ( strpos( $paddlekonnect_lite_plugin, 'hjcyberx-checkout-for-paddle-pro.php' ) !== false && strpos( $paddlekonnect_lite_plugin, 'lite' ) === false ) {
		$paddlekonnect_lite_pro_active = true;
		break;
	}
}

if ( $paddlekonnect_lite_pro_active ) {
	// Pro is active, don't delete shared data.
	// Only delete Lite-specific gateway settings.
	delete_option( 'woocommerce_paddlekonnect-lite_settings' );
	return;
}

// ──────────────────────────────────────────────.
// Pro is NOT active — safe to clean everything.
// ──────────────────────────────────────────────.

// 1. Delete Lite Gateway Settings.
delete_option( 'woocommerce_paddlekonnect-lite_settings' );

// 2. Delete the "dismiss notice" flags.
delete_metadata( 'user', 0, 'paddlekonnect_lite_marketing_dismissed', '', true );

// 3. Remove Custom Post Meta (Products).
global $wpdb;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching

$wpdb->query( "DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ('_paddlekonnect_price_id', '_paddlekonnect_sandbox_price_id')" );

// 4. Clean up Order Meta related to Paddle.
$wpdb->query( "DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ('_paddlekonnect_pending', '_paddlekonnect_transaction_id', '_paddlekonnect_processed_events')" );

// 5. HPOS cleanup.
if ( class_exists( '\Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore' ) ) {
	$paddlekonnect_lite_orders_meta_table = $wpdb->prefix . 'wc_orders_meta';
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $paddlekonnect_lite_orders_meta_table ) ) ) === $paddlekonnect_lite_orders_meta_table ) {
		$wpdb->query( "DELETE FROM {$wpdb->prefix}wc_orders_meta WHERE meta_key IN ('_paddlekonnect_pending', '_paddlekonnect_transaction_id', '_paddlekonnect_processed_events')" );
	}
}

// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:enable WordPress.DB.DirectDatabaseQuery.NoCaching
