<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL -- Uninstall removes a fixed list of plugin-owned tables.

/**
 * Fired when the plugin is uninstalled.
 *
 * This file handles complete cleanup of plugin data based on user settings.
 * It respects the settings configured in the plugin's Settings page:
 * - Delete All Popups (instant_popup_builder_db_active)
 * - Preserve Analytics (instant_popup_builder_preserve_analytics)
 * - Clean Plugin Options (instant_popup_builder_cleanup_options)
 *
 * @link       https://instantpopupbuilder.com
 * @since      1.0.0
 * @package    Instant_Popup_Builder
 */

// If uninstall not called from WordPress, then exit.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

/**
 * Uninstall for single site
 */
function instant_popup_builder_uninstall_site() {
	global $wpdb;

	// Get user settings
	$delete_popups      = get_option( 'instant_popup_builder_db_active', 'no' );
	$preserve_analytics = get_option( 'instant_popup_builder_preserve_analytics', 'yes' );
	$cleanup_options    = get_option( 'instant_popup_builder_cleanup_options', 'no' );

	$prefix = $wpdb->prefix;

	// Array to track what was cleaned up (for debugging)
	$cleanup_log = array();

	// 1. Handle Popup Data Deletion
	if ( 'yes' === $delete_popups ) {
		// Delete main popup table
		$popup_table = $prefix . 'instant_popup_builder';
		$escaped_popup_table = esc_sql( $popup_table );
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange
		$wpdb->query( "DROP TABLE IF EXISTS `{$escaped_popup_table}`" );
		$cleanup_log[] = 'Dropped table: ' . $popup_table;

		// Delete subscription settings table
		$subscription_settings_table = $prefix . 'instant_popup_subscription_settings';
		$escaped_subscription_settings_table = esc_sql( $subscription_settings_table );
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange
		$wpdb->query( "DROP TABLE IF EXISTS `{$escaped_subscription_settings_table}`" );
		$cleanup_log[] = 'Dropped table: ' . $subscription_settings_table;

		// Delete subscriber table
		$subscriber_table = $prefix . 'instant_popup_subscriber';
		$escaped_subscriber_table = esc_sql( $subscriber_table );
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange
		$wpdb->query( "DROP TABLE IF EXISTS `{$escaped_subscriber_table}`" );
		$cleanup_log[] = 'Dropped table: ' . $subscriber_table;
	}

	// 2. Handle Analytics Data
	if ( 'no' === $preserve_analytics ) {
		// Only delete analytics if user chose not to preserve it
		$analytics_table = $prefix . 'instant_popup_analytics';
		$escaped_analytics_table = esc_sql( $analytics_table );
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange
		$wpdb->query( "DROP TABLE IF EXISTS `{$escaped_analytics_table}`" );
		$cleanup_log[] = 'Dropped table: ' . $analytics_table;
	} else {
		$cleanup_log[] = 'Preserved analytics table (user setting)';
	}

	// 3. Handle Plugin Options Cleanup
	if ( 'yes' === $cleanup_options ) {
		// List of all plugin options to remove
		$options_to_delete = array(
			'instant_popup_builder_db_active',
			'instant_popup_builder_db_debug',
			'instant_popup_builder_preserve_analytics',
			'instant_popup_builder_cleanup_options',
			'instant_popup_analytics_dashboard_widget',
			'ipb_activation_date',
			'ipb_review_show_date',
			'ipb_show_review_notice',
			'instant_popup_subscription_settings',
			'instant_popup_subscription_activated',
			'subscription_license_active',
		);

		// Allow extensions to add their own options to be deleted
		$options_to_delete = apply_filters( 'instant_popup_builder_uninstall_options', $options_to_delete );

		foreach ( $options_to_delete as $option ) {
			delete_option( $option );
		}
		$cleanup_log[] = 'Deleted ' . count( $options_to_delete ) . ' plugin options';

		// Clean up user meta for review notices
		$users = get_users( array( 'fields' => 'ID' ) );
		$user_meta_cleaned = 0;
		foreach ( $users as $uid ) {
			delete_user_meta( $uid, 'ipb_review_notice_dismissed' );
			delete_user_meta( $uid, 'ipb_review_already_given' );
			$user_meta_cleaned++;
		}
		$cleanup_log[] = 'Cleaned user meta for ' . $user_meta_cleaned . ' users';
	}

	// 4. Clean up transients (always do this)
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
			'_transient_ipb_%',
			'_transient_timeout_ipb_%'
		)
	);
	$cleanup_log[] = 'Deleted plugin transients';

	// 5. Clean up uploaded files (always do this to avoid orphaned files)
	$upload_dir = plugin_dir_path( __FILE__ ) . 'assets/uploads/';
	if ( is_dir( $upload_dir ) ) {
		$files = glob( $upload_dir . '*' );
		$files_deleted = 0;
		if ( is_array( $files ) ) {
			foreach ( $files as $file ) {
				if ( is_file( $file ) ) {
					wp_delete_file( $file );
					$files_deleted++;
				}
			}
		}
		$cleanup_log[] = 'Deleted ' . $files_deleted . ' uploaded files';
	}

	// Allow extensions to perform their own cleanup
	do_action( 'instant_popup_builder_uninstall_cleanup' );

	// Log cleanup if debug mode was enabled (store in a temporary option that will be deleted)
	if ( 'yes' === get_option( 'instant_popup_builder_db_debug', 'no' ) ) {
		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
		error_log( 'Instant Popup Builder Uninstall: ' . implode( ' | ', $cleanup_log ) );
	}
}

/**
 * Handle multisite uninstall
 */
function instant_popup_builder_uninstall_multisite() {
	global $wpdb;

	// Get all blog IDs
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
	$blog_ids = $wpdb->get_col( "SELECT blog_id FROM {$wpdb->blogs}" );

	// Get the original blog ID
	$original_blog_id = get_current_blog_id();

	// Uninstall for each site
	foreach ( $blog_ids as $blog_id ) {
		switch_to_blog( $blog_id );
		instant_popup_builder_uninstall_site();
	}

	// Switch back to the original blog
	switch_to_blog( $original_blog_id );

	// Clean up any network-wide options if they exist
	if ( is_multisite() ) {
		delete_site_option( 'instant_popup_builder_network_activated' );
	}
}

// Main uninstall logic
if ( is_multisite() ) {
	instant_popup_builder_uninstall_multisite();
} else {
	instant_popup_builder_uninstall_site();
}
