<?php
/**
 * Deployment Tab: Admin Bar
 *
 * Manage which agents appear in the WordPress admin bar chat overlay.
 * Each enabled agent has its own position and page targeting settings.
 * Agents show under the "AI Agents" menu in the toolbar and open a
 * slide-in chat panel on click.
 *
 * Included by admin/deployment.php — do not load directly.
 *
 * @package    Agent_Builder
 * @subpackage Admin
 * @since      2.8.3
 *
 * php version 8.1
 */

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

// Handle save.
if (
	isset( $_POST['agentic_save_admin_bar'], $_POST['_wpnonce'] )
	&& wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'agentic_admin_bar_settings' )
) {
	$agentic_ab_raw = isset( $_POST['agentic_ab'] ) && is_array( $_POST['agentic_ab'] )
		? wp_unslash( $_POST['agentic_ab'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized per-field below.
		: array();

	// Collect all known slugs — every agent in the registry needs a display='' reset
	// if not submitted, so unchecking a box is correctly persisted.
	$agentic_ab_registry   = \Agentic_Agent_Registry::get_instance();
	$agentic_ab_all_slugs  = array_keys( $agentic_ab_registry->get_all_instances() );
	$agentic_ab_submitted  = array();
	$agentic_ab_config_log = array();

	foreach ( $agentic_ab_raw as $agentic_ab_slug => $agentic_ab_data ) {
		$agentic_ab_slug = sanitize_key( $agentic_ab_slug );
		if ( ! $agentic_ab_slug ) {
			continue;
		}

		$agentic_ab_position = sanitize_key( $agentic_ab_data['position'] ?? 'bottom-right' );
		if ( ! in_array( $agentic_ab_position, array( 'bottom-right', 'bottom-left' ), true ) ) {
			$agentic_ab_position = 'bottom-right';
		}

		$agentic_ab_pages = sanitize_key( $agentic_ab_data['pages'] ?? 'all' );
		if ( ! in_array( $agentic_ab_pages, array( 'all', 'admin', 'front' ), true ) ) {
			$agentic_ab_pages = 'all';
		}

		$agentic_ab_display = ! empty( $agentic_ab_data['enabled'] ) ? '1' : '';

		// Store in agentic_agent_settings — the single source of truth.
		\Agentic\Agent_Settings::update( $agentic_ab_slug, 'admin_bar_display', $agentic_ab_display );
		\Agentic\Agent_Settings::update( $agentic_ab_slug, 'admin_bar_position', $agentic_ab_position );
		\Agentic\Agent_Settings::update( $agentic_ab_slug, 'admin_bar_pages', $agentic_ab_pages );

		$agentic_ab_submitted[] = $agentic_ab_slug;
		if ( '1' === $agentic_ab_display ) {
			$agentic_ab_config_log[ $agentic_ab_slug ] = array(
				'position' => $agentic_ab_position,
				'pages'    => $agentic_ab_pages,
			);
		}
	}

	// Disable agents that were not in the submitted form (i.e. their checkbox was absent).
	foreach ( $agentic_ab_all_slugs as $agentic_ab_missing ) {
		if ( ! in_array( $agentic_ab_missing, $agentic_ab_submitted, true ) ) {
			\Agentic\Agent_Settings::update( $agentic_ab_missing, 'admin_bar_display', '' );
		}
	}

	$agentic_ab_audit = new \Agentic\Audit_Log();
	$agentic_ab_audit->log(
		'system',
		'settings_changed',
		'deployment_admin_bar',
		array(
			'setting' => 'admin_bar_agents',
			'changes' => $agentic_ab_config_log,
		)
	);

	$agentic_notice = __( 'Admin bar settings saved.', 'agent-builder' );
}

// Load per-agent settings from agentic_agent_settings (pre-loaded into cache on init).
$agentic_registry   = \Agentic_Agent_Registry::get_instance();
$agentic_all_agents = $agentic_registry->get_all_instances();

// Build a display row for each agent: check agent_settings first, then fall back to
// the legacy Deployments table for installations that haven't saved yet.
$agentic_ab_rows = array();
foreach ( $agentic_all_agents as $agentic_ab_slug => $agentic_ab_inst ) {
	$agentic_ab_display = \Agentic\Agent_Settings::get( $agentic_ab_slug, 'admin_bar_display' );

	// One-time migration: if key is absent from agent_settings, check Deployments.
	if ( '' === $agentic_ab_display && class_exists( '\Agentic\Deployments' ) ) {
		$agentic_dep_rows = \Agentic\Deployments::all( \Agentic\Deployments::TYPE_ADMIN_BAR, $agentic_ab_slug );
		if ( ! empty( $agentic_dep_rows[0] ) && ! empty( $agentic_dep_rows[0]['enabled'] ) ) {
			$agentic_dep_cfg    = $agentic_dep_rows[0]['config'] ?? array();
			$agentic_ab_display = '1';
			// Write into agent_settings so we don't fall back next time.
			\Agentic\Agent_Settings::update( $agentic_ab_slug, 'admin_bar_display', '1' );
			\Agentic\Agent_Settings::update( $agentic_ab_slug, 'admin_bar_position', $agentic_dep_cfg['position'] ?? 'bottom-right' );
			\Agentic\Agent_Settings::update( $agentic_ab_slug, 'admin_bar_pages', $agentic_dep_cfg['pages'] ?? 'all' );
		}
	}

	$agentic_ab_rows[ $agentic_ab_slug ] = array(
		'enabled' => '1' === $agentic_ab_display,
		'config'  => array(
			'position' => \Agentic\Agent_Settings::get( $agentic_ab_slug, 'admin_bar_position', 'bottom-right' ),
			'pages'    => \Agentic\Agent_Settings::get( $agentic_ab_slug, 'admin_bar_pages', 'all' ),
		),
	);
}
?>

<?php if ( isset( $agentic_notice ) ) : ?>
<div class="notice notice-success is-dismissible">
	<p><?php echo esc_html( $agentic_notice ); ?></p>
</div>
<?php endif; ?>

<div class="agentic-tab-section">

	<h2><?php esc_html_e( 'Admin Bar', 'agent-builder' ); ?></h2>
	<p>
		<?php esc_html_e( 'Select which agents appear in the WordPress admin bar. Enabled agents show under the "AI Agents" toolbar menu and open a slide-in chat overlay when clicked.', 'agent-builder' ); ?>
	</p>

	<?php if ( empty( $agentic_all_agents ) ) : ?>
		<div class="notice notice-warning">
			<p><?php esc_html_e( 'No active agents found. Activate at least one agent first.', 'agent-builder' ); ?></p>
		</div>
	<?php else : ?>
		<form method="post" action="">
			<?php wp_nonce_field( 'agentic_admin_bar_settings' ); ?>

			<table class="widefat striped">
				<thead>
					<tr>
						<th class="agentic-col-40"><?php esc_html_e( 'Enable', 'agent-builder' ); ?></th>
						<th><?php esc_html_e( 'Agent', 'agent-builder' ); ?></th>
						<th><?php esc_html_e( 'Position', 'agent-builder' ); ?></th>
						<th><?php esc_html_e( 'Show On', 'agent-builder' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $agentic_all_agents as $agentic_slug => $agentic_agent ) : ?>
						<?php
						$agentic_ab_row        = $agentic_ab_rows[ $agentic_slug ] ?? array();
						$agentic_ab_is_enabled = ! empty( $agentic_ab_row['enabled'] );
						$agentic_ab_cfg        = $agentic_ab_row['config'] ?? array();
						$agentic_ab_position   = $agentic_ab_cfg['position'] ?? 'bottom-right';
						$agentic_ab_pages      = $agentic_ab_cfg['pages'] ?? 'all';
						?>
						<tr>
							<td class="agentic-td-center">
								<input type="checkbox"
									name="agentic_ab[<?php echo esc_attr( $agentic_slug ); ?>][enabled]"
									value="1"
									<?php checked( $agentic_ab_is_enabled ); ?>>
							</td>
							<td>
								<?php echo esc_html( $agentic_agent->get_icon() . ' ' . $agentic_agent->get_name() ); ?>
								<code class="agentic-code-meta"><?php echo esc_html( $agentic_slug ); ?></code>
							</td>
							<td>
								<select name="agentic_ab[<?php echo esc_attr( $agentic_slug ); ?>][position]" class="agentic-select-full">
									<option value="bottom-right" <?php selected( $agentic_ab_position, 'bottom-right' ); ?>>
										<?php esc_html_e( 'Bottom Right', 'agent-builder' ); ?>
									</option>
									<option value="bottom-left" <?php selected( $agentic_ab_position, 'bottom-left' ); ?>>
										<?php esc_html_e( 'Bottom Left', 'agent-builder' ); ?>
									</option>
								</select>
							</td>
							<td>
								<select name="agentic_ab[<?php echo esc_attr( $agentic_slug ); ?>][pages]" class="agentic-select-full">
									<option value="all" <?php selected( $agentic_ab_pages, 'all' ); ?>>
										<?php esc_html_e( 'Everywhere', 'agent-builder' ); ?>
									</option>
									<option value="admin" <?php selected( $agentic_ab_pages, 'admin' ); ?>>
										<?php esc_html_e( 'Admin Only', 'agent-builder' ); ?>
									</option>
									<option value="front" <?php selected( $agentic_ab_pages, 'front' ); ?>>
										<?php esc_html_e( 'Frontend Only', 'agent-builder' ); ?>
									</option>
								</select>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>

			<?php submit_button( __( 'Save Settings', 'agent-builder' ), 'primary', 'agentic_save_admin_bar' ); ?>
		</form>
	<?php endif; ?>

	<div class="agentic-embed-note">
		<h3><?php esc_html_e( 'How the Admin Bar Works', 'agent-builder' ); ?></h3>
		<ul>
			<li><?php esc_html_e( 'Enabled agents appear under the "AI Agents" menu in the WordPress toolbar.', 'agent-builder' ); ?></li>
			<li><?php esc_html_e( 'Clicking an agent opens a slide-in chat panel according to the position setting.', 'agent-builder' ); ?></li>
			<li><?php esc_html_e( 'Chat history is stored per agent in the browser — conversations persist across page loads.', 'agent-builder' ); ?></li>
			<li><?php esc_html_e( 'The admin bar is visible to users with the "chat_admin_bar" capability (administrators by default).', 'agent-builder' ); ?></li>
			<li><?php esc_html_e( 'The "AI Agents" toolbar menu always appears for administrators — enable agents here to add them as chat options.', 'agent-builder' ); ?></li>
		</ul>
	</div>

</div>
