<?php
/**
 * Plugin uninstall cleanup.
 *
 * @package Australcode\Rewards
 */

declare(strict_types=1);

namespace Australcode\Rewards;

use Australcode\Rewards\Infrastructure\Database\Schema;

defined( 'ABSPATH' ) || exit;

/**
 * Removes the plugin's data when the user uninstalls it from wp-admin.
 *
 * Wired to the Freemius SDK `after_uninstall` hook (registered in the main file),
 * NOT a root `uninstall.php`: with an `uninstall.php` present Freemius cannot
 * track the uninstall event (a WordPress limitation) and rejects the deploy with
 * HTTP 400. Freemius invokes Uninstaller::uninstall() during uninstall.
 *
 * Opt-in deletion: data is wiped only when the "Delete all plugin data on
 * uninstall" setting (acrwd_settings.delete_data_on_uninstall) is enabled. The
 * default (OFF) preserves balances and history so a reinstall keeps the loyalty
 * program intact. Deactivation never deletes data (see Deactivator). License state
 * is owned by Freemius (fs_accounts) — this cleanup never touches it.
 */
final class Uninstaller {

	/**
	 * `after_uninstall` callback for the Freemius SDK.
	 */
	public static function uninstall(): void {
		$settings = get_option( 'acrwd_settings', array() );
		$delete   = is_array( $settings ) && ! empty( $settings['delete_data_on_uninstall'] );

		if ( ! $delete ) {
			return;
		}

		global $wpdb;

		// Custom tables (balances, transactions, tiers, campaigns, referrals,
		// migrations). Schema::all_tables() is the single source of truth.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery
		foreach ( Schema::all_tables() as $table ) {
			$name = Schema::table_name( $table );
			$wpdb->query( "DROP TABLE IF EXISTS {$name}" );
		}
		// phpcs:enable

		// Options.
		delete_option( 'acrwd_settings' );
		delete_option( 'acrwd_installed_version' );
		delete_option( 'acrwd_flush_rewrite' );
		delete_option( 'acrwd_registered_endpoint' );

		// Per-user admin flash notices stored as transients (acrwd_*_notice_*).
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery
		$wpdb->query(
			"DELETE FROM {$wpdb->options}
			 WHERE option_name LIKE '\\_transient\\_acrwd\\_%'
			    OR option_name LIKE '\\_transient\\_timeout\\_acrwd\\_%'"
		);
		// phpcs:enable

		// WP-Cron events scheduled by the plugin (already cleared on deactivation,
		// repeated here for an uninstall that bypasses deactivation).
		wp_clear_scheduled_hook( 'acrwd_expire_points' );
		wp_clear_scheduled_hook( 'acrwd_birthday_tick' );
		wp_clear_scheduled_hook( 'acrwd_points_expiring_tick' );
		wp_clear_scheduled_hook( 'acrwd_redemption_refund_tick' );
	}
}
