<?php
/**
 * Uninstall handler.
 *
 * Fires when the plugin is deleted via the WordPress admin.
 *
 * Plugin-internal data (options, transients, cron events, custom tables,
 * generated asset files — all regenerable or meaningless without the
 * plugin) is always removed.
 *
 * USER CONTENT is preserved by default: builder templates/components and
 * the builder meta on native pages (custom CSS/JS, import documents,
 * style maps, conversations). Reinstalling the plugin restores full
 * editing of every builder page. To remove user content too, either set
 * `remove_data_on_uninstall` in the `ambld_general` option (Settings) or
 * define `AMBLD_REMOVE_ALL_DATA` as true in wp-config.php before deleting
 * the plugin.
 *
 * @package Antimanual_Builder
 * @since   1.0.0
 */

// Exit if not called by WordPress uninstall.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

/**
 * Delete all plugin data.
 */
function ambld_uninstall() {
	global $wpdb;

	$general        = get_option( 'ambld_general', array() );
	$remove_content =
		( defined( 'AMBLD_REMOVE_ALL_DATA' ) && AMBLD_REMOVE_ALL_DATA ) ||
		( is_array( $general ) && ! empty( $general['remove_data_on_uninstall'] ) );

	if ( $remove_content ) {
		// Builder custom post types. Note: builder pages are native `page`
		// posts and are NEVER deleted — only their builder meta below.
		// (Earlier versions listed a nonexistent `ambld_page` type here and
		// missed `ambld_template` entirely.)
		$builder_post_types = array( 'ambld_template', 'ambld_component' );
		foreach ( $builder_post_types as $post_type ) {
			$post_ids = get_posts(
				array(
					'post_type'              => $post_type,
					'post_status'            => 'any',
					'fields'                 => 'ids',
					'posts_per_page'         => -1,
					'no_found_rows'          => true,
					'update_post_meta_cache' => false,
					'update_post_term_cache' => false,
				)
			);

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

		// All builder meta, including on native pages. This irreversibly
		// removes custom CSS/JS, import documents, and chat conversations —
		// hence the consent gate above.
		$meta_keys = array(
			'_ambld_builder_enabled',
			'_ambld_blocks',
			'_ambld_rendered_html',
			'_ambld_custom_css',
			'_ambld_custom_js',
			'_ambld_custom_js_authorized_by',
			'_ambld_imported_markup_authorized_by',
			'_ambld_import_document',
			'_ambld_style_map',
			'_ambld_page_settings',
			'_ambld_component_type',
			'_ambld_design_overrides',
			'_ambld_conversations',
			'_ambld_imported_scripts',
			'_ambld_imported_scripts_authorized_by',
			'_ambld_imported_script_urls',
			'_ambld_imported_js_urls',
			'_ambld_imported_inline_js',
			'_ambld_template_kind',
			'_ambld_revisions',
		);

		$placeholders = implode( ',', array_fill( 0, count( $meta_keys ), '%s' ) );
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ({$placeholders})",
				$meta_keys
			)
		);
	}

	// ── Plugin-internal data: always removed. ──────────────────────────

	// Delete plugin options.
	$options = array(
		'ambld_version',
		'ambld_activated_at',
		'ambld_ai_settings',
		'ambld_ai_budget',
		'ambld_general',
		'ambld_rewrite_flushed',
		'ambld_design_defaults',
		'ambld_migration_mode',
		'ambld_migration_behavior',
		'ambld_custom_presets',
		'ambld_pages_list_cache_version',
		'ambld_components_list_cache_version',
		'ambld_legacy_code_purged',
		'ambld_rag_schema_version',
		'ambld_seed_completed_at',
		'ambld_seed_last_error',
		'ambld_seed_retry_count',
	);

	foreach ( $options as $option ) {
		delete_option( $option );
	}

	// Delete transients.
	$wpdb->query(
		"DELETE FROM {$wpdb->options} WHERE option_name LIKE '%_transient_ambld_%' OR option_name LIKE '%_transient_timeout_ambld_%'"
	);

	// Unschedule the RAG seed-embedding cron.
	wp_clear_scheduled_hook( 'ambld_seed_embed_run' );

	// Drop custom tables.
	$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}ambld_assets" );
	$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}ambld_rag_chunks" );

	// Delete generated/uploaded asset directories. These hold compiled
	// CSS/JS and import-upload chunks — all regenerable from post meta on
	// reinstall, so they are safe to remove regardless of the consent gate.
	$upload_dir = wp_upload_dir();
	$asset_dirs = array(
		trailingslashit( $upload_dir['basedir'] ) . 'antimanual-builder',
		trailingslashit( $upload_dir['basedir'] ) . 'am-builder',
		trailingslashit( $upload_dir['basedir'] ) . 'ambld-import-chunks',
	);

	foreach ( $asset_dirs as $dir ) {
		if ( is_dir( $dir ) ) {
			ambld_delete_directory( $dir );
		}
	}

	// Flush rewrite rules.
	flush_rewrite_rules();
}

/**
 * Recursively delete a directory and its contents.
 *
 * @param string $dir Directory path.
 * @return void
 */
function ambld_delete_directory( $dir ) {
	if ( ! is_dir( $dir ) ) {
		return;
	}

	$files = array_diff( scandir( $dir ), array( '.', '..' ) );

	foreach ( $files as $file ) {
		$path = trailingslashit( $dir ) . $file;
		if ( is_dir( $path ) ) {
			ambld_delete_directory( $path );
		} else {
			wp_delete_file( $path );
		}
	}

	global $wp_filesystem;

	if ( empty( $wp_filesystem ) ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		WP_Filesystem();
	}

	if ( $wp_filesystem ) {
		$wp_filesystem->rmdir( $dir );
	}
}

ambld_uninstall();
