<?php
/**
 * Desinstalación. Solo borra datos si el usuario activó la opción
 * "eliminar todos los datos al desinstalar" (embp_delete_data_on_uninstall).
 *
 * @package EmberPrice
 */

defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

/**
 * Runs the actual uninstall. Wrapped in a prefixed function (rather than
 * top-level script code) so every local variable lives in function scope
 * instead of the global scope that WPCS's PrefixAllGlobals sniff checks.
 */
function embp_run_uninstall(): void {
	if ( ! get_option( 'embp_delete_data_on_uninstall' ) ) {
		return;
	}

	global $wpdb;

	$embp_tables = array(
		"{$wpdb->prefix}embp_suppliers",
		"{$wpdb->prefix}embp_jobs",
		"{$wpdb->prefix}embp_rows",
		"{$wpdb->prefix}embp_aliases",
		"{$wpdb->prefix}embp_snapshots",
	);

	foreach ( $embp_tables as $embp_table ) {
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
		$wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $embp_table ) );
	}

	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$embp_options = $wpdb->get_col(
		$wpdb->prepare(
			"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
			$wpdb->esc_like( 'embp_' ) . '%'
		)
	);

	foreach ( $embp_options as $embp_option_name ) {
		delete_option( $embp_option_name );
	}

	$embp_upload_dir = wp_get_upload_dir();
	$embp_dir        = trailingslashit( $embp_upload_dir['basedir'] ) . 'emberprice';

	if ( ! is_dir( $embp_dir ) ) {
		return;
	}

	if ( ! function_exists( 'WP_Filesystem' ) ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
	}

	WP_Filesystem();

	global $wp_filesystem;

	if ( $wp_filesystem ) {
		$wp_filesystem->delete( $embp_dir, true );
	}
}

embp_run_uninstall();
