<?php
/**
 * Full plugin data removal on uninstall.
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Remove scheduled events, database artifacts, options, and plugin content.
 */
function askagento_plugin_uninstall_cleanup() {
    global $wpdb;

    if (function_exists('askagento_recommend_upsell_unschedule_cron')) {
        askagento_recommend_upsell_unschedule_cron();
    }

    if (function_exists('askagento_recommend_cross_sell_unschedule_cron')) {
        askagento_recommend_cross_sell_unschedule_cron();
    }

    if (function_exists('askagento_catalogue_sync_unschedule_cron')) {
        askagento_catalogue_sync_unschedule_cron();
    }

    wp_clear_scheduled_hook('askagento_rebuild_filter_cache');

    $filter_ids = get_posts([
        'post_type'      => defined('ASKAGENTO_POST_TYPE') ? ASKAGENTO_POST_TYPE : 'askagento_filter',
        'post_status'    => 'any',
        'numberposts'    => -1,
        'fields'         => 'ids',
        'suppress_filters' => false,
    ]);

    if (is_array($filter_ids)) {
        foreach ($filter_ids as $filter_id) {
            $filter_id = (int) $filter_id;
            if ($filter_id > 0) {
                wp_delete_post($filter_id, true);
            }
        }
    }

    $table_cache = $wpdb->prefix . 'askagento_cache';
    $table_terms = $wpdb->prefix . 'askagento_term_results';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Dropping the plugin's own custom cache table on uninstall is the intended schema change; caching does not apply.
    $wpdb->query($wpdb->prepare('DROP TABLE IF EXISTS %i', $table_cache));
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Dropping the plugin's own custom term-results table on uninstall is the intended schema change; caching does not apply.
    $wpdb->query($wpdb->prepare('DROP TABLE IF EXISTS %i', $table_terms));

    $option_names = [
        'askagento_consent_required',
        'askagento_data_transfer_consent',
        'askagento_activated_at',
        'askagento_install_settings',
        'askagento_install_site_id',
        'askagento_last_installation_id',
        'askagento_install_last_status',
        'askagento_install_last_product_count',
        'askagento_install_completion_notice_pending',
        'askagento_install_processing_notice_dismissed',
        'askagento_install_last_send',
        'askagento_install_admin_notice',
        'askagento_unlock_onboarding_next_admin',
        'askagento_welcome_notice',
        'askagento_install_activation_pending',
        'askagento_show_welcome_on_plugins',
        'askagento_ai_recommend_auto',
        'askagento_ai_recommend_auto_mode',
        'askagento_ai_recommend_auto_last_run',
        'askagento_ai_recommend_auto_last_error',
        'askagento_ai_recommend_installed_at',
        'askagento_ai_cross_sell_auto',
        'askagento_ai_cross_sell_auto_mode',
        'askagento_ai_cross_sell_auto_last_run',
        'askagento_ai_cross_sell_auto_last_error',
        'askagento_ai_cross_sell_installed_at',
        'askagento_llm_provider_api_keys',
        'askagento_llm_openai_model',
        'askagento_ai_text_search_live_enabled',
        'askagento_ai_text_search_live_debounce_ms',
        'askagento_ai_chatbot_welcome_message',
        'askagento_ai_chatbot_bubble_enabled',
        'askagento_ai_chatbot_powered_by_enabled',
        'askagento_ai_chatbot_bubble_color',
        'askagento_ai_chatbot_panel_logo',
        'askagento_ai_chatbot_panel_title',
        'askagento_last_recommendations_api_fetch_day',
        'askagento_last_cross_sell_recommendations_api_fetch_day',
        'askagento_last_upsell_recommendations_payload',
        'askagento_last_upsell_recommendations_site_id',
        'askagento_last_cross_sell_recommendations_payload',
        'askagento_last_cross_sell_recommendations_site_id',
        'askagento_catalogue_auto_sync_last_slot',
        'askagento_catalogue_auto_sync_last_run',
        'askagento_catalogue_auto_sync_last_error',
    ];

    foreach ($option_names as $name) {
        delete_option($name);
    }

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- No core API deletes transients by prefix; caching does not apply, table name sourced from $wpdb.
    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
            $wpdb->esc_like('_transient_askagento_') . '%',
            $wpdb->esc_like('_transient_timeout_askagento_') . '%'
        )
    );

    $user_meta_keys = [
        'askagento_show_consent_dialog',
        'askagento_onboarding_welcome',
    ];

    foreach ($user_meta_keys as $meta_key) {
        delete_metadata('user', 0, $meta_key, '', true);
    }

    $product_meta_keys = [
        '_askagento_ai_upsell_ids',
        '_askagento_ai_related_ids',
        '_askagento_ai_cross_sell_ids',
        '_askagento_cache_built',
        '_askagento_cache_products',
        '_askagento_settings',
        '_askagento_fields',
    ];

    foreach ($product_meta_keys as $meta_key) {
        delete_post_meta_by_key($meta_key);
    }

    flush_rewrite_rules(false);
}
