<?php
// Security Check: Make sure it's WordPress calling the uninstall, not a direct hit.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    die;
}

global $wpdb;

// 1. Delete Custom Database Tables (Tasks + task messages thread)
$table_name = $wpdb->prefix . 'newsai_alerts';
$messages_table = $wpdb->prefix . 'newsai_task_messages';
$wpdb->query( "DROP TABLE IF EXISTS {$table_name}" );
$wpdb->query( "DROP TABLE IF EXISTS {$messages_table}" );
$gsc_table = $wpdb->prefix . 'newsai_gsc_performance';
$wpdb->query( "DROP TABLE IF EXISTS {$gsc_table}" );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}newsai_gsc_site_daily" );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}newsai_gsc_device" );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}newsai_gsc_queries" );

// 2. Delete All Options saved in wp_options table
$options_to_delete = [
    'newsai_site_name',
    'newsai_site_desc',
    'newsai_lang',
    'newsai_settings_ui',
    'newsai_geo',
    'newsai_tone',
    'newsai_prompt_title',
    'newsai_prompt_rewrite',
    'newsai_prompt_seo',
    'newsai_competitor_rss',
    'newsai_mobile_bottom_sheet',
    'newsai_editor_faq_enabled',
    'newsai_indexing_enabled',
    'newsai_indexing_publish_only',
    'newsai_indexing_bearer_token',
    'newsai_indexing_service_json',
    'newsai_indexing_service_email',
    'newsai_indexing_sc_property',
    'newsai_indexing_last_code',
    'newsai_indexing_last_ping',
    'newsai_indexing_last_url',
    'newsai_indexing_last_error',
    'newsai_decay_radar_enabled',
    'newsai_decay_batch_size',
    'newsai_decay_use_views_filter',
    'newsai_decay_views_meta_key',
    'newsai_decay_min_views',
    'newsai_decay_scan_offset',
    'newsai_lite_mode',
    'newsai_large_site_mode',
    'newsai_deferred_activation_done',
    'newsai_publisher_profile',
    'nros_schema_founding_date',
    'nros_wizard_completed',
    'nros_do_activation_redirect',
    'nros_team_size',
    'nros_schema_type',
    'nros_site_name',
    'nros_site_niche',
    'nros_org_type',
    'nros_schema_output_mode',
    'nros_social_links',
    'nros_org_publishing_principles_url',
    'nros_org_corrections_policy_url',
    'nros_org_ownership_funding_url',
    'nros_org_actionable_feedback_url',
    'newsai_liveblog_schema_enabled',
    'newsai_breaking_expire_hours',
    'newsai_breaking_badge_enabled',
    'newsai_timeline_days',
    'newsai_timeline_para',
    'newsai_timeline_heading',
    'newsai_timeline_mode',
    'newsai_timeline_limit',
    'nros_schema_global_v',
    'nros_schema_megasite_mode',
    'nros_schema_perf_profile',
    'nros_schema_listings_v',
    'nros_schema_warm_last_batch',
    'nros_schema_warm_last_count',
    'nros_schema_cron_warm_queue',
    'nros_schema_archive_warm_queue',
    'nros_schema_stale_warm_cursor',
    'nros_schema_warm_backlog_stats',
    'nros_schema_warm_idle_runs',
    'newsai_plugin_duplicate_folders',
    'newsai_pro_license_key',
    'newsai_pro_license_email',
    'newsai_pro_license_status',
    'newsai_pro_license_checked_at',
    'newsai_pro_license_last_error',
    'newsai_pro_license_expires_at',
    'newsai_pro_license_billing',
    'newsai_tag_guard_enabled',
    'newsai_tag_pool_size',
    'newsai_tag_pool_editor_size',
    'newsai_about_page_id',
    'newsai_wikidata_enrich_enabled',
    'newsai_decay_scan_last_id',
    'newsai_decay_scan_weekly',
    'newsai_seasonal_radar_enabled',
    'newsai_seasonal_lead_days',
    'newsai_seasonal_min_clicks',
    'newsai_seasonal_email_enabled',
    'newsai_seasonal_radar_cache',
    'newsai_trend_history',
    'newsai_240_bootstrapped',
    'newsai_sem_links_profile',
    'newsai_ai_provider',
    'newsai_ai_openai_api_key',
    'newsai_ai_openai_model',
    'newsai_ai_gemini_api_key',
    'newsai_ai_gemini_model',
    'newsai_ai_groq_api_key',
    'newsai_ai_groq_model',
    'newsai_ai_daily_limit_per_user',
    'newsai_ai_alt_enabled',
    'newsai_ai_alt_on_upload',
    'newsai_usage_registry_optin',
    'newsai_usage_registry_consent_at',
    'newsai_usage_registry_install_id',
    'newsai_usage_registry_bootstrapped',
    'newsai_usage_registry_gdpr_migrated_v1',
    'newsai_task_messaging_enabled',
    'newsai_task_email_enabled',
    'newsai_task_email_assigned',
    'newsai_task_email_message',
    'newsai_task_email_done',
    'newsai_task_messages_retention_days',
    'newsai_task_last_purge',
    'newsai_task_last_purge_count',
    'newsai_weekly_report_enabled',
    'newsai_weekly_report_recipients',
    'newsai_weekly_report_window_days',
    'newsai_weekly_report_last_week',
    'newsai_weekly_report_last_sent',
    'newsai_weekly_report_last_count',
    'newsai_indexnow_enabled',
    'newsai_indexnow_key',
    'newsai_indexnow_flushed',
    'newsai_indexnow_rewrite_ver',
    'newsai_indexnow_last_code',
    'newsai_indexnow_last_ping',
    'newsai_indexnow_last_url',
    'newsai_indexnow_last_error',
    'newsai_db_version',
    'newsai_gsc_enabled',
    'newsai_gsc_last_sync',
    'newsai_gsc_last_count',
    'newsai_gsc_last_error',
    'newsai_gsc_last_site_rows',
    'newsai_gsc_last_device_rows',
    'newsai_gsc_last_site_full_sync',
    'newsai_gsc_last_sync_window',
    'newsai_gsc_last_sync_mode',
    'newsai_gsc_last_by_type',
    'newsai_gsc_cache_gen',
    'newsai_gsc_query_sync_enabled',
    'newsai_gsc_last_query_rows',
    'newsai_gsc_last_query_sync_mode',
    'newsai_gsc_last_query_full_sync',
    'newsai_gsc_traffic_drop_enabled',
    'newsai_gsc_traffic_drop_days',
    'newsai_gsc_traffic_drop_min_prev_clicks',
    'newsai_gsc_traffic_drop_min_loss',
    'newsai_gsc_traffic_drop_channel',
    'newsai_gsc_backfill_state',
    'newsai_gsc_backfill_completed_at',
    'newsai_decay_retired_v1',
];

