<?php
/**
 * Vollstart Repair Desk — Uninstall handler.
 *
 * Only runs when the plugin is deleted via WordPress admin.
 * Respects the "Delete all data on uninstall" setting.
 */
defined('WP_UNINSTALL_PLUGIN') or die('Direct access not allowed');

// Use our own DB class — lightweight, no full plugin load
require_once __DIR__ . '/db.php';
$vollstart_rd_db = new VollstartRD_DB(null);

// Check delete flag from our options table
$vollstart_rd_delete = $vollstart_rd_db->getVar(
    "SELECT option_value FROM %i WHERE option_key = %s",
    $vollstart_rd_db->getTabelle('options'),
    'deleteDataOnUninstall'
);

if ($vollstart_rd_delete != 1) {
    return;
}

// Drop all plugin database tables
foreach ($vollstart_rd_db->getTables() as $vollstart_rd_table) {
    $vollstart_rd_db->rawQuery("DROP TABLE IF EXISTS %i", $vollstart_rd_db->getTabelle($vollstart_rd_table));
}

// Delete uploaded files
$vollstart_rd_upload_dir = wp_upload_dir();
$vollstart_rd_files_dir = $vollstart_rd_upload_dir['basedir'] . '/repair-desk';
if (is_dir($vollstart_rd_files_dir)) {
    global $wp_filesystem;
    if (!function_exists('WP_Filesystem')) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }
    WP_Filesystem();
    $wp_filesystem->rmdir($vollstart_rd_files_dir, true);
}

// Clean up wp_options
delete_option('vollstart_rd_db_version');
delete_option('vollstart_rd_rewrite_flushed');
delete_option('vollstart_rd_first_activated_at');
