<?php
// If uninstall not called from WordPress, then exit.
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

// Check if the user opted to delete data on uninstall.
$aiflt_delete_data = get_option('aiflt_delete_data_on_uninstall', '0');

if ($aiflt_delete_data === '1') {
    global $wpdb;

    // 1. Delete plugin-owned custom tables.
    $aiflt_tables = [
        'aiflt_funnel_data',
        'aiflt_behavior_data',
        'aiflt_ai_usage_log',
        'aiflt_ai_report_log',
        'aiflt_license_activations',
        'aiflt_change_log',
        'aiflt_product_copy_revisions',
        'aiflt_ab_test_ideas',
    ];

    foreach ($aiflt_tables as $aiflt_table) {
        $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}{$aiflt_table}");
    }

    // 2. Delete plugin options. Do not delete unrelated addon options unless they are plugin-owned.
    $aiflt_options = [
        'aiflt_db_version',
        'aiflt_activation_time',
        'aiflt_ai_provider',
        'aiflt_ai_external_consent',
        'aiflt_ai_aggregate_only',
        'aiflt_free_ai_monthly_limit',
        'aiflt_ai_api_key',
        'aiflt_zywrap_api_key',
        'aiflt_zywrap_endpoint',
        'aiflt_pro_license_key',
        'aiflt_license_server_url',
        'aiflt_license_activation_table_version',
        'aiflt_ai_model',
        'aiflt_ai_response_language',
        'aiflt_data_retention',
        'aiflt_delete_data_on_uninstall',
        'aiflt_anonymize_ip',
        'aiflt_enable_tracking',
        'aiflt_excluded_roles',
        'aiflt_excluded_ips',
        'aiflt_world_class_settings',
        'aiflt_setup_completed_steps',
        'aiftcr_settings',
    ];

    foreach ($aiflt_options as $aiflt_option) {
        delete_option($aiflt_option);
    }

    // 3. Clear plugin transients.
    $aiflt_transients = [
        'aiflt_welcome_redirect',
        'aiftaa_latest_full_report',
        'aiftap_latest_prediction',
        'aiflt_ai_report',
        'aiflt_license_status_cache',
        'aiflt_license_data_cache',
    ];

    foreach ($aiflt_transients as $aiflt_transient) {
        delete_transient($aiflt_transient);
    }

    // 4. Clear scheduled events owned by the plugin.
    wp_clear_scheduled_hook('aiflt_daily_cleanup_event');
    wp_clear_scheduled_hook('aiflt_weekly_summary_email_event');
    wp_clear_scheduled_hook('aiflt_weekly_license_check_event');
}
