<?php
/**
 * Uninstall Script
 *
 * @package Spin_Wheel
 */

// Exit if accessed directly or not uninstalling
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

// Check if user wants to delete data
$spin_wheel_settings = get_option('swp_settings', []);
$spin_wheel_delete_data = isset($spin_wheel_settings['delete_data_on_uninstall']) ? $spin_wheel_settings['delete_data_on_uninstall'] : 0;

if (!$spin_wheel_delete_data) {
    return;
}

global $wpdb;

// One-time uninstall cleanup of custom tables and options; direct queries are
// required and caching is irrelevant here.
// phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL, PluginCheck.Security.DirectDB

// Delete custom post type posts
$wpdb->query("DELETE FROM {$wpdb->posts} WHERE post_type = 'swp_wheel'");
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id NOT IN (SELECT id FROM {$wpdb->posts})");

// Drop custom tables
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}swp_entries");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}swp_winners");

// Delete options
delete_option('swp_settings');
delete_option('swp_version');
delete_option('swp_auto_embed_wheel_id');

// phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL, PluginCheck.Security.DirectDB

// Clear any cached data
wp_cache_flush();
