<?php
/**
 * PostGate Uninstall Script
 *
 * This file runs when the plugin is uninstalled (deleted) through the WordPress admin.
 * It handles cleanup of plugin data based on user preferences set in the Advanced settings tab.
 *
 * WordPress executes this file automatically when the plugin is uninstalled. It does NOT run
 * when the plugin is simply deactivated - only on actual deletion through the Plugins page.
 *
 * Direct database queries are used following WordPress best practices for uninstall methods.
 *
 * @link https://developer.wordpress.org/plugins/plugin-basics/uninstall-methods/
 *
 * @package PostGate
 * @since 1.0.0
 * @author QodeSphere
 * @license GPL-2.0+
 */

// Exit if not called by WordPress uninstall process
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

/**
 * Check if user has enabled data removal on uninstall.
 *
 * Respects user preference from the Advanced settings tab.
 * If the toggle is disabled (default), we preserve all data for potential reinstallation.
 * If enabled, we perform complete cleanup.
 */
$postgate_remove_data = get_option( 'postgate_remove_data_on_uninstall', false );

// Exit early if data removal is not enabled
if ( ! $postgate_remove_data ) {
	// User wants to preserve data - exit without deletion
	return;
}

/**
 * ============================================================================
 * DATA REMOVAL - Only executed if user explicitly enabled data removal
 * ============================================================================
 */

global $wpdb;

/**
 * Step 1: Delete all plugin options
 *
 * Removes all PostGate settings from the wp_options table including:
 * - General settings (lock modes, enabled post types, bypass roles)
 * - Payment settings (Stripe credentials, webhook secrets)
 * - Appearance settings (templates, preview modes)
 * - Installation metadata
 */

// General settings
delete_option( 'postgate_lock_entire_site' );
delete_option( 'postgate_enabled_post_types' );
delete_option( 'postgate_lock_mode' );
delete_option( 'postgate_bypass_roles' );
delete_option( 'postgate_after_purchase_behavior' );
delete_option( 'postgate_after_purchase_page' );

// Payment settings
delete_option( 'postgate_stripe_connect_mode' );
delete_option( 'postgate_display_currency' );
delete_option( 'postgate_webhook_secret_live' );
delete_option( 'postgate_webhook_secret_sandbox' );
delete_option( 'postgate_stripe_products' );

// Stripe credentials for both modes
$postgate_modes = [ 'live', 'sandbox' ];
$postgate_stripe_keys = [ 'connected_acct', 'access_token', 'refresh_token', 'publishable_key' ];

foreach ( $postgate_modes as $postgate_mode ) {
	foreach ( $postgate_stripe_keys as $postgate_key ) {
		delete_option( "postgate_{$postgate_key}_{$postgate_mode}" );
	}
}

// Bridge service options
delete_option( 'postgate_bridge_url' );
delete_option( 'postgate_bridge_shared_secret' );

// Installation key
delete_option( 'postgate_install_key' );

// Appearance settings
delete_option( 'postgate_preview_mode' );
delete_option( 'postgate_preview_limit' );
delete_option( 'postgate_paywall_layout' );
delete_option( 'postgate_paywall_badge' );
delete_option( 'postgate_paywall_title' );
delete_option( 'postgate_paywall_description' );
delete_option( 'postgate_paywall_content_before' );
delete_option( 'postgate_paywall_content_after' );
delete_option( 'postgate_paywall_button_text' );
delete_option( 'postgate_paywall_login_text' );

// Login gate settings
delete_option( 'postgate_login_badge' );
delete_option( 'postgate_login_title' );
delete_option( 'postgate_login_description' );
delete_option( 'postgate_login_button_text' );
delete_option( 'postgate_login_register_text' );
delete_option( 'postgate_login_forgot_text' );

// Advanced settings (including the uninstall toggle itself)
delete_option( 'postgate_remove_data_on_uninstall' );

/**
 * Step 2: Delete all post meta
 *
 * Removes PostGate meta data from all posts including:
 * - Lock overrides (_postgate_lock_override)
 * - Lock modes (_postgate_lock_mode)
 * - Product IDs (_postgate_product_ids)
 * - Preview settings (_postgate_preview_mode, _postgate_preview_limit)
 */
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query( "DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE '_postgate_%'" );

/**
 * Step 3: Delete all term meta
 *
 * Removes PostGate meta data from all taxonomy terms (categories, tags, etc.)
 */
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query( "DELETE FROM {$wpdb->termmeta} WHERE meta_key LIKE '_postgate_%'" );

/**
 * Step 4: Delete all user meta
 *
 * Removes user access grants and permissions:
 * - _postgate_access_grants: Purchase and subscription access records
 * - _postgate_trial_end: Trial period end dates
 */
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query( "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE '_postgate_%'" );

/**
 * Step 5: Drop custom database tables
 *
 * Completely removes:
 * - postgate_orders: All purchase and subscription records
 * - postgate_webhooks: All webhook event logs
 *
 * Warning: This permanently deletes all order history and webhook logs.
 */
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}postgate_orders" );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}postgate_webhooks" );

/**
 * Step 6: Clear any cached data
 *
 * Flush object cache to remove any cached PostGate data
 */
wp_cache_flush();

/**
 * Uninstall complete.
 *
 * All PostGate data has been permanently removed from the database.
 * This includes settings, orders, webhooks, post meta, term meta, user meta,
 * and custom database tables.
 */
