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

$settings = get_option('novajyin_settings', array());
$keep_data = is_array($settings) && !empty($settings['keep_data_on_delete']);

if (!$keep_data) {
    global $wpdb;

    $tables = array(
        $wpdb->prefix . 'nova_jyo_inquiries',
        $wpdb->prefix . 'nova_jyo_inquiry_groups',
        $wpdb->prefix . 'nova_jyo_inquiry_group_users',
        $wpdb->prefix . 'nova_jyo_inquiry_statuses',
        $wpdb->prefix . 'nova_jyo_inquiry_priorities',
        $wpdb->prefix . 'nova_jyo_inquiry_histories',
        $wpdb->prefix . 'nova_jyo_inquiry_memos',
        $wpdb->prefix . 'nova_jyo_inquiry_rules',
    );

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

    $upload_dir = wp_upload_dir();
    $attachment_dir = trailingslashit($upload_dir['basedir']) . 'nova-jyo-inquiries';
    if (is_dir($attachment_dir)) {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($attachment_dir, FilesystemIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );
        foreach ($iterator as $file) {
            if ($file->isDir()) {
                rmdir($file->getPathname());
            } else {
                unlink($file->getPathname());
            }
        }
        rmdir($attachment_dir);
    }

    delete_option('novajyin_settings');
    delete_option('novajyin_db_version');
}

$caps = array(
    'novajyin_access',
    'novajyin_manage_inquiries',
    'novajyin_edit_inquiries',
    'novajyin_delete_inquiries',
    'novajyin_export_inquiries',
    'novajyin_manage_settings',
    'novajyin_manage_groups',
    'novajyin_view_all_inquiries',
    'novajyin_edit_assigned_inquiries',
);

$administrator = get_role('administrator');
if ($administrator) {
    foreach ($caps as $cap) {
        $administrator->remove_cap($cap);
    }
}

remove_role('novajyin_staff');
remove_role('novajyin_viewer');





