<?php
/**
 * Niwa AI uninstall cleanup, registered through Freemius after_uninstall.
 *
 * @package Niwa_AI
 */

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

/**
 * Normalize a filesystem path for prefix checks.
 *
 * @param string $path Raw path.
 * @return string
 */
function niwa_ai_uninstall_normalize_path( $path ) {
    if ( function_exists( 'wp_normalize_path' ) ) {
        $path = wp_normalize_path( $path );
    } else {
        $path = str_replace( '\\', '/', (string) $path );
    }

    return untrailingslashit( (string) $path );
}

/**
 * Recursively delete a path under uploads.
 *
 * @param string $path             Target path.
 * @param string $uploads_base_dir Uploads base directory.
 * @return void
 */
function niwa_ai_uninstall_delete_path( $path, $uploads_base_dir ) {
    if ( empty( $path ) ) {
        return;
    }

    $uploads_base_dir = niwa_ai_uninstall_normalize_path( $uploads_base_dir );
    $candidate_path   = realpath( $path );
    $candidate_path   = false !== $candidate_path ? $candidate_path : $path;
    $candidate_path   = niwa_ai_uninstall_normalize_path( $candidate_path );

    if ( '' === $uploads_base_dir || '' === $candidate_path ) {
        return;
    }

    $uploads_prefix = trailingslashit( $uploads_base_dir );

    if ( 0 !== strpos( trailingslashit( $candidate_path ), $uploads_prefix ) ) {
        return;
    }

    if ( is_link( $path ) || is_file( $path ) ) {
        @unlink( $path );
        return;
    }

    if ( ! is_dir( $path ) ) {
        return;
    }

    $entries = scandir( $path );
    if ( false !== $entries ) {
        foreach ( $entries as $entry ) {
            if ( '.' === $entry || '..' === $entry ) {
                continue;
            }

            niwa_ai_uninstall_delete_path( trailingslashit( $path ) . $entry, $uploads_base_dir );
        }
    }

    @rmdir( $path );
}

/**
 * Remove Niwa AI runtime files from uploads for the current site.
 *
 * @return void
 */
function niwa_ai_uninstall_cleanup_uploads() {
    $uploads = wp_upload_dir();

    if ( ! empty( $uploads['basedir'] ) ) {
        $uploads_base_dir = $uploads['basedir'];
        $paths            = array(
            trailingslashit( $uploads_base_dir ) . 'niwa-ai-workspace',
            trailingslashit( $uploads_base_dir ) . 'niwa-ai-temp',
        );

        foreach ( $paths as $path ) {
            niwa_ai_uninstall_delete_path( $path, $uploads_base_dir );
        }
    }

    if ( class_exists( 'Niwa_AI_Admin_Autonomy_Workspace' ) ) {
        $private_root = Niwa_AI_Admin_Autonomy_Workspace::get_private_data_root();
        if ( '' !== $private_root ) {
            niwa_ai_uninstall_delete_path( $private_root, dirname( $private_root ) );
        }
    }
}

/**
 * Flush option caches touched by direct SQL cleanup.
 *
 * @return void
 */
