<?php
/**
 * Uninstall cleanup, routed through Freemius's after_uninstall hook.
 *
 * WordPress's native uninstall.php mechanism (a file at the plugin's
 * root, auto-run by WP_UNINSTALL_PLUGIN) is deliberately NOT used —
 * Freemius flagged it during their pre-listing review: keeping a
 * parallel uninstall.php bypasses their own uninstall flow (license
 * deactivation sync, usage-tracking stop, their own uninstall feedback
 * screen), which runs first.
 *
 * Freemius's SDK registers WordPress's real uninstall hook internally
 * (register_uninstall_hook(), on every deactivation — see
 * class-freemius.php) and relays it via $fs->do_action('after_uninstall')
 * once that fires. Confirmed in the SDK source (not assumed): that
 * relay call sits outside the block gated on the site having opted in
 * to Freemius tracking, so this fires on uninstall regardless of
 * whether the site clicked "Allow & Continue" or "Skip" on the opt-in
 * screen — the exact same reach the old uninstall.php had.
 *
 * @package Briefify
 */

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

if ( function_exists( 'nrbb_fs' ) ) {
	nrbb_fs()->add_action( 'after_uninstall', 'nrbb_cleanup_on_uninstall' );
}

/**
 * Remove all NR Brief Builder data — options and every submission post
 * + its meta — across all sites on a multisite network. Same logic
 * uninstall.php used to run natively, moved here verbatim.
 */
function nrbb_cleanup_on_uninstall() {
	if ( is_multisite() ) {
		$nrbb_sites = get_sites( array( 'fields' => 'ids' ) );

		foreach ( $nrbb_sites as $nrbb_site_id ) {
			switch_to_blog( $nrbb_site_id );
			nrbb_cleanup_on_uninstall_single_site();
			restore_current_blog();
		}
	} else {
		nrbb_cleanup_on_uninstall_single_site();
	}
}

/**
 * Remove NR Brief Builder data on the current site only.
 */
function nrbb_cleanup_on_uninstall_single_site() {
	delete_option( 'briefify_settings' );
	delete_option( 'briefify_test_email_sent' );

	$submissions = get_posts(
		array(
			'post_type'   => 'briefify_submission',
			'post_status' => 'any',
			'numberposts' => -1,
			'fields'      => 'ids',
		)
	);

	foreach ( $submissions as $post_id ) {
		wp_delete_post( $post_id, true );
	}
}
