<?php
/**
 * Plugin uninstall handler.
 *
 * Fired when the plugin is uninstalled. Removes all plugin data from the database.
 *
 * @package MasterQuiz
 * @since   1.0.0
 */

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

// Delete all plugin options.
$masterquiz_options = array(
	'masterquiz_gemini_api_key',
	'masterquiz_openrouter_api_key',
	'masterquiz_groq_api_key',
	'masterquiz_default_num_questions',
	'masterquiz_default_quiz_mode',
	'masterquiz_default_question_types',
	'masterquiz_max_pdf_size',
	'masterquiz_temperature',
	'masterquiz_rag_service_url',
	'masterquiz_rag_service_enabled',
	'masterquiz_rag_service_timeout',
	'masterquiz_auto_create_quiz',
	'masterquiz_default_course',
	'masterquiz_default_lesson',
	'masterquiz_quiz_passing_percentage',
	'masterquiz_essay_grading',
	'masterquiz_minimum_capability',
	'masterquiz_version',
);

foreach ( $masterquiz_options as $masterquiz_option ) {
	delete_option( $masterquiz_option );
}

// Delete all plugin transients.
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- one-time cleanup during uninstall, no caching needed.
$wpdb->query(
	$wpdb->prepare(
		"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
		$wpdb->esc_like( '_transient_masterquiz_' ) . '%',
		$wpdb->esc_like( '_transient_timeout_masterquiz_' ) . '%'
	)
);

// Clean up temp upload directory using WP_Filesystem.
$masterquiz_upload_dir = wp_upload_dir();
$masterquiz_temp_dir   = trailingslashit( $masterquiz_upload_dir['basedir'] ) . 'masterquiz-temp';

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

	$masterquiz_files = new RecursiveIteratorIterator(
		new RecursiveDirectoryIterator( $masterquiz_temp_dir, RecursiveDirectoryIterator::SKIP_DOTS ),
		RecursiveIteratorIterator::CHILD_FIRST
	);

	foreach ( $masterquiz_files as $masterquiz_file ) {
		if ( $masterquiz_file->isDir() ) {
			$wp_filesystem->rmdir( $masterquiz_file->getRealPath() );
		} else {
			wp_delete_file( $masterquiz_file->getRealPath() );
		}
	}

	$wp_filesystem->rmdir( $masterquiz_temp_dir );
}

// Remove scheduled cron events.
$masterquiz_cron_hooks = array( 'masterquiz_process_job', 'masterquiz_cleanup_uploads' );
foreach ( $masterquiz_cron_hooks as $masterquiz_hook ) {
	wp_clear_scheduled_hook( $masterquiz_hook );
}
