<?php
/**
 * Uninstall Script
 *
 * Fired when the plugin is uninstalled (deleted) from WordPress.
 * This file is called automatically by WordPress when the user deletes the plugin.
 *
 * @package DonorCore
 * @since 1.0.0
 */

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

/**
 * Delete custom database tables
 */
function donor_core_delete_tables() {
	global $wpdb;
	
	// Define table names
	$tables = array(
		$wpdb->prefix . 'donorcore_donation_logs',
		$wpdb->prefix . 'donorcore_donor_analytics',
	);
	
	// Drop each table
	foreach ( $tables as $table ) {
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Required for uninstall
		$wpdb->query( "DROP TABLE IF EXISTS `{$table}`" );
	}
}

/**
 * Delete all plugin options
 */
function donor_core_delete_options() {
	global $wpdb;
	
	// Delete individual options
	$options = array(
		// Database version
		'donorcore_db_version',
		
		// Email settings
		'donorcore_email_subject',
		'donorcore_email_template',
		
		// PDF settings
		'donorcore_pdf_header',
		'donorcore_pdf_body',
		'donorcore_pdf_footer',
		
		// General settings
		'donorcore_minimum_donation_amount',
		'donorcore_suggested_amounts',
		'donorcore_org_address',
		
		// Donation Form Styling - Typography
		'donorcore_donation_form_font_family',
		'donorcore_donation_form_heading_size',
		'donorcore_donation_form_body_size',
		'donorcore_donation_form_button_font_size',
		'donorcore_donation_form_font_weight_heading',
		'donorcore_donation_form_font_weight_body',
		'donorcore_donation_form_font_weight_button',
		'donorcore_donation_form_line_height',
		
		// Donation Form Styling - Colors
		'donorcore_donation_form_primary_color',
		'donorcore_donation_form_secondary_color',
		'donorcore_donation_form_bg_color',
		'donorcore_donation_form_text_color',
		'donorcore_donation_form_label_color',
		'donorcore_donation_form_border_color',
		'donorcore_donation_form_input_bg_color',
		'donorcore_donation_form_input_focus_color',
		
		// Donation Form Styling - Spacing & Layout
		'donorcore_donation_form_container_padding',
		'donorcore_donation_form_container_margin',
		'donorcore_donation_form_element_gap',
		'donorcore_donation_form_max_width',
		
		// Donation Form Styling - Borders & Shadows
		'donorcore_donation_form_border_radius',
		'donorcore_donation_form_button_radius',
		'donorcore_donation_form_input_radius',
		'donorcore_donation_form_border_width',
		'donorcore_donation_form_shadow',
		
		// Donation Form Styling - Buttons
		'donorcore_donation_form_button_padding_y',
		'donorcore_donation_form_button_padding_x',
		'donorcore_donation_form_button_hover_effect',
		
		// Donation Form Styling - Inputs
		'donorcore_donation_form_input_padding',
		'donorcore_donation_form_amount_btn_padding',
		'donorcore_donation_form_amount_cols',
		
		// Progress Bar Styling
		'donorcore_progress_bar_primary_color',
		'donorcore_progress_bar_font_family',
		'donorcore_progress_bar_heading_size',
		'donorcore_progress_bar_body_size',
		'donorcore_progress_bar_border_radius',
		'donorcore_progress_bar_bg_color',
		'donorcore_progress_bar_text_color',
		'donorcore_progress_bar_fill_color',
		'donorcore_progress_bar_height',
		'donorcore_progress_bar_container_padding',
		'donorcore_progress_bar_container_margin',
		'donorcore_progress_bar_max_width',
		'donorcore_progress_bar_shadow',
		'donorcore_progress_bar_heading_font_weight',
		'donorcore_progress_bar_amount_font_weight',
		'donorcore_progress_bar_label_font_weight',
		'donorcore_progress_bar_percentage_font_weight',
		'donorcore_progress_bar_amount_font_size',
		'donorcore_progress_bar_track_bg_color',
		'donorcore_progress_bar_percentage_text_color',
	);
	
	// Delete each option
	foreach ( $options as $option ) {
		delete_option( $option );
	}
	
	// Delete any options that start with donorcore_ or donor_core_
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
			$wpdb->esc_like( 'donorcore_' ) . '%',
			$wpdb->esc_like( 'donor_core_' ) . '%'
		)
	);
	
	// Delete transients and cached data
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s",
			$wpdb->esc_like( '_transient_donorcore_' ) . '%',
			$wpdb->esc_like( '_transient_timeout_donorcore_' ) . '%',
			$wpdb->esc_like( '_transient_donor_core_' ) . '%',
			$wpdb->esc_like( '_transient_timeout_donor_core_' ) . '%'
		)
	);
}

