<?php
/**
 * Fired when the plugin is uninstalled.
 *
 * @package GoValid_QR
 */

// Abort if not called by WordPress.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

/**
 * Best-effort token revocation.
 */
$govalid_tokens_raw = get_option( 'govalid_qr_tokens', '' );
if ( ! empty( $govalid_tokens_raw ) ) {
	// We can't use the plugin classes here (already unloaded), so just delete the data.
	// Token revocation would require decryption keys and HTTP calls — skip for uninstall.
}

/**
 * Remove all plugin options.
 */
$govalid_options = array(
	'govalid_qr_tokens',
	'govalid_qr_client_id',
	'govalid_qr_client_secret',
	'govalid_qr_base_url',
	'govalid_qr_userinfo',
	'govalid_qr_version',
	'govalid_qr_db_version',
	'govalid_qr_floating_verify',
	'govalid_qr_verify_position',
);

foreach ( $govalid_options as $govalid_option ) {
	delete_option( $govalid_option );
}

/**
 * Remove all transients.
 */
global $wpdb;
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	"DELETE FROM {$wpdb->options}
	 WHERE option_name LIKE '_transient_govalid_qr_%'
	    OR option_name LIKE '_transient_timeout_govalid_qr_%'
	    OR option_name LIKE '_transient_govalid_oauth_%'
	    OR option_name LIKE '_transient_timeout_govalid_oauth_%'"
);

/**
 * Remove cached image directory.
 */
$govalid_upload_dir = wp_upload_dir();
$govalid_cache_dir  = $govalid_upload_dir['basedir'] . '/govalid-qr-cache';
if ( is_dir( $govalid_cache_dir ) ) {
	$govalid_files = glob( $govalid_cache_dir . '/*' );
	if ( ! empty( $govalid_files ) ) {
		foreach ( $govalid_files as $govalid_file ) {
			if ( is_file( $govalid_file ) ) {
				wp_delete_file( $govalid_file );
			}
		}
	}
	rmdir( $govalid_cache_dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
}

/**
 * Clear scheduled cron hooks.
 */
wp_clear_scheduled_hook( 'govalid_qr_cache_cleanup' );

/**
 * Drop custom database tables.
 */
global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}govalid_form_submission_values" ); // phpcs:ignore
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}govalid_form_submissions" ); // phpcs:ignore
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}govalid_form_fields" ); // phpcs:ignore
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}govalid_forms" ); // phpcs:ignore
