<?php
/**
 * Shared uninstall cleanup function.
 *
 * Called from uninstall.php (free build) and from the Freemius
 * 'after_uninstall' action (pro build). Both trigger the same
 * cleanup, gated by the "Delete data on uninstall" setting so
 * users who plan to re-install or upgrade don't lose their data.
 *
 * @package SkyEmagSync
 */

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

if ( ! function_exists( 'skyemag_uninstall_cleanup' ) ) {

	/**
	 * Remove all plugin data from the database.
	 * No-op unless the user has opted in via Settings → Data Management.
	 */
	function skyemag_uninstall_cleanup() {
		// Respect user choice. Default: keep data (safer for Free→Pro upgrades).
		if ( 'yes' !== get_option( 'skyemag_delete_on_uninstall' ) ) {
			return;
		}

		// ── Delete all plugin options ─────────────────────────────────────
		$skyemag_options = [
			'skyemag_api_credentials',
			'skyemag_master_enabled',
			'skyemag_global_margin',
			'skyemag_global_min_margin',
			'skyemag_global_max_margin',
			'skyemag_global_stock_percent',
			'skyemag_min_wc_stock',
			'skyemag_rounding_rule',
			'skyemag_sync_schedule',
			'skyemag_vat_cache',
			'skyemag_db_version',
			'skyemag_bootstrap_done',
			'skyemag_publish_warranty',
			'skyemag_publish_resupply_days',
			'skyemag_publish_live',
			'skyemag_brand_sources',
			'skyemag_ean_sources',
			'skyemag_log_retention_days',
			'skyemag_delete_on_uninstall',
			'skyemag_auto_sanitize_chars',
			'skyemag_notif_email_enabled',
			'skyemag_notif_email_address',
			'skyemag_notif_event_sync_errors',
			'skyemag_notif_event_product_blocked',
			'skyemag_notif_event_competitor_alert',
			'skyemag_notif_event_bb_drop',
			'skyemag_notif_competitor_threshold',
			'skyemag_sync_min_price_ex_vat',
			'skyemag_sync_max_weight_kg',
			'skyemag_sync_skip_sku_pattern',
			'skyemag_sync_skip_zero_stock',
			'skyemag_use_regular_price',
			'skyemag_min_image_pixels',
			'skyemag_order_import_enabled',
			'skyemag_order_fetch_frequency',
			'skyemag_order_auto_decrement_stock',
			'skyemag_order_import_customer_as_user',
			'skyemag_order_notify_admin',
			'skyemag_order_status_mapping',
			'skyemag_order_historical_days',
			'skyemag_orders_callback_key',
			'skyemag_order_dry_run',
			'skyemag_awb_default_print_format',
			'skyemag_awb_sender_name',
			'skyemag_awb_sender_contact',
			'skyemag_awb_sender_phone',
			'skyemag_courier_accounts_cache',
			'skyemag_addresses_cache',
			'skyemag_setup_step',
			'skyemag_setup_completed',
			'skyemag_setup_skipped',
		];
		foreach ( $skyemag_options as $skyemag_opt ) {
			delete_option( $skyemag_opt );
		}

		// ── Delete all post meta added by this plugin ─────────────────────
		$skyemag_meta_keys = [
			'_skyemag_sync_enabled',
			'_skyemag_margin_percent',
			'_skyemag_min_margin_percent',
			'_skyemag_max_margin_percent',
			'_skyemag_stock_percent',
			'_skyemag_last_sync_at',
			'_skyemag_last_error',
			'_skyemag_vendor_ext_id',
			'_skyemag_vat_id',
			'_skyemag_min_price',
			'_skyemag_max_price',
			'_skyemag_handling_time',
			'_skyemag_emag_status',
			'_skyemag_emag_identifier',
			'_skyemag_publish_status',
			'_skyemag_publish_sent_at',
			'_skyemag_publish_error',
			'_skyemag_publish_dry_run',
			'_skyemag_buy_button_rank',
			'_skyemag_num_offers',
			'_skyemag_best_offer_price',
			'_skyemag_bb_updated_at',
			'_skyemag_validation_status',
			'_skyemag_validation_description',
			'_skyemag_validation_errors',
			'_skyemag_offer_validation',
			'_skyemag_last_sync',
			'_skyemag_sync_status',
			'_skyemag_sync_error',
			'_skyemag_notif_competitor_alerted',
			'_skyemag_emag_order_id',
			'_skyemag_emag_status',
			'_skyemag_imported_at',
			'_skyemag_emag_payload',
			'_skyemag_stock_decremented',
			'_skyemag_cancel_noted',
			'_skyemag_awb_emag_id',
			'_skyemag_awb_courier_name',
			'_skyemag_awb_issued_at',
		];

		global $wpdb;
		foreach ( $skyemag_meta_keys as $skyemag_key ) {
			$wpdb->delete( $wpdb->postmeta, [ 'meta_key' => $skyemag_key ], [ '%s' ] ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
		}

		// ── Drop custom tables ───────────────────────────────────────────
		$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}skyemag_logs`" );
		$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}skyemag_categories`" );
		$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}skyemag_category_map`" );
		$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}skyemag_characteristic_map`" );
		$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}skyemag_family_map`" );
		$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}skyemag_margin_history`" );

		// ── Clear scheduled cron events ───────────────────────────────────
		wp_clear_scheduled_hook( 'skyemag_sync_cron' );
		wp_clear_scheduled_hook( 'skyemag_cron_sync' );
		wp_clear_scheduled_hook( 'skyemag_sync_single' );
		wp_clear_scheduled_hook( 'skyemag_buy_button_track' );
		wp_clear_scheduled_hook( 'skyemag_log_prune' );

		$timestamp = wp_next_scheduled( 'skyemag_awb_cache_refresh' );
		if ( $timestamp ) {
			wp_unschedule_event( $timestamp, 'skyemag_awb_cache_refresh' );
		}
		wp_clear_scheduled_hook( 'skyemag_awb_cache_refresh' );

		// ── Clear transients ─────────────────────────────────────────────
		delete_transient( 'skyemag_sync_lock' );
		delete_transient( 'skyemag_cat_import_progress' );
		delete_transient( 'skyemag_cat_import_lock' );
		delete_transient( 'skyemag_bs_import_progress' );
		delete_transient( 'skyemag_bs_import_lock' );
		delete_transient( 'skyemag_server_ip' );
		delete_transient( 'skyemag_schedule_coerced_notice' );
		delete_transient( 'skyemag_setup_redirect' );
		delete_transient( 'skyemag_setup_validation_error' );

		// Notification throttles (event-only + per-product suffix variants).
		$wpdb->query( $wpdb->prepare(
			"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
			$wpdb->esc_like( '_transient_skyemag_notif_throttle_' ) . '%',
			$wpdb->esc_like( '_transient_timeout_skyemag_notif_throttle_' ) . '%'
		) );

		// ── Per-user meta added by the setup wizard (skipped-notice dismiss flag) ──
		delete_metadata( 'user', 0, 'skyemag_setup_notice_dismissed', '', true );
	}
}
