<?php
/**
 * Uninstall script for Ask Any plugin
 *
 * This file is executed when the plugin is deleted from WordPress admin.
 * It removes all plugin data including database tables, options, and user meta.
 *
 * @package Askany
 * @since 1.0.0
 */

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

// Security check - make sure this is a legitimate uninstall
if ( ! current_user_can( 'activate_plugins' ) ) {
	exit;
}

// Include WordPress database functions
global $wpdb;

/**
 * Remove all plugin database tables
 */
function askany_remove_database_tables() {
	global $wpdb;

	// List of all plugin tables
	$tables = array(
		$wpdb->prefix . 'askany_content_index',
		$wpdb->prefix . 'askany_pdf_index',
		$wpdb->prefix . 'askany_chat_history',
		$wpdb->prefix . 'askany_qa_pairs',
		$wpdb->prefix . 'askany_chat_sessions',
		$wpdb->prefix . 'askany_chat_messages',
		$wpdb->prefix . 'askany_user_agents',
		$wpdb->prefix . 'askany_typing_indicators',
		$wpdb->prefix . 'askany_home_faqs',
		$wpdb->prefix . 'askany_home_links',
		$wpdb->prefix . 'askany_api_stats',
		$wpdb->prefix . 'askany_external_sources',
	);

	// Drop each table
	foreach ( $tables as $table ) {
		$wpdb->query( "DROP TABLE IF EXISTS `{$table}`" );
	}
}

/**
 * Remove all plugin options
 */
function askany_remove_plugin_options() {
	// List of all plugin options
	$options = array(
		// API Settings
		'askany_api_key',
		'askany_api_key_openai',
		'askany_api_key_deepseek',
		'askany_api_key_gemini',
		'askany_api_key_claude',
		'askany_api_key_grok',
		'askany_api_key_openrouter',
		'askany_api_provider',
		'askany_api_model',
		'askany_api_url',
		'askany_api_url_openai',
		'askany_api_url_gemini',
		'askany_api_url_deepseek',
		'askany_api_url_claude',
		'askany_api_url_grok',
		'askany_api_url_openrouter',
		'askany_api_enabled',
		'askany_fallback_enabled',

		// Widget Settings
		'askany_floating_widget_enabled',
		'askany_widget_position',
		'askany_chat_header_text',
		'askany_assistant_avatar',
		'askany_contact_form_enabled',
		'askany_contact_form_shortcode',

		// Home Page Settings
		'askany_home_page_enabled',
		'askany_home_logo',
		'askany_home_welcome_message',
		'askany_show_agents',
		'askany_show_documentation',
		'askany_documentation_url',
		'askany_documentation_description',
		'askany_show_faq',
		'askany_show_custom_links',

		// News Section Settings
		'askany_news_enabled',
		'askany_news_label',
		'askany_news_mode',
		'askany_news_timeframe',
		'askany_news_count',
		'askany_news_excerpt_length',
		'askany_news_selected_posts',

		// Plugin Version and Installation
		'askany_version',
		'askany_db_version',
		'askany_installed',
		'askany_activation_time',

		// Cache and Temporary Options
		'askany_cache_version',
		'askany_last_cleanup',
		'askany_stats_cache',
	);

	// Delete each option
	foreach ( $options as $option ) {
		delete_option( $option );

		// Also delete from site options (for multisite)
		delete_site_option( $option );
	}
}

/**
 * Remove plugin user meta data
 */
function askany_remove_user_meta() {
	global $wpdb;

	// List of user meta keys used by the plugin
	$meta_keys = array(
		'askany_agent_status',
		'askany_agent_permissions',
		'askany_chat_preferences',
		'askany_last_activity',
	);

	// Remove user meta for all users
	foreach ( $meta_keys as $meta_key ) {
		$wpdb->delete(
			$wpdb->usermeta,
			array( 'meta_key' => $meta_key ),
			array( '%s' )
		);
	}
}

/**
 * Remove plugin transients and cached data
 */
function askany_remove_transients() {
	global $wpdb;

	// Remove all transients that start with 'askany_'
	$wpdb->query(
		"DELETE FROM {$wpdb->options} 
		WHERE option_name LIKE '_transient_askany_%' 
		OR option_name LIKE '_transient_timeout_askany_%'"
	);

	// For multisite, also remove site transients
	if ( is_multisite() ) {
		$wpdb->query(
			"DELETE FROM {$wpdb->sitemeta} 
			WHERE meta_key LIKE '_site_transient_askany_%' 
			OR meta_key LIKE '_site_transient_timeout_askany_%'"
		);
	}
}

/**
 * Remove uploaded files and directories
 */
function askany_remove_uploaded_files() {
	$upload_dir = wp_upload_dir();
	$askany_dir = $upload_dir['basedir'] . '/askany';

	// Remove the askany upload directory if it exists
	if ( is_dir( $askany_dir ) ) {
		askany_remove_directory_recursive( $askany_dir );
	}
}

/**
 * Recursively remove directory and all its contents
 *
 * @param string $dir Directory path to remove
 */
function askany_remove_directory_recursive( $dir ) {
	if ( ! is_dir( $dir ) ) {
		return;
	}

	$files = array_diff( scandir( $dir ), array( '.', '..' ) );

	foreach ( $files as $file ) {
		$path = $dir . DIRECTORY_SEPARATOR . $file;

		if ( is_dir( $path ) ) {
			askany_remove_directory_recursive( $path );
		} else {
			unlink( $path );
		}
	}

	rmdir( $dir );
}

/**
 * Remove plugin capabilities from all roles
 */
function askany_remove_capabilities() {
	// Get all roles
	$roles = wp_roles()->roles;

	// Plugin capabilities to remove
	$capabilities = array(
		'askany_manage_settings',
		'askany_manage_chat',
		'askany_view_analytics',
		'askany_manage_agents',
	);

	// Remove capabilities from all roles
	foreach ( $roles as $role_name => $role_info ) {
		$role = get_role( $role_name );
		if ( $role ) {
			foreach ( $capabilities as $cap ) {
				$role->remove_cap( $cap );
			}
		}
	}
}

/**
 * Clean up scheduled events
 */
function askany_remove_scheduled_events() {
	// List of scheduled events used by the plugin
	$events = array(
		'askany_cleanup_old_sessions',
		'askany_cleanup_old_messages',
		'askany_update_statistics',
		'askany_cleanup_typing_indicators',
	);

	// Remove each scheduled event
	foreach ( $events as $event ) {
		wp_clear_scheduled_hook( $event );
	}
}

/**
 * Log uninstall activity (optional - for debugging)
 */
function askany_log_uninstall() {
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		// error_log( 'Ask Any Plugin: Uninstall process completed at ' . current_time( 'mysql' ) );
	}
}

/**
 * Main uninstall function
 */
function askany_uninstall_plugin() {
	// Perform cleanup in order
	askany_remove_scheduled_events();
	askany_remove_database_tables();
	askany_remove_plugin_options();
	askany_remove_user_meta();
	askany_remove_transients();
	askany_remove_uploaded_files();
	askany_remove_capabilities();
	askany_log_uninstall();

	// Clear any object cache
	if ( function_exists( 'wp_cache_flush' ) ) {
		wp_cache_flush();
	}
}

// Execute the uninstall
askany_uninstall_plugin();

// Final cleanup - remove any remaining traces
if ( function_exists( 'wp_cache_flush' ) ) {
	wp_cache_flush();
}

// Log completion
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
	// error_log( 'Ask Any Plugin: Complete uninstall finished successfully' );
}
