<?php
/*
Completely remove TWX-Chat Plugin and Data/Files/Options/Jobs etc
This file runs once when the plugin is deleted via the WordPress admin "Delete" action (not just deactivated).
*/

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

require_once __DIR__ . '/includes/twx_util.php';

// DB tables
global $wpdb;

$tables = ['twxchat_vectors','twxchat_chatlog','twxchat_chatbots'];
foreach($tables as $table){
    $wp_table_name = $wpdb->prefix . $table;
    $wpdb->query( "DROP TABLE IF EXISTS {$wp_table_name}" );
}

// Uploads dir
if ( ! function_exists( 'wp_upload_dir' ) ) {
    require_once ABSPATH . 'wp-includes/functions.php';
}
$upload_base_dir = wp_upload_dir()['basedir'];
$twx_chat_uploads_dir = $upload_base_dir . '/twx-chat/';
TWXChatUtil::recursiveDelete($twx_chat_uploads_dir);

// Options
$prefix = 'twx_chat';
$options = $wpdb->get_col( $wpdb->prepare(
    "SELECT option_name FROM $wpdb->options WHERE option_name LIKE %s",
    $wpdb->esc_like( $prefix ) . '%'
) );

foreach ( $options as $option ) {
    delete_option( $option );
}

// Cron jobs
$hook = 'twx_chat_site_crawler_daily_event';
wp_clear_scheduled_hook($hook);
wp_cron(); // forces hooks out of memory - apparently
$time = wp_next_scheduled($hook);
if($time) {
    wp_unschedule_event($time, $hook);
    wp_cron();
}

$hook = 'twx_chat_site_crawler_weekly_event';
wp_clear_scheduled_hook($hook);
wp_cron(); // forces hooks out of memory - apparently
$time = wp_next_scheduled($hook);
if($time) {
    wp_unschedule_event($time, $hook);
    wp_cron();
}

$hook = 'twx_chat_cleanup_chatlog_event';
wp_clear_scheduled_hook($hook);
wp_cron(); // forces hooks out of memory - apparently
$time = wp_next_scheduled($hook);
if($time) {
    wp_unschedule_event($time, $hook);
    wp_cron();
}




?>