<?php
/**
 * Biscotti CMP Uninstall
 *
 * Fired when the plugin is uninstalled (deleted via WP admin).
 * Cleans up all plugin data from the database.
 *
 * @package Biscotti_CMP
 * @since 3.0.0
 */

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

// Delete plugin options
delete_option('biscotti_options');
delete_option('biscotti_installed');
delete_option('biscotti_version');
delete_option('biscotti_cmp_api_url');
delete_option('biscotti_last_scan');
delete_option('biscotti_settings');
delete_option('biscotti_legal_documents');
delete_option('biscotti_legal_archive');

// Delete all transient caches using WordPress API
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Uninstall cleanup requires direct query
$biscotti_transient_keys = $wpdb->get_col(
    $wpdb->prepare(
        "SELECT REPLACE(option_name, '_transient_', '') FROM {$wpdb->options} WHERE option_name LIKE %s",
        '_transient_biscotti_%'
    )
);
foreach ($biscotti_transient_keys as $biscotti_key) {
    delete_transient($biscotti_key);
}

// Drop custom tables if they exist (legacy from v2.x)
$biscotti_table_name = $wpdb->prefix . 'biscotti_consent_log';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Uninstall must drop legacy tables
$wpdb->query( 'DROP TABLE IF EXISTS `' . esc_sql( $biscotti_table_name ) . '`' );
