<?php
/**
 * Contentosapp Studio Standalone — Uninstall
 *
 * Cleanup logic when the plugin is deleted.
 * Protects database tables by default unless the user explicitly
 * opted-in to delete all data.
 *
 * @package Contentosapp_Studio
 * @since   1.0.1
 */

defined( 'WP_UNINSTALL_PLUGIN' ) || exit;
defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Uninstall cleanup must delete dynamic plugin-owned options/transients and optionally drop plugin-owned tables.

// Read the destructive-delete opt-in before removing any options.
// Tables must be preserved by default; only an explicit pre-existing flag
// allows dropping plugin-owned data tables.
$costudio_should_delete_tables = (bool) get_option( 'costudio_uninstall_delete_data', false );

// ── 1. Scalar options ────────────────────────────────────────────────────────

$costudio_options = array(
	// Core standalone settings
	'costudio_settings',
	'costudio_settings_iv',
	'costudio_sites',
	'costudio_activated_at',
	'costudio_plugin_version',
	'costudio_db_version',
	'costudio_imported_to_core',
	'costudio_site_fingerprint',

	// License — all fields written by Costudio_Standalone_License
	'costudio_license_key',
	'costudio_license_key_type',
	'costudio_license_commercial_key',
	'costudio_license_plan',
	'costudio_license_site_limit',
	'costudio_license_quota',
	'costudio_license_quota_plan',
	'costudio_license_image_limit',
	'costudio_license_image_limit_plan',
	'costudio_license_trial_remaining',
	'costudio_license_status',
	'costudio_license_expires',
	'costudio_license_email',
	'costudio_license_last_check',
	'costudio_license_check_failures',

	// AI model caches (rebuilt on demand)
	'costudio_models_cache',
	'costudio_image_models_cache',
	'costudio_search_models_cache',
	'costudio_last_model_fallback',

	// Agent prompt seeder metadata
	'costudio_prompts_version',
	'costudio_prompts_locale',
	'costudio_prompts_lock_vault',
	'costudio_prompts_customized',

	// Brand voice settings
	'costudio_brand_voices',

	// Telemetry settings
	'costudio_telemetry_enabled',
	'costudio_telemetry_endpoint',
	'costudio_telemetry_secret',
	'costudio_telemetry_last_status',
	'costudio_telemetry_last_flush_ts',
	'costudio_telemetry_queue',
	'costudio_telemetry_consent_version',

	// UI state
	'costudio_welcome_dismissed',
	'costudio_byok_warning_dismissed',
	'costudio_review_prompt_state',

	// Maintenance preferences
	'costudio_housekeeping_optimize_tables',
	'costudio_auto_retry_agents',
	'costudio_enable_web_search',
	'costudio_debug',
	'costudio_debug_enabled',

	// Add-on and usage caches
	'costudio_addon_balance_cache',

	// Queue locks
	'costudio_queue_dispatch_lock',
	'costudio_byok_execution_mode',
	'costudio_byok_worker_heartbeat',
	'costudio_byok_canary_license_hashes',
);

// Agent prompts: costudio_agent_01..07 plus per-agent overrides.
for ( $costudio_i = 1; $costudio_i <= 7; $costudio_i++ ) {
	$costudio_options[] = sprintf( 'costudio_agent_%02d', $costudio_i );
	$costudio_options[] = sprintf( 'costudio_agent_%02d_niche', $costudio_i );
	$costudio_options[] = sprintf( 'costudio_agent_%02d_extra', $costudio_i );
	$costudio_options[] = sprintf( 'costudio_agent_%02d_temperature', $costudio_i );
	$costudio_options[] = sprintf( 'costudio_agent_%02d_history', $costudio_i );
	$costudio_options[] = sprintf( 'costudio_agent_%02d_is_custom', $costudio_i );
}

foreach ( $costudio_options as $costudio_option ) {
	delete_option( $costudio_option );
}

// ── 2. Dynamic options (wildcard patterns) ────────────────────────────────────

global $wpdb;

// Plugin transients (costudio_*).
$wpdb->query(
	"DELETE FROM {$wpdb->options}
	 WHERE option_name LIKE '_transient_%'
	   AND option_name LIKE '%costudio%'"
);

$wpdb->query(
	$wpdb->prepare(
		"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
		$wpdb->esc_like( 'costudio_byok_count_' ) . '%'
	)
);

$costudio_option_prefixes = array(
	'costudio_runner_lock_',
	'costudio_bg_',
	'costudio_bg_src_',
	'costudio_bg_at_',
	'costudio_handoff_recovery_',
);

foreach ( $costudio_option_prefixes as $costudio_option_prefix ) {
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
			$wpdb->esc_like( $costudio_option_prefix ) . '%'
		)
	);
}

// Cache transients for Reference Renderer (v3.2+)
$wpdb->query(
	$wpdb->prepare(
		"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
		$wpdb->esc_like( '_transient_costudio_vurl_' ) . '%',
		$wpdb->esc_like( '_transient_costudio_title_' ) . '%'
	)
);

// ── 3. Transients ────────────────────────────────────────────────────────────
// Per-production transients use dynamic keys — clean them up via a direct DB
// query to avoid iterating over every production row.

// Pipeline log:       costudio_plog_{id} / costudio_plog_last_{id}
// Background token:   costudio_bg_{id} / costudio_bg_src_{id} / costudio_bg_at_{id}
// Image errors:       costudio_img_errors_{id}
// Streaming progress: costudio_stream_{id}
$costudio_transient_prefixes = array(
	'costudio_bg_',
	'costudio_bg_src_',
	'costudio_bg_at_',
	'costudio_plog_',
	'costudio_plog_last_',
	'costudio_img_errors_',
	'costudio_stream_',
);

foreach ( $costudio_transient_prefixes as $costudio_transient_prefix ) {
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
			$wpdb->esc_like( '_transient_' . $costudio_transient_prefix ) . '%',
			$wpdb->esc_like( '_transient_timeout_' . $costudio_transient_prefix ) . '%'
		)
	);
}

// ── 4. Scheduled cron events ─────────────────────────────────────────────────
// deactivate() clears these on deactivation, but uninstall must also clear
// them in case the user deletes the plugin without deactivating first.

$costudio_cron_hooks = array(
	'costudio_telemetry_ping',
	'costudio_revalidate_license',
	'costudio_sync_prompts_cron',
	'costudio_housekeeping_cleanup',
	'costudio_stalled_pipeline_watchdog',
	'costudio_queue_dispatch_watchdog',
	'costudio_pipeline_cron_run',
	'costudio_publication_job_run',
);

foreach ( $costudio_cron_hooks as $costudio_cron_hook ) {
	wp_clear_scheduled_hook( $costudio_cron_hook );
}

// ── 5. Database Tables (OPT-IN ONLY) ─────────────────────────────────────────
// A specific option 'costudio_uninstall_delete_data' must be true before
// deletion. This prevents accidental data loss during migration to ContentOS.

if ( $costudio_should_delete_tables ) {
	$costudio_tables = array(
		'costudio_productions',
		'costudio_planning',
		'costudio_usage',
		'costudio_logs',
		'costudio_publication_attempts',
		'costudio_byok_jobs',
	);

	foreach ( $costudio_tables as $costudio_table ) {
		$costudio_table_name = str_replace( '`', '``', $wpdb->prefix . $costudio_table );
		$wpdb->query( "DROP TABLE IF EXISTS `{$costudio_table_name}`" );
	}
}

// Remove the destructive-delete flag last so its value is still available for
// the table decision above.
delete_option( 'costudio_uninstall_delete_data' );