// Post meta from IndexNow per-post diagnostics.
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ('_newsai_indexnow_last_code','_newsai_indexnow_last_ping','_newsai_indexnow_last_error')");


// User meta from Pro promo banner dismissal.
delete_metadata( 'user', 0, 'newsai_pro_promo_dismiss_until', '', true );

// Per-user unread watermarks for task threads.
delete_metadata( 'user', 0, 'newsai_task_thread_seen', '', true );

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

// 3. Delete Transients (Cached Data) — prepared prefix deletes via transient-cleanup.php
$newsai_transient_cleanup = dirname( __FILE__ ) . '/includes/transient-cleanup.php';
if ( file_exists( $newsai_transient_cleanup ) ) {
	require_once $newsai_transient_cleanup;
	if ( function_exists( 'newsai_clear_all_plugin_transients' ) ) {
		newsai_clear_all_plugin_transients();
	}
}

// ==========================================
// 🚀 FIX: MISSING CLEANUP (AUDIT RECOMMENDATIONS)
// ==========================================

// 4. Delete User Meta (E-E-A-T Profiles)
$wpdb->query("DELETE FROM {$wpdb->usermeta} WHERE meta_key IN ('nros_job_title', 'nros_alumni_of', 'nros_knows_about', 'nros_social_facebook', 'nros_social_twitter', 'nros_social_linkedin', 'nros_trends_beat')");

// 5. Delete Term Meta (Entity SEO, Geo & Wikidata)
$wpdb->query("DELETE FROM {$wpdb->termmeta} WHERE meta_key IN ('nros_wikidata_url', 'nros_wikidata_label', 'nros_wikidata_confidence', 'nros_wikidata_source', 'nros_lat', 'nros_lng', 'nros_entity_type', '_newsai_target_geo')");

// 6. Delete Post Meta (Timeline Exclusion Flags)
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key = '_newsai_disable_auto_timeline'");
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ('_nros_timeline_html_v5', '_nros_timeline_html_v5_ts', '_nros_timeline_html_v6', '_nros_timeline_html_v6_ts')");
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key = '_newsai_target_geo'");
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key = '_newsai_enable_liveblog'");
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ('_newsai_breaking_active', '_newsai_breaking_started', '_newsai_breaking_expires')");
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key = '_newsai_last_decay_task_ts'");
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key = '_newsai_ai_alt_generated'");

// 7. Delete Author Performance postmeta (Focus Score history + live) and cached aggregates.
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ('_newsai_focus_score', '_newsai_focus_score_at_publish', '_newsai_discover_score', '_newsai_discover_score_breakdown', '_newsai_ai_seo_analysis')");

// 8. Schema JSON-LD post meta (megasite cache).
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ('_nros_schema_ld_json', '_nros_schema_ld_v')");

// 9. Stop background crons so orphaned tasks do not run after the folder is removed.
$newsai_uninstall_crons = [
	'newsai_pro_daily_license_check',
	'newsai_task_messages_purge',
	'nros_refresh_trend_keyword_cache',
	'newsai_breaking_expire_scan',
	'newsai_gsc_daily_sync',
	'newsai_usage_registry_weekly',
	'newsai_content_decay_scan',
	'newsai_seasonal_radar_refresh',
	'newsai_ai_alt_generate_event',
	'newsai_weekly_cleanup',
	'nros_schema_legacy_warm_batch',
	'nros_schema_nightly_warm_start',
	'nros_schema_nightly_warm_end',
	'nros_schema_nightly_warm_pulse',
	'newsai_deferred_activation_init',
];
foreach ( $newsai_uninstall_crons as $newsai_cron_hook ) {
	wp_clear_scheduled_hook( $newsai_cron_hook );
}