<?php
/**
 * Uninstall JOC Blockora Morph.
 *
 * @package JOCBM
 *
 * Copyright (C) 2026 JayOnCode
 * License: GPL-2.0-or-later
 */

defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

global $wpdb;

$jocbm_tables = array(
	$wpdb->prefix . 'blockora_morph_boc_system_block_categories',
	$wpdb->prefix . 'blockora_morph_boc_user_contents',
	$wpdb->prefix . 'blockora_morph_boc_user_blocks',
	$wpdb->prefix . 'blockora_morph_boc_system_blocks',
	$wpdb->prefix . 'blockora_morph_boc_categories',
);

foreach ( $jocbm_tables as $jocbm_table ) {
	// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- uninstall drops plugin tables only.
	$wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $jocbm_table ) );
}

$jocbm_options = array(
	'jocbm_db_version',
	'jocbm_welcome_seen',
	'jocbm_installed',
	'jocbm_theme_config',
	'jocbm_frontend_editor',
	'jocbm_version',
	'jocbm_seed_version',
	'jocbm_templates_fp',
	'jocbm_icon_libraries',
	'jocbm_legacy_options_migrated',
);

foreach ( $jocbm_options as $jocbm_option ) {
	delete_option( $jocbm_option );
}

delete_transient( 'jocbm_activation_redirect' );

$jocbm_upload  = wp_upload_dir();
$jocbm_css_dir = trailingslashit( $jocbm_upload['basedir'] ) . 'joc-blockora-morph';

if ( is_dir( $jocbm_css_dir ) ) {
	$jocbm_files = glob( $jocbm_css_dir . '/*' );
	if ( is_array( $jocbm_files ) ) {
		foreach ( $jocbm_files as $jocbm_file ) {
			if ( is_file( $jocbm_file ) ) {
				wp_delete_file( $jocbm_file );
			}
		}
	}

	global $wp_filesystem;
	if ( ! $wp_filesystem instanceof WP_Filesystem_Base ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		WP_Filesystem();
	}
	if ( $wp_filesystem instanceof WP_Filesystem_Base ) {
		$wp_filesystem->rmdir( $jocbm_css_dir, false );
	}
}
