<?php
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
global $wpdb;

// Remove settings and transients.
delete_option( 'smc_settings' );
delete_option( 'smc_orphan_count' );

// Drop log table.
$smc_table = esc_sql( $wpdb->prefix . 'smc_log' );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$wpdb->query( "DROP TABLE IF EXISTS `{$smc_table}`" );

// Remove all virtual folder taxonomy terms, their meta, and object relationships.
$taxonomy = 'smc_media_folder';

// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$smc_term_taxonomy_ids = $wpdb->get_col(
	$wpdb->prepare(
		"SELECT tt.term_taxonomy_id FROM {$wpdb->term_taxonomy} tt WHERE tt.taxonomy = %s",
		$taxonomy
	)
);

if ( ! empty( $smc_term_taxonomy_ids ) ) {
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery
	$smc_term_ids = $wpdb->get_col(
		$wpdb->prepare(
			"SELECT tt.term_id FROM {$wpdb->term_taxonomy} tt WHERE tt.taxonomy = %s",
			$taxonomy
		)
	);

	// Delete object relationships (removes folder assignment from attachments).
	$smc_tt_id_list = implode( ',', array_map( 'intval', $smc_term_taxonomy_ids ) );
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	$wpdb->query( "DELETE FROM {$wpdb->term_relationships} WHERE term_taxonomy_id IN ({$smc_tt_id_list})" );

	// Delete term meta.
	$smc_term_id_list = implode( ',', array_map( 'intval', $smc_term_ids ) );
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	$wpdb->query( "DELETE FROM {$wpdb->termmeta} WHERE term_id IN ({$smc_term_id_list})" );

	// Delete term taxonomy rows.
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	$wpdb->query( "DELETE FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id IN ({$smc_tt_id_list})" );

	// Delete terms themselves (only if they have no other taxonomies).
	foreach ( $smc_term_ids as $smc_term_id ) {
		$smc_term_id = (int) $smc_term_id;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$smc_other = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->term_taxonomy} WHERE term_id = %d",
				$smc_term_id
			)
		);
		if ( ! $smc_other ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery
			$wpdb->delete( $wpdb->terms, array( 'term_id' => $smc_term_id ), array( '%d' ) );
		}
	}
}
