<?php
/**
 * Tiriri Uninstall
 *
 * Removes all plugin data when the plugin is deleted via the WordPress admin.
 */

// Exit if not called by WordPress
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    exit;
}

/**
 * Clean up all plugin data for a single site.
 */
function tiriri_uninstall_cleanup() {
    global $wpdb;

    // Delete plugin options
    delete_option( 'tiriri_settings' );
    delete_option( 'tiriri_scan_results' );
    delete_option( 'tiriri_installed' );
    delete_option( 'tiriri_manual_declarations' );
    delete_option( 'tiriri_disclosures' );

    // Delete all post meta created by the plugin.
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-off cleanup on uninstall; no cache to invalidate.
    $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s", '_tiriri_%' ) );

    // Clear scheduled events
    wp_clear_scheduled_hook( 'tiriri_daily_scan' );
}

// Handle multisite
if ( is_multisite() ) {
    $sites = get_sites( array( 'fields' => 'ids' ) );
    foreach ( $sites as $site_id ) {
        switch_to_blog( $site_id );
        tiriri_uninstall_cleanup();
        restore_current_blog();
    }
} else {
    tiriri_uninstall_cleanup();
}
