<?php
/**
 * Uninstall handler for CoffeeWP Media Cleanup.
 *
 * Runs when a site administrator deletes the plugin via the WordPress
 * Plugins screen. Activating or deactivating does NOT trigger this file
 * — only the explicit "Delete" action does.
 *
 * Behaviour is opt-in destructive: the plugin's data (custom tables,
 * options, transients, on-disk logs + trash) is preserved by default so
 * accidental deletion is recoverable. The user enables destructive
 * uninstall via the `cwpm_delete_data_on_uninstall` option (planned
 * Settings page toggle — see docs/TODO.md). When that option is true,
 * this file performs a complete teardown.
 *
 * Identifiers torn down:
 *  - DB tables  : wp_cwpm_scan_results, wp_cwpm_trash, wp_cwpm_file_hashes
 *  - Options    : every wp_options row whose option_name starts with `cwpm_`
 *                 (covers plain options + transients in their _transient_<name>
 *                 and _transient_timeout_<name> shapes, plus site transients).
 *  - User meta  : every wp_usermeta row whose meta_key starts with `cwpm_`
 *  - Post type  : posts with post_type='cwpm-trash' (tier-2 soft-deleted
 *                 attachments) are hard-deleted via wp_delete_post.
 *  - Filesystem : uploads/cwpm/ directory (logs + trash files).
 *
 * @package CoffeeWP_Media_Cleanup
 */

defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

if ( ! get_option( 'cwpm_delete_data_on_uninstall', false ) ) {
	// User chose to preserve their data — exit without touching anything.
	return;
}

global $wpdb;

// phpcs:disable WordPress.DB.DirectDatabaseQuery -- uninstall context; object cache is being torn down with the site.

// 1. Hard-delete tier-2 trashed attachments (post_type=cwpm-trash).
$cwpm_trash_post_ids = $wpdb->get_col(
	$wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = %s", 'cwpm-trash' )
);
foreach ( (array) $cwpm_trash_post_ids as $cwpm_post_id ) {
	wp_delete_post( (int) $cwpm_post_id, true );
}

// 2. Drop custom tables.
$cwpm_tables = array(
	$wpdb->prefix . 'cwpm_scan_results',
	$wpdb->prefix . 'cwpm_trash',
	$wpdb->prefix . 'cwpm_file_hashes',
);
foreach ( $cwpm_tables as $cwpm_table ) {
	// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table names from our own prefix concat; cannot be parameterized in MySQL.
	$wpdb->query( "DROP TABLE IF EXISTS `{$cwpm_table}`" );
}

// 3. Delete every cwpm_* option (covers transients + site transients).
$wpdb->query(
	"DELETE FROM {$wpdb->options}
	 WHERE option_name LIKE 'cwpm\\_%' ESCAPE '\\\\'
	    OR option_name LIKE '\\_transient\\_cwpm\\_%' ESCAPE '\\\\'
	    OR option_name LIKE '\\_transient\\_timeout\\_cwpm\\_%' ESCAPE '\\\\'
	    OR option_name LIKE '\\_site\\_transient\\_cwpm\\_%' ESCAPE '\\\\'
	    OR option_name LIKE '\\_site\\_transient\\_timeout\\_cwpm\\_%' ESCAPE '\\\\'"
);

// 4. Delete every cwpm_* user_meta key.
$wpdb->query(
	"DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE 'cwpm\\_%' ESCAPE '\\\\'"
);

// phpcs:enable WordPress.DB.DirectDatabaseQuery

// 5. Remove the plugin's data directory under uploads (logs + trash files).
$cwpm_uploads  = wp_upload_dir();
$cwpm_data_dir = $cwpm_uploads['basedir'] . '/cwpm';
if ( is_dir( $cwpm_data_dir ) ) {
	cwpm_uninstall_rrmdir( $cwpm_data_dir );
}

/**
 * Recursively remove a directory and all its contents.
 *
 * Local helper kept inside uninstall.php so we don't depend on the plugin's
 * autoloader (which isn't bootstrapped during uninstall).
 *
 * @param string $cwpm_dir Absolute path to directory.
 * @return void
 */
function cwpm_uninstall_rrmdir( $cwpm_dir ) {
	if ( ! is_dir( $cwpm_dir ) ) {
		return;
	}
	$cwpm_items = array_diff( scandir( $cwpm_dir ), array( '.', '..' ) );
	foreach ( $cwpm_items as $cwpm_item ) {
		$cwpm_path = $cwpm_dir . '/' . $cwpm_item;
		if ( is_dir( $cwpm_path ) ) {
			cwpm_uninstall_rrmdir( $cwpm_path );
		} else {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink,WordPress.PHP.NoSilencedErrors.Discouraged -- removing our own plugin-managed files during uninstall.
			@unlink( $cwpm_path );
		}
	}
	// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- best-effort cleanup; non-empty dir (perms) is silently ignored.
	@rmdir( $cwpm_dir );
}
