<?php
/**
 *  EnviaYa Uninstall
 *
 *  Uninstalling WooCommerce deletes user roles, pages, tables, and options.
 *
 */

defined('WP_UNINSTALL_PLUGIN') || exit;

global $wpdb;

const PREFIX = 'enviaya';

$deleteAllData = get_option('woocommerce_enviaya_settings')['total_remove'];
error_log('Delete ALL: ' .  json_encode($deleteAllData));

$dir = WP_PLUGIN_DIR . '/enviaya-for-woocommerce/lang/';
$request = wp_remote_get(content_url() . '/plugins/enviaya-for-woocommerce/lang/en_US.json');
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file === get_locale() . '.json') {
                $request = wp_remote_get(content_url() . '/plugins/enviaya-for-woocommerce/lang/' . get_locale() . '.json');
            }
        }
        closedir($dh);
    }
}

if (strtoupper(trim($deleteAllData)) === strtoupper("yes")) {
    // Delete options.
    $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE 'woocommerce_enviaya_setting%';");

    // Drop tables
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}" . PREFIX . "_rates");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}" . PREFIX . "_shipment");

    // Drop logs files
    $upload_dir   = wp_upload_dir();
    outputFiles($upload_dir["basedir"]."/wc-logs");    
}

// Define a function to output files in a directory
function outputFiles($path)
{   // Check directory exists or not
    if(file_exists($path) && is_dir($path)){
        // Scan the files in this directory
        $result = scandir($path);
        
        // Filter out the current (.) and parent (..) directories
        $files = array_diff($result, array('.', '..'));
        
        if(count($files) > 0){
            // Loop through retuned array
            foreach($files as $file){
                if(is_file("$path/$file")){
                    // Display filename
                    $needle = substr($file, 0, 21);
                    if($needle == "enviaya-rating-logger")
                    {
                        unlink("$path/$file");
                    }
                        
                } else if(is_dir("$path/$file")){
                    // Recursively call the function if directories found
                    outputFiles("$path/$file");
                }
            }
        } else{
            error_log( "ERROR: No files found in the directory." );
        }
    } else {
        error_log( "ERROR: The directory does not exist.");
    }
}//end