<?php

 /**
 * =============================================================================
 * @package		        Blue Raven (Free Version)
 * Plugin URI		    https://enterrahost.com/plugins/blue-raven
 * 
 * @Author		        EnterraHost
 * @Author URI		    https://enterrahost.com
 * @License		        GPL-2.0-or-later
 *  
 * @Copyright		    (c) 2025 EnterraHost
 * @File Description    Uninstaller
 * 
 * =============================================================================
 */

/**
 * Blue Raven Uninstaller
 * 
 * This file handles the cleanup when the plugin is uninstalled.
 * It removes all database tables and options created by the plugin.
 * 
 * @package Blue Raven
 */


if ( ! defined( 'ABSPATH' ) ) exit;
if (!defined('WP_UNINSTALL_PLUGIN')) exit;

remove_filter('wp_sitemaps_enabled', '__return_false');

$remove_all_data = get_option('blue_raven_remove_all_data', false);

if ($remove_all_data) {
    global $wpdb;

    ## =========== Remove Tool Items -> Site Map Index now txt =========== ##

    $bingSiteMapKeys = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}BlueRavenValues WHERE setting LIKE %s", '%bing-site-map-key%'));

    if (!empty($bingSiteMapKeys)) {
        $key = $bingSiteMapKeys[0]->value;
        $document_root = isset($_SERVER['DOCUMENT_ROOT']) ? sanitize_text_field(wp_unslash($_SERVER['DOCUMENT_ROOT'])) : ABSPATH;
		$old_txt_path = rtrim($document_root, '/') . '/' . sanitize_file_name($key) . '.txt';
		
        if (file_exists($old_txt_path) && !wp_delete_file($old_txt_path)) return new WP_Error('delete_failed', 'Failed to delete old IndexNow key file.');
    }

    ## =========== Drop tables =========== ##

    $tables = [
        'BlueRavenConfig',
        'BlueRavenValues',
        'BlueRavenProducts',
        'BlueRavenMessages',
        'BlueRavenLogs'
    ];

    foreach ($tables as $table) {
        $table_name = $wpdb->prefix . $table;
        $wpdb->query("DROP TABLE IF EXISTS {$table_name}");
    }

    ## =========== Drop Options =========== ##

    $options = [
        'blueraven_products_db_version',
        'blueraven_messages_db_version',
        'blue_raven_remove_all_data',
    ];

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

}

wp_clear_scheduled_hook('blue_raven_daily_maintenance');