<?php
/**
 * Uninstall — Agency Pulse Admin Menu Organizer
 *
 * Runs when the plugin is deleted via the WordPress Plugins screen (not on
 * deactivation). Removes all plugin data from the database so the site is
 * returned to a clean state with no orphaned options or capabilities.
 *
 * @package Agency_Pulse_Admin_Menu
 * @since   1.0.0
 */

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

// ── 1. Delete all plugin options ─────────────────────────────────────────────

$option_keys = array(
	'aamo_menu_configs',
	'aamo_role_assignments',
	'aamo_settings',
	'aamo_access_mode',
	'aamo_ao_connector_state',
	'aamo_template_slugs',
	'aamo_branding_icon',
	'aamo_admin_footer',
	'aamo_color_scheme',
	'aamo_dashboard_message',
	'aamo_db_version',
);

foreach ( $option_keys as $key ) {
	delete_option( $key );
}

// ── 2. Remove capability from all registered roles ───────────────────────────

foreach ( array_keys( wp_roles()->roles ) as $role_slug ) {
	$role = get_role( $role_slug );
	if ( $role ) {
		$role->remove_cap( 'ap_menu_manager' );
	}
}

// ── 3. Remove explicit per-user capability grants ────────────────────────────
//
// Users granted individual access via the Access Control panel have
// 'ap_menu_manager' stored directly in their wp_capabilities user meta.
// A LIKE query finds them without loading every user in the database.

global $wpdb;

$users_with_cap = get_users(
	array(
		'meta_query' => array(
			array(
				'key'     => $wpdb->prefix . 'capabilities',
				'value'   => 'ap_menu_manager',
				'compare' => 'LIKE',
			),
		),
		'fields' => 'all',
	)
);

foreach ( $users_with_cap as $user ) {
	$user->remove_cap( 'ap_menu_manager' );
}
