<?php
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

delete_option('dori-chatbot-sharing-id');
delete_option('dori-chatbot-integrate');
delete_option('dori-chatbot-client-id');
delete_option('dori-chatbot-client-secret');
delete_option('dori-chatbot-version');

delete_option('dori_chatbot_auto_update');
delete_option('dori_chatbot_last_update');
delete_option('dori_chatbot_update_error');
delete_option('dori_chatbot_last_update_check');

if (function_exists('as_unschedule_all_actions')) {
    as_unschedule_all_actions('dori_chatbot_send_order_data', array(), 'dori-chatbot');
    as_unschedule_all_actions('dori_chatbot_send_cart_data', array(), 'dori-chatbot');
}

wp_clear_scheduled_hook('dori_chatbot_send_order_data');
wp_clear_scheduled_hook('dori_chatbot_send_cart_data');

global $wpdb;

$upload_dir = wp_upload_dir();
$plugin_assets_dir = $upload_dir['basedir'] . '/dori-chatbot-assets/';

require_once(ABSPATH . 'wp-admin/includes/file.php');
$creds = request_filesystem_credentials(site_url() . '/wp-admin/', '', false, false, array());

if (WP_Filesystem($creds)) {
    global $wp_filesystem;

    if ($wp_filesystem->is_dir($plugin_assets_dir)) {
        $files = $wp_filesystem->dirlist($plugin_assets_dir);
        if (is_array($files)) {
            foreach ($files as $file) {
                $wp_filesystem->delete($plugin_assets_dir . $file['name'], false, 'f');
            }
        }

        $wp_filesystem->rmdir($plugin_assets_dir, false);
    }
}

delete_transient('dori_chatbot_cache');

$transients = $wpdb->get_results("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '_transient_dori%' OR option_name LIKE '_transient_timeout_dori%'");
foreach ($transients as $transient) {
	$name = str_replace(['_transient_', '_transient_timeout_'], '', $transient->option_name);
	delete_transient($name);
}

$wpdb->query("DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE 'dori_chatbot_%'");

$wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'dori_chatbot_%'");

$wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'dori-chatbot-%'");

delete_post_meta_by_key('_dori_thread_id');

if (function_exists('WC')) {
	$session_table = $wpdb->prefix . 'woocommerce_sessions';
	$sessions = $wpdb->get_results("SELECT session_key FROM $session_table WHERE session_value LIKE '%dori%'");
	foreach ($sessions as $session) {
		$wpdb->delete($session_table, ['session_key' => $session->session_key], ['%s']);
	}

	$api_keys = $wpdb->get_results("SELECT key_id FROM {$wpdb->prefix}woocommerce_api_keys WHERE description LIKE '%Dori Chatbot%' OR description LIKE '%Mori Chatbot%'");
	foreach ($api_keys as $key) {
		$wpdb->delete($wpdb->prefix . 'woocommerce_api_keys', ['key_id' => $key->key_id], ['%d']);
	}
}

?>