/**
 * Delete campaign posts
 */
function donor_core_delete_campaigns() {
	// Get all campaign posts
	$campaigns = get_posts(
		array(
			'post_type'      => 'donorcore_campaign',
			'posts_per_page' => -1,
			'post_status'    => 'any',
			'fields'         => 'ids',
		)
	);
	
	// Delete each campaign (with trash and post meta)
	foreach ( $campaigns as $campaign_id ) {
		wp_delete_post( $campaign_id, true ); // true = force delete, bypass trash
	}
}

/**
 * Delete uploaded files (PDF receipts)
 */
function donor_core_delete_uploads() {
	$upload_dir   = wp_upload_dir();
	$receipts_dir = trailingslashit( $upload_dir['basedir'] ) . 'donor-core-receipts';

	global $wp_filesystem;

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

	if ( ! $wp_filesystem ) {
		return;
	}

	// Safety check: ensure path is inside uploads directory.
	$base_dir     = realpath( $upload_dir['basedir'] );
	$receipts_dir_real = realpath( $receipts_dir );

	if (
		$receipts_dir_real &&
		strpos( $receipts_dir_real, $base_dir ) === 0 &&
		$wp_filesystem->is_dir( $receipts_dir )
	) {
		// Recursively delete directory and contents.
		$wp_filesystem->rmdir( $receipts_dir, true );
	}
}

/**
 * Clean up WooCommerce donation product metadata
 * Note: We keep the orders themselves (donation records) intact
 */
function donor_core_cleanup_woocommerce_metadata() {
	global $wpdb;
	
	// Delete donation product types (if any were created as actual products)
	$donation_products = get_posts(
		array(
			'post_type'      => 'product',
			'posts_per_page' => -1,
			'post_status'    => 'any',
			'fields'         => 'ids',
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required for uninstall cleanup
			'meta_query'     => array(
				array(
					'key'   => '_donorcore_is_donation',
					'value' => 'yes',
				),
			),
		)
	);
	
	foreach ( $donation_products as $product_id ) {
		wp_delete_post( $product_id, true );
	}
	
	// Clean up orphaned post meta (metadata without posts)
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s",
			$wpdb->esc_like( '_donorcore_' ) . '%'
		)
	);
}

/**
 * Main uninstall function
 */
function donor_core_uninstall() {
	// Only run on single site or main site of multisite
	if ( ! is_multisite() || is_main_site() ) {
		
		// 1. Delete custom database tables
		donor_core_delete_tables();
		
		// 2. Delete all plugin options
		donor_core_delete_options();
		
		// 3. Delete campaign posts
		donor_core_delete_campaigns();
		
		// 4. Delete uploaded PDF receipts
		donor_core_delete_uploads();
		
		// 5. Clean up WooCommerce metadata
		donor_core_cleanup_woocommerce_metadata();
	}
	
	// For multisite, delete options from all sites
	if ( is_multisite() ) {
		global $wpdb;
		
		// Get all blog IDs
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$blog_ids = $wpdb->get_col( "SELECT blog_id FROM {$wpdb->blogs}" );
		
		foreach ( $blog_ids as $blog_id ) {
			switch_to_blog( $blog_id );
			
			donor_core_delete_tables();
			donor_core_delete_options();
			donor_core_delete_campaigns();
			donor_core_delete_uploads();
			donor_core_cleanup_woocommerce_metadata();
			
			restore_current_blog();
		}
	}
	
	// Clear any remaining cache
	wp_cache_flush();
}

// Run the uninstall
donor_core_uninstall();
