<?php

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

global $wpdb;

// Remove settings
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}bundlepress_settings");

// Remove bundle items
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}bundlepress_bundle_items");

// Remove bundle product type meta
$wpdb->query("DELETE FROM {$wpdb->prefix}postmeta WHERE meta_key = '_bundlepress_settings'");

// Get all bundle products
$bundle_ids = get_posts([
    'post_type' => 'product',
    'post_status' => 'any',
    'fields' => 'ids',
    'tax_query' => [
        [
            'taxonomy' => 'product_type',
            'field'    => 'slug',
            'terms'    => 'bundlepress',
        ],
    ],
]);

foreach ($bundle_ids as $id) {
    wp_delete_post($id, true);
}

// Send delete event if consented
if (get_option('bundlepress_insights_consent') === 'yes') {
    $data = [
        'site_url' => (string) get_site_url(),
        'date' => (string) current_time('mysql'),
        'plugin_slug' => 'bundlepress',
        'event_type' => 'delete',
        'wp_version' => get_bloginfo('version'),
        'email' => get_option('admin_email'),
    ];
    wp_remote_post('https://dominopress.com/api/woocommerce/events', [
        'method' => 'POST',
        'timeout' => 15,
        'headers' => [
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer z1yN6YtKp3dQw8VhR2cU9mlb7XjA4DFMG0He9qPiDoSrTuWvYlZkBnCfDgEhJiY5',
        ],
        'body' => wp_json_encode($data),
    ]);
}

// Remove options
delete_option('bundlepress_version');
delete_option('bundlepress_version_tracked');
delete_option('bundlepress_insights_consent');
delete_option('bundlepress_install_event_sent');
delete_option('bundlepress_just_activated');
delete_option('bundlepress_first_activated');
delete_option('bundlepress_dismissed_notices');

// Remove transients
delete_transient('bundlepress_activation_redirect');
delete_transient('bundlepress_insights_notice_dismissed');
delete_transient('bundlepress_promoter_dismissed');
