<?php
/**
 * Uninstall script for BW Dev.
 *
 * Runs when the plugin is deleted via the WP Admin plugins screen.
 * Cleans up options, custom tables, custom post-meta, and scheduled events.
 */

defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

global $wpdb;

// Delete plugin options.
delete_option( 'bw_dev_settings' );
delete_option( 'bw_dev_version' );
delete_option( 'bw_dev_migration_version' );
delete_option( 'bw_dev_login_log_db_version' );
delete_option( 'bw_dev_dashboard_widget_cache' );

// Delete site meta on multisite.
if ( is_multisite() ) {
	delete_site_option( 'bw_dev_settings' );
	delete_site_option( 'bw_dev_migration_version' );
	delete_site_option( 'bw_dev_login_log_db_version' );
}

// Drop the Login Activity Log table.
$login_log_table = $wpdb->prefix . 'bw_dev_login_log';
$wpdb->query( "DROP TABLE IF EXISTS {$login_log_table}" ); // phpcs:ignore WordPress.DB

// Drop per-menu-item visibility meta from the Menu Visibility module.
$wpdb->delete( $wpdb->postmeta, array( 'meta_key' => '_bw_dev_menu_visibility' ), array( '%s' ) ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key

// Drop per-post title override meta from the Title Override module.
$wpdb->delete( $wpdb->postmeta, array( 'meta_key' => '_bw_dev_title_override' ), array( '%s' ) ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key

// Drop per-post scheduled-action meta from the Scheduled Post Actions module.
// `_bw_dev_psa_actions` is the current (1.11.1+) JSON-list key; the other four
// are legacy single-action keys kept around for cleanup on pre-1.11.1 data.
foreach ( array( '_bw_dev_psa_timestamp', '_bw_dev_psa_actions', '_bw_dev_psa_action', '_bw_dev_psa_status', '_bw_dev_psa_taxonomy', '_bw_dev_psa_terms' ) as $bw_dev_psa_meta_key ) {
	$wpdb->delete( $wpdb->postmeta, array( 'meta_key' => $bw_dev_psa_meta_key ), array( '%s' ) ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
}

// Clear any scheduled events the plugin owns.
wp_clear_scheduled_hook( 'bw_dev_login_log_prune' );
wp_clear_scheduled_hook( 'bw_dev_psa_run' );
