<?php
/**
 * Uninstall TradeSchool Manager.
 *
 * Data is removed only when the administrator explicitly enabled the
 * `tsm_remove_data_on_uninstall` option.
 *
 * @package TradeSchoolManager
 */

if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

if ( ! get_option( 'tsm_remove_data_on_uninstall', false ) ) {
	return;
}

( static function () {
	// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	global $wpdb;

	$tradeschool_manager_uninstall_tables = array(
		// Core.
		'tsm_school_years',
		'tsm_students',
		'tsm_teachers',
		'tsm_classes',
		'tsm_class_teachers',
		'tsm_enrollments',
		'tsm_assignments',
		'tsm_grades',
		'tsm_attendance',
		'tsm_payments',
		'tsm_notes',
		'tsm_audit_log',
		'tsm_announcements',
		'tsm_custom_fields',
		'tsm_custom_field_values',
		'tsm_programs',
		'tsm_program_classes',
		'tsm_program_enrollments',
		'tsm_parents',
		'tsm_parent_links',
		'tsm_parent_invite_codes',

		// Invoicing / contracts.
		'tsm_invoices',
		'tsm_invoice_items',
		'tsm_invoice_payments',
		'tsm_invoice_reminders',
		'tsm_payment_plans',
		'tsm_contracts',
		'tsm_contract_events',

		// Applications.
		'tsm_application_forms',
		'tsm_application_submissions',
		'tsm_application_files',
		'tsm_application_leads',

		// Certificates.
		'tsm_certificates',
		'tsm_cert_templates',

		// Student documents.
		'tsm_doc_types',
		'tsm_student_docs',
		'tsm_doc_audit',

		// Workshops.
		'tsm_workshops',
		'tsm_workshop_instances',
		'tsm_workshop_enrollments',
		'tsm_workshop_assignments',
		'tsm_workshop_grades',
		'tsm_workshop_attendance',
	);

	foreach ( $tradeschool_manager_uninstall_tables as $tradeschool_manager_uninstall_table_slug ) {
		$tradeschool_manager_uninstall_table = $wpdb->prefix . $tradeschool_manager_uninstall_table_slug;
		$wpdb->query( "DROP TABLE IF EXISTS {$tradeschool_manager_uninstall_table}" );
	}

	$tradeschool_manager_uninstall_options = array(
		'tsm_settings',
		'tsm_db_version',
		'tsm_caps_version',
		'tsm_remove_data_on_uninstall',
		'tsm_addon_data_markers',
		'tsm_core_portal_pages_created',
		'tsm_first_run_seen',
		'tsm_parents_migrated_to_table',
		'tsm_parent_portal_page_id',
		'tsm_parent_signup_page_id',
		'tsm_cert_core_cols_v1',
		'tsm_cert_core_cols_v2',
		'tsm_apps_db_version',
		'tsws_db_version',
		'tsmp_brevo_settings',
		'tsmp_brevo_log',
		'tsmp_brevo_daily_count',
		'tsmp_mail_settings',
		'tsmp_mail_log',
		'tsmp_emails_settings',
		'tsmp_archive_theme',
		'tsm_page_title_hider',
	);

	foreach ( $tradeschool_manager_uninstall_options as $tradeschool_manager_uninstall_option ) {
		delete_option( $tradeschool_manager_uninstall_option );
	}

	$tradeschool_manager_uninstall_like_patterns = array(
		'tsm_program_enrollment_open_%',
		'tsm_program_enrollment_start_%',
		'tsm_program_enrollment_end_%',
		'tsm_app_approval_%',
		'tsm_app_fee_invoice_%',
		'_transient_tsm_%',
		'_transient_timeout_tsm_%',
		'_site_transient_tsm_%',
		'_site_transient_timeout_tsm_%',
	);

	foreach ( $tradeschool_manager_uninstall_like_patterns as $tradeschool_manager_uninstall_pattern ) {
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
				$tradeschool_manager_uninstall_pattern
			)
		);
	}

	foreach ( array( 'tsm_license_daily_check', 'tsm_invoice_daily', 'tsm_apps_lead_cleanup', 'tsm_cert_reminders_daily' ) as $tradeschool_manager_uninstall_hook ) {
		wp_clear_scheduled_hook( $tradeschool_manager_uninstall_hook );
	}

	$tradeschool_manager_uninstall_uploads = wp_upload_dir();
	if ( empty( $tradeschool_manager_uninstall_uploads['error'] ) && ! empty( $tradeschool_manager_uninstall_uploads['basedir'] ) ) {
		$tradeschool_manager_uninstall_delete_dir = static function ( $tradeschool_manager_uninstall_dir, $tradeschool_manager_uninstall_upload_root ) use ( &$tradeschool_manager_uninstall_delete_dir ) {
			$tradeschool_manager_uninstall_real_dir  = realpath( $tradeschool_manager_uninstall_dir );
			$tradeschool_manager_uninstall_real_root = realpath( $tradeschool_manager_uninstall_upload_root );
			if ( ! $tradeschool_manager_uninstall_real_dir || ! $tradeschool_manager_uninstall_real_root || 0 !== strpos( $tradeschool_manager_uninstall_real_dir, trailingslashit( $tradeschool_manager_uninstall_real_root ) ) ) {
				return;
			}

			$tradeschool_manager_uninstall_items = glob( trailingslashit( $tradeschool_manager_uninstall_real_dir ) . '*', GLOB_NOSORT );
			if ( ! is_array( $tradeschool_manager_uninstall_items ) ) {
				return;
			}

			foreach ( $tradeschool_manager_uninstall_items as $tradeschool_manager_uninstall_item ) {
				if ( is_dir( $tradeschool_manager_uninstall_item ) ) {
					$tradeschool_manager_uninstall_delete_dir( $tradeschool_manager_uninstall_item, $tradeschool_manager_uninstall_upload_root );
				} else {
					wp_delete_file( $tradeschool_manager_uninstall_item );
				}
			}

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

			if ( $wp_filesystem ) {
				$wp_filesystem->rmdir( $tradeschool_manager_uninstall_real_dir );
			}
		};

		$tradeschool_manager_uninstall_upload_dirs = array(
			trailingslashit( $tradeschool_manager_uninstall_uploads['basedir'] ) . 'tsm-applications',
			trailingslashit( $tradeschool_manager_uninstall_uploads['basedir'] ) . 'tsm-certificates',
			trailingslashit( $tradeschool_manager_uninstall_uploads['basedir'] ) . 'tsm-contracts',
			trailingslashit( $tradeschool_manager_uninstall_uploads['basedir'] ) . 'tsm-private',
		);

		foreach ( $tradeschool_manager_uninstall_upload_dirs as $tradeschool_manager_uninstall_upload_dir ) {
			$tradeschool_manager_uninstall_delete_dir( $tradeschool_manager_uninstall_upload_dir, $tradeschool_manager_uninstall_uploads['basedir'] );
		}
	}
} )();