function niwa_ai_uninstall_flush_option_caches() {
    wp_cache_delete( 'alloptions', 'options' );
    wp_cache_delete( 'notoptions', 'options' );

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

/**
 * Purge common page-builder and optimization caches that can keep serving old
 * bundled widget CSS/JS after the plugin is removed.
 *
 * @return void
 */
function niwa_ai_uninstall_purge_site_caches() {
    if ( class_exists( '\Elementor\Plugin' ) && isset( \Elementor\Plugin::$instance->files_manager ) ) {
        try {
            \Elementor\Plugin::$instance->files_manager->clear_cache();
        } catch ( Throwable $e ) {
            // Ignore third-party cache purge failures.
        }
    }

    if ( class_exists( '\LiteSpeed\Purge' ) ) {
        try {
            \LiteSpeed\Purge::purge_all();
        } catch ( Throwable $e ) {
            // Ignore third-party cache purge failures.
        }
    } else {
        do_action( 'litespeed_purge_all' );
    }

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

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

    if ( class_exists( 'autoptimizeCache' ) && method_exists( 'autoptimizeCache', 'clearall' ) ) {
        \autoptimizeCache::clearall();
    }

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

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

/**
 * Remove Niwa AI data for the current site.
 *
 * @return void
 */
function niwa_ai_uninstall_cleanup_site() {
    global $wpdb;

    $option_like             = $wpdb->esc_like( 'niwa_ai_' ) . '%';
    $transient_like          = $wpdb->esc_like( '_transient_niwa_ai_' ) . '%';
    $transient_timeout_like  = $wpdb->esc_like( '_transient_timeout_niwa_ai_' ) . '%';
    $legacy_options          = array(
        'zaa_agent_profile',
        'niwa_bloging_settings',
    );
    $legacy_transients       = array(
        'niwa_bloging_site_content_map',
    );
    $tables                  = array(
        $wpdb->prefix . 'niwa_ai_contacts',
        $wpdb->prefix . 'niwa_ai_conversion_analytics',
        $wpdb->prefix . 'niwa_ai_ac_analytics',
        $wpdb->prefix . 'niwa_ai_content_index',
        $wpdb->prefix . 'niwa_ai_admin_runs',
        $wpdb->prefix . 'niwa_ai_admin_scheduled_jobs',
        $wpdb->prefix . 'niwa_ai_frontend_questions',
    );
    $scheduled_hooks         = array(
        'niwa_ai_cb_cleanup_expired',
        'niwa_ai_process_memory_embeddings',
        'niwa_ai_process_index_queue',
        'niwa_ai_process_lead_notifications',
        'niwa_ai_process_frontend_chat_queue',
        'niwa_ai_admin_autonomy_process_turn_queue',
        'niwa_ai_site_knowledge_reindex_deferred',
		'niwa_ai_refresh_frontend_semantic_lexicon',
        'niwa_ai_index_upsert',
        'niwa_ai_index_delete',
        'niwa_ai_index_rebuild_full',
        'niwa_ai_admin_autonomy_poll_telegram',
        'niwa_ai_admin_autonomy_process_scheduled_tasks',
    );

    foreach ( $scheduled_hooks as $hook ) {
        wp_clear_scheduled_hook( $hook );
    }

    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->options}
             WHERE option_name LIKE %s
                OR option_name LIKE %s
                OR option_name LIKE %s",
            $option_like,
            $transient_like,
            $transient_timeout_like
        )
    );

    foreach ( $legacy_options as $option_name ) {
        delete_option( $option_name );
    }

    foreach ( $legacy_transients as $transient_name ) {
        delete_transient( $transient_name );
        delete_site_transient( $transient_name );
    }

    foreach ( $tables as $table_name ) {
        $wpdb->query( "DROP TABLE IF EXISTS `{$table_name}`" );
    }

    niwa_ai_uninstall_cleanup_uploads();
    niwa_ai_uninstall_flush_option_caches();
    niwa_ai_uninstall_purge_site_caches();
}

/**
 * Remove Niwa AI multisite-wide transient rows when present.
 *
 * @return void
 */
function niwa_ai_uninstall_cleanup_network_meta() {
    global $wpdb;

    if ( ! is_multisite() || empty( $wpdb->sitemeta ) ) {
        return;
    }

    $site_transient_like         = $wpdb->esc_like( '_site_transient_niwa_ai_' ) . '%';
    $site_transient_timeout_like = $wpdb->esc_like( '_site_transient_timeout_niwa_ai_' ) . '%';

    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->sitemeta}
             WHERE meta_key LIKE %s
                OR meta_key LIKE %s",
            $site_transient_like,
            $site_transient_timeout_like
        )
    );

    niwa_ai_uninstall_flush_option_caches();
    niwa_ai_uninstall_purge_site_caches();
}

/**
 * Remove Niwa AI data after Freemius has reported the uninstall event.
 *
 * @return void
 */
function niwa_ai_uninstall_cleanup() {
    if ( defined( 'NIWA_AI_PRESERVE_DATA_ON_UNINSTALL' ) && NIWA_AI_PRESERVE_DATA_ON_UNINSTALL ) {
        return;
    }

    if ( is_multisite() ) {
        $site_ids = get_sites(
            array(
                'fields' => 'ids',
                'number' => 0,
            )
        );

        foreach ( $site_ids as $site_id ) {
            switch_to_blog( (int) $site_id );
            niwa_ai_uninstall_cleanup_site();
            restore_current_blog();
        }

        niwa_ai_uninstall_cleanup_network_meta();
        return;
    }

    niwa_ai_uninstall_cleanup_site();
}

/**
 * Register Freemius uninstall cleanup.
 *
 * @return void
 */
function niwa_ai_register_freemius_uninstaller() {
    if ( ! function_exists( 'na_fs' ) ) {
        return;
    }

    na_fs()->add_action( 'after_uninstall', 'niwa_ai_uninstall_cleanup' );
}
