<?php

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

/**
 * Clean up plugin data on uninstall.
 */
function devikit_sellsy_uninstall() {
	$settings  = get_option( 'devikit_sellsy_settings', [] );
	$keep_data = is_array( $settings )
		&& isset( $settings['keep_data_on_uninstall'] )
		&& $settings['keep_data_on_uninstall'] === 'yes';

	if ( ! $keep_data ) {
		delete_option( 'devikit_sellsy_settings' );
		delete_option( 'devikit_sellsy_oauth_tokens' );

		global $wpdb;

		$meta_keys = [
			'_sellsy_customer_id',
			'_sellsy_related_id',
			'_sellsy_related_type',
			'_sellsy_contact_id',
			'_sellsy_invoice_id',
			'_sellsy_invoice_number',
			'_sellsy_invoice_status',
			'_sellsy_last_error',
			'_sellsy_invoice_total_mismatch',
			'_sellsy_invoice_order_total',
			'_sellsy_invoice_sellsy_total',
			'_sellsy_invoice_total_difference',
			'_sellsy_invoice_booked',
			'_sellsy_credit_note_id',
			'_sellsy_credit_note_number',
			'_sellsy_credit_note_status',
		];

		foreach ( $meta_keys as $meta_key ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key
			$wpdb->delete( $wpdb->postmeta, [ 'meta_key' => $meta_key ] );
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key
			$wpdb->delete( $wpdb->prefix . 'wc_orders_meta', [ 'meta_key' => $meta_key ] );
		}
	}

	global $wpdb;

	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
			$wpdb->esc_like( '_transient_devikit_sellsy_' ) . '%',
			$wpdb->esc_like( '_transient_timeout_devikit_sellsy_' ) . '%'
		)
	);
}

devikit_sellsy_uninstall();
