<?php
/**
 * Plugin data cleanup on uninstall (Freemius after_uninstall).
 *
 * @package WPDudeProducts
 */

declare(strict_types=1);

namespace WPDude\Products\Uninstall;

use WPDude\Products\Orders\Post_Type as Order_Post_Type;
use WPDude\Products\Products\Post_Type as Product_Post_Type;

/**
 * Deletes plugin data when the merchant opted in via settings.
 */
final class Cleanup {

	/**
	 * Run uninstall cleanup if enabled in settings.
	 */
	public static function run(): void {
		$delete_data = get_option( 'wpdude_dc_delete_data_on_uninstall', 'no' );
		if ( 'yes' !== $delete_data ) {
			return;
		}

		global $wpdb;

		$tables = array(
			$wpdb->prefix . 'wpdude_dc_stripe_events',
			$wpdb->prefix . 'wpdude_dc_order_tokens',
			$wpdb->prefix . 'wpdude_dc_webhook_deliveries',
		);

		foreach ( $tables as $table ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- uninstall drops known prefixed tables only.
			$wpdb->query( "DROP TABLE IF EXISTS {$table}" );
		}

		$product_ids = get_posts(
			array(
				'post_type'      => Product_Post_Type::POST_TYPE,
				'post_status'    => 'any',
				'posts_per_page' => -1,
				'fields'         => 'ids',
			)
		);
		foreach ( $product_ids as $product_id ) {
			wp_delete_post( (int) $product_id, true );
		}

		$order_ids = get_posts(
			array(
				'post_type'      => Order_Post_Type::POST_TYPE,
				'post_status'    => 'any',
				'posts_per_page' => -1,
				'fields'         => 'ids',
			)
		);
		foreach ( $order_ids as $order_id ) {
			wp_delete_post( (int) $order_id, true );
		}

		$options = array(
			'wpdude_dc_db_version',
			'wpdude_dc_settings',
			'wpdude_dc_secrets',
			'wpdude_dc_delete_data_on_uninstall',
		);

		foreach ( $options as $option ) {
			delete_option( $option );
		}

		wp_clear_scheduled_hook( 'wpdude_dc_process_outgoing_webhooks' );
	}
}
