<?php
/**
 * Uninstall script for Recast Paywall
 */

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

// Get plugin settings
$settings = get_option('recast_paywall_settings', []);

// Remove plugin options
delete_option('recast_paywall_settings');

// Remove post meta if setting allows it
if (!empty($settings['remove_data_on_uninstall'])) {
    global $wpdb;
    
    // Direct database queries are used here for performance during uninstall
    // WordPress doesn't provide efficient bulk deletion for post meta
    // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
    // phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
    
    // Remove all plugin post meta using individual queries to avoid prepared SQL issues
    $meta_keys = [
        '_recast_inventory_item_id',
        '_recast_last_synced_at', 
        '_recast_paywall_enabled',
        '_recast_sync_retry_count',
        '_recast_price',
        '_recast_status',
        '_recast_geo_availability',
        '_recast_affiliate_share_pct',
        '_recast_gating_mode'
    ];
    
    foreach ($meta_keys as $meta_key) {
        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Direct meta_key deletion is necessary for complete plugin data cleanup during uninstall.
        $wpdb->delete(
            $wpdb->postmeta,
            ['meta_key' => $meta_key], // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
            ['%s']
        );
    }
    
    // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery
    // phpcs:enable WordPress.DB.DirectDatabaseQuery.NoCaching
}

// Clear any scheduled events
wp_clear_scheduled_hook('recast_paywall_sync_retry');

// Clear all transients related to the plugin
global $wpdb;

// Direct database queries are necessary for bulk transient cleanup during uninstall
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query(
    "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_recast_entitlement_%'"
);

$wpdb->query(
    "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_recast_entitlement_%'"
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:enable WordPress.DB.DirectDatabaseQuery.NoCaching
