<?php
/**
 * Uninstall handler.
 *
 * Runs when the plugin is DELETED via Plugins → Delete.
 * NOT called on deactivation — deactivation never destroys data.
 *
 * @package Kramar
 * @since   1.0.0
 */

// Exit if not called by WordPress during uninstall.
defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

/**
 * Tear down a single site.
 */
$kramar_uninstall_site = static function (): void {
	$kramar_data = get_option( 'kramar_settings' );
	$kramar_full = is_array( $kramar_data ) && ! empty( $kramar_data['_full_cleanup'] );

	if ( $kramar_full ) {
		delete_option( 'kramar_settings' );
		delete_option( 'kramar_custom_order_statuses' );
		delete_option( 'kramar_next_order_number' );
		delete_option( 'kramar_checkout_fields_billing' );
		delete_option( 'kramar_checkout_fields_shipping' );
		delete_option( 'kramar_checkout_fields_additional' );
		delete_option( 'kramar_invoice_template' );
		delete_option( 'kramar_invoice_key' );
		delete_option( 'kramar_custom_emails' );
		delete_option( 'kramar_email_overrides' );
		delete_option( 'kramar_email_settings' );
		delete_option( 'kramar_business_details' );
		delete_option( 'kramar_gmc_rewrite_version' );
		// Written by real code paths but previously left behind, so a site that
		// opted into full cleanup still kept Kramar rows in wp_options.
		delete_option( 'kramar_google_feed_stats' );
		delete_option( 'kramar_logo_migrated' );
		delete_option( 'kramar_setup_dismissed' );
		delete_option( 'kramar_toko_emails_cleaned' );
		delete_option( 'kramar_tracking_page_id' );
		delete_option( 'kramar_tracking_page_lock' );
		delete_option( 'kramar_withdrawal_page_id' );
		delete_option( 'kramar_withdrawal_page_lock' );

		// Scheduled work outlives the plugin otherwise: WP-Cron rows sit in
		// wp_options and Action Scheduler rows in its own tables, firing hooks
		// that no longer exist.
		foreach ( [
			'kramar_omnibus_check',
			'kramar_cleanup_sessions',
			'kramar_cleanup_analytics',
			'kramar_cleanup_geolocation',
			'kramar_acr_abandon_check',
			'kramar_acr_send_email',
			'kramar_acr_retention',
			'kramar_bis_notify_batch',
			'kramar_bis_discontinued_batch',
			'kramar_bis_retention',
			'kramar_send_review_reminder',
			'kramar_send_custom_email',
			'kramar_google_feed_generate',
		] as $kramar_hook ) {
			wp_clear_scheduled_hook( $kramar_hook );
			if ( function_exists( 'as_unschedule_all_actions' ) ) {
				as_unschedule_all_actions( $kramar_hook );
			}
		}

		if ( function_exists( 'as_unschedule_all_actions' ) ) {
			// Everything this plugin queued, by group.
			as_unschedule_all_actions( '', [], 'kramar' );
		}

		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}kramar_invoice_numbers" );
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}kramar_omnibus_log" );
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}kramar_abandoned_carts" );
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}kramar_stock_subscribers" );

		$upload_dir = wp_get_upload_dir();
		$invoice_dir = trailingslashit( $upload_dir['basedir'] ) . 'kramar-invoices/';
		if ( is_dir( $invoice_dir ) ) {
			$files = new RecursiveIteratorIterator(
				new RecursiveDirectoryIterator( $invoice_dir, FilesystemIterator::SKIP_DOTS ),
				RecursiveIteratorIterator::CHILD_FIRST
			);
			foreach ( $files as $file ) {
				if ( $file->isDir() ) {
					// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- uninstall context; WP_Filesystem unavailable before WP fully loads
					rmdir( $file->getRealPath() );
				} else {
					// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- uninstall context; WP_Filesystem unavailable before WP fully loads
					unlink( $file->getRealPath() );
				}
			}
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- uninstall context; WP_Filesystem unavailable before WP fully loads
			rmdir( $invoice_dir );
		}
	}
};

if ( is_multisite() ) {
	$kramar_site_ids = get_sites( [ 'fields' => 'ids', 'number' => 0 ] );
	foreach ( $kramar_site_ids as $kramar_site_id ) {
		switch_to_blog( (int) $kramar_site_id );
		$kramar_uninstall_site();
		restore_current_blog();
	}
} else {
	$kramar_uninstall_site();
}
