<?php
/**
 * Uninstall file for CloudXM NFe
 *
 * @package CloudXM_NFe
 */

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

// Delete plugin options
delete_option('cloudxm_nfe_api_base_url');
delete_option('cloudxm_nfe_token_staging');
delete_option('cloudxm_nfe_token_production');
delete_option('cloudxm_nfe_environment');
delete_option('cloudxm_nfe_cancel_days_limit');
delete_option('cloudxm_nfe_auto_issue');
delete_option('cloudxm_nfe_municipality_code');
delete_option('cloudxm_nfe_logging_enabled');

// Delete post meta for orders
global $wpdb;

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

// Clean up log files
$upload_dir = wp_upload_dir();
$log_dir = $upload_dir['basedir'] . '/cloudxm-nfe-logs/';

if (is_dir($log_dir)) {
    $files = glob($log_dir . '*.log');

    foreach ($files as $file) {
        if (is_file($file)) {
            @unlink($file);
        }
    }

    // Try to remove directory
    @rmdir($log_dir);
}

// Clear scheduled hooks
wp_clear_scheduled_hook('cloudxm_nfe_clean_logs');
