<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Hooked via Freemius `after_uninstall` action — runs when the user deletes the plugin.
 * Replaces the legacy uninstall.php (forbidden by Freemius / wp.org guidelines).
 */
class CCGAL_Uninstaller {

	public static function cleanup() {
		global $wpdb;

		$options_to_delete = array(
			// Core / DB
			'ccgal_db_version',
			'ccgal_legacy_shortcodes_migrated',
			'ccgal_shortcode_migration_v2_done',
			// OAuth — Google Drive
			'ccgal_oauth_client_id',
			'ccgal_oauth_client_secret',
			'ccgal_oauth_tokens',
			// OAuth — Dropbox
			'ccgal_dropbox_app_key',
			'ccgal_dropbox_app_secret',
			'ccgal_dropbox_tokens',
			// Design
			'ccgal_accent_color',
			'ccgal_hover_color',
			'ccgal_border_color',
			// Text-Overrides
			'ccgal_text_overrides',
			// Print shop — formats / papers / legal
			'ccgal_print_formats',
			'ccgal_paper_options_enabled',
			'ccgal_paper_price_lists',
			'ccgal_print_legal_checkboxes',
			// Print shop — currency
			'ccgal_currency_code',
			// Print shop — payment
			'ccgal_payment_paypal_me',
			'ccgal_payment_paypal_label',
			'ccgal_payment_sepa_holder',
			'ccgal_payment_sepa_iban',
			'ccgal_payment_sepa_bic',
			'ccgal_payment_sepa_bank',
			'ccgal_payment_sepa_label',
			'ccgal_payment_instructions',
			// Print shop — emails
			'ccgal_email_admin_subject',
			'ccgal_email_admin_to',
			'ccgal_email_customer_subject',
			'ccgal_email_customer_intro',
			'ccgal_email_customer_footer',
			'ccgal_order_thankyou',
			// Print shop — shipping
			'ccgal_shipping_cost',
			'ccgal_shipping_threshold',
			// Print shop — page reference
			'ccgal_print_page_id',
		);

		foreach ( $options_to_delete as $option ) {
			delete_option( $option );
		}

		$tables = array(
			$wpdb->prefix . 'ccgal_favorites',
			$wpdb->prefix . 'ccgal_orders',
			$wpdb->prefix . 'ccgal_order_items',
		);

		/**
		 * Pro statistics module adds its tables (ccgal_views, ccgal_downloads)
		 * to this list so they are dropped on uninstall as well.
		 *
		 * @param array $tables Array of fully-qualified table names.
		 */
		$tables = apply_filters( 'ccgal_uninstall_tables', $tables );

		foreach ( $tables as $table ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter -- one-shot DROP TABLE during uninstall; $table is composed of $wpdb->prefix plus a constant string suffix from the hardcoded $tables array above; caching/schema-change concerns do not apply at uninstall time and table-identifier placeholders are not supported by $wpdb->prepare().
			$wpdb->query( "DROP TABLE IF EXISTS {$table}" );
		}

		$galleries = get_posts(
			array(
				'post_type'   => 'ccgal_gallery',
				'post_status' => 'any',
				'numberposts' => -1,
				'fields'      => 'ids',
			)
		);

		foreach ( $galleries as $gallery_id ) {
			wp_delete_post( $gallery_id, true );
		}

		// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
		// Justification: one-shot uninstall query to find pages we created via _ccgal_system_page meta; speed is not a concern at uninstall time and the alternative would be storing these IDs in an option that we'd then have to clean up.
		$print_page_ids = get_posts( array(
			'post_type'   => 'page',
			'post_status' => 'any',
			'numberposts' => -1,
			'fields'      => 'ids',
			'meta_key'    => '_ccgal_system_page',
			'meta_value'  => '1',
		) );
		// phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
		foreach ( $print_page_ids as $pid ) {
			wp_delete_post( $pid, true );
		}

		// Bulk-cleanup of the plugin's transient leftovers (ccgal_oauth_state_*,
		// ccgal_folder_map_*, ccgal_meta_notice_*, etc.). The `_wpg_` patterns
		// catch any pre-1.12.1 leftovers that the prefix migration did not move —
		// defensive, harmless if absent.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- one-shot transient cleanup at uninstall; delete_transient() loop would be much slower for thousands of leftover transients.
		$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\\_transient\\_ccgal\\_%' OR option_name LIKE '\\_transient\\_timeout\\_ccgal\\_%' OR option_name LIKE '\\_transient\\_wpg\\_%' OR option_name LIKE '\\_transient\\_timeout\\_wpg\\_%'" );

		$timestamp = wp_next_scheduled( 'ccgal_cache_cleanup' );
		if ( $timestamp ) {
			wp_unschedule_event( $timestamp, 'ccgal_cache_cleanup' );
		}
		wp_clear_scheduled_hook( 'ccgal_cache_cleanup' );

		$upload_dir = wp_upload_dir();
		$cache_dir  = trailingslashit( $upload_dir['basedir'] ) . 'ccgal-cache';

		if ( is_dir( $cache_dir ) ) {
			$files = new RecursiveIteratorIterator(
				new RecursiveDirectoryIterator( $cache_dir, RecursiveDirectoryIterator::SKIP_DOTS ),
				RecursiveIteratorIterator::CHILD_FIRST
			);
			foreach ( $files as $file ) {
				if ( $file->isDir() ) {
					@rmdir( $file->getRealPath() ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- WP_Filesystem cannot be initialized reliably during uninstall (no admin context for FTP credentials); direct rmdir() is intentional and silently no-ops on permission errors.
				} else {
					wp_delete_file( $file->getRealPath() );
				}
			}
			@rmdir( $cache_dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- see above
		}
	}
}
