<?php
/**
 * ArkHost Security Pack Uninstaller.
 *
 * @package ArkHost_Security_Pack
 */

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

// Load the database class.
require_once plugin_dir_path( __FILE__ ) . 'includes/class-arksp-db.php';

// Run uninstall.
ARKSP_DB::uninstall();

// Clear any remaining transients.
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Cleanup during uninstall, caching not applicable.
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_arksp_%'" );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Cleanup during uninstall, caching not applicable.
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_arksp_%'" );

// Clear scheduled events.
wp_clear_scheduled_hook( 'arksp_daily_cleanup' );
wp_clear_scheduled_hook( 'arksp_daily_file_scan' );
wp_clear_scheduled_hook( 'arksp_weekly_malware_scan' );

// Delete user meta for 2FA.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Cleanup during uninstall, caching not applicable.
$wpdb->query( "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE '_arksp_%'" );

// Clean up uploads directory (geo-database and quarantine files).
$arksp_upload_dir  = wp_upload_dir();
$arksp_plugin_data = $arksp_upload_dir['basedir'] . '/arkhost-security-pack';
if ( is_dir( $arksp_plugin_data ) ) {
	// Recursively delete all files and subdirectories.
	$arksp_iterator = new RecursiveIteratorIterator(
		new RecursiveDirectoryIterator( $arksp_plugin_data, RecursiveDirectoryIterator::SKIP_DOTS ),
		RecursiveIteratorIterator::CHILD_FIRST
	);
	foreach ( $arksp_iterator as $arksp_item ) {
		if ( $arksp_item->isDir() ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- Uninstall cleanup.
			rmdir( $arksp_item->getPathname() );
		} else {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- Uninstall cleanup.
			unlink( $arksp_item->getPathname() );
		}
	}
	// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- Uninstall cleanup.
	rmdir( $arksp_plugin_data );
}
