<?php
/**
 * Configuración de roles y permisos por pestaña.
 *
 * @package Logistica
 */

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

if ( ! class_exists( 'Logistica_Roles', false ) || ! Logistica_Roles::user_can_manage_config() ) {
	return;
}

$role_definitions = Logistica_Roles::get_role_definitions();
$role_permissions = Logistica_Roles::get_role_permissions();
$tab_choices      = Logistica_Roles::tab_choices();
$config_tabs      = class_exists( 'Logistica_Settings', false )
	? Logistica_Settings::sort_tabs_by_menu_order( $tab_choices )
	: $tab_choices;
$backend_page_id  = Logistica_Roles::get_backend_page_id();
$backend_page_url = $backend_page_id ? get_permalink( $backend_page_id ) : '';
$config_tab_url   = logistica_configuracion_tab_url();
$users_section_url = function_exists( 'logistica_config_section_url' )
	? logistica_config_section_url( 'logistica-config-usuarios' )
	: $config_tab_url;
$current_user_id  = (int) get_current_user_id();
?>
<section id="logistica-config-roles" class="logistica-configuracion-card logistica-configuracion-card--roles logistica-roles-settings logistica-configuracion-section">
	<div class="logistica-configuracion-card__head">
		<h3><?php esc_html_e( 'Roles y permisos', 'logistica' ); ?></h3>
		<p class="description">
			<?php if ( defined( 'LOGISTICA_STANDALONE' ) && LOGISTICA_STANDALONE ) : ?>
				<?php esc_html_e( 'Define qué pestañas puede usar cada rol en el panel operativo y en el panel público.', 'logistica' ); ?>
			<?php else : ?>
				<?php esc_html_e( 'Define la página de operaciones y qué pestañas puede usar cada rol en el backend y en el panel público.', 'logistica' ); ?>
			<?php endif; ?>
		</p>
	</div>
	<div class="logistica-configuracion-card__body">
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="logistica-role-permissions-form">
			<input type="hidden" name="action" value="logistica_save_role_permissions">
			<input type="hidden" name="logistica_redirect_to" value="<?php echo esc_url( $config_tab_url ); ?>">
			<?php wp_nonce_field( 'logistica_save_role_permissions' ); ?>

			<?php if ( defined( 'LOGISTICA_STANDALONE' ) && LOGISTICA_STANDALONE ) : ?>
				<input type="hidden" name="backend_page_id" value="<?php echo esc_attr( (string) max( 1, (int) $backend_page_id ) ); ?>">
			<?php else : ?>
			<div class="logistica-frontend-page-picker logistica-configuracion-backend-picker">
				<label for="logistica-backend-page-id">
					<strong><?php esc_html_e( 'Página de operaciones (backend)', 'logistica' ); ?></strong>
				</label>
				<?php
				wp_dropdown_pages(
					array(
						'name'              => 'backend_page_id',
						'id'                => 'logistica-backend-page-id',
						'selected'          => $backend_page_id,
						'show_option_none'  => __( '— Seleccionar página —', 'logistica' ),
						'option_none_value' => '0',
					)
				);
				?>
				<p class="description">
					<?php esc_html_e( 'Usa la plantilla «JB Planeación — Operaciones». El plugin puede crearla automáticamente al activarse.', 'logistica' ); ?>
					<?php if ( $backend_page_url ) : ?>
						<a href="<?php echo esc_url( $backend_page_url ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Abrir operaciones', 'logistica' ); ?></a>
					<?php endif; ?>
				</p>
			</div>
			<?php endif; ?>

			<div class="logistica-table-wrap logistica-table-wrap--responsive">
				<table class="widefat striped logistica-role-permissions-table logistica-config-responsive-table">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Rol', 'logistica' ); ?></th>
							<th><?php esc_html_e( 'Panel operativo (usuario)', 'logistica' ); ?></th>
							<th><?php esc_html_e( 'Panel público (legacy)', 'logistica' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $role_definitions as $role_slug => $role_data ) : ?>
							<?php
							$backend_selected  = $role_permissions[ $role_slug ]['backend'] ?? array();
							$frontend_selected = $role_permissions[ $role_slug ]['frontend'] ?? array();
							$frontend_choices  = $config_tabs;
							unset( $frontend_choices['logistica-configuracion'] );
							$backend_count     = count( $backend_selected );
							$backend_total     = count( $config_tabs );
							$frontend_count    = count( $frontend_selected );
							$frontend_total    = count( $frontend_choices );
							$backend_summary   = sprintf(
								/* translators: 1: active tab count, 2: total tab count */
								__( '%1$d de %2$d activas', 'logistica' ),
								$backend_count,
								$backend_total
							);
							$frontend_summary  = sprintf(
								/* translators: 1: active tab count, 2: total tab count */
								__( '%1$d de %2$d activas', 'logistica' ),
								$frontend_count,
								$frontend_total
							);
							?>
							<tr>
								<td class="logistica-role-permissions-table__role">
									<strong><?php echo esc_html( $role_data['label'] ); ?></strong>
									<p class="description"><?php echo esc_html( $role_data['description'] ); ?></p>
									<code><?php echo esc_html( $role_slug ); ?></code>
								</td>
								<td class="logistica-role-permissions-table__panel">
									<?php $backend_panel_id = 'logistica-role-perms-' . $role_slug . '-backend'; ?>
									<button
										type="button"
										class="logistica-role-permissions-trigger"
										data-role-permissions-open
										aria-controls="<?php echo esc_attr( $backend_panel_id ); ?>"
										aria-expanded="false"
										data-role-label="<?php echo esc_attr( $role_data['label'] ); ?>"
										data-panel-label="<?php esc_attr_e( 'Panel operativo (usuario)', 'logistica' ); ?>"
									>
										<span class="logistica-role-permissions-trigger__title"><?php esc_html_e( 'Panel operativo (usuario)', 'logistica' ); ?></span>
										<span class="logistica-role-permissions-trigger__meta" data-role-permissions-summary><?php echo esc_html( $backend_summary ); ?></span>
										<span class="logistica-role-permissions-trigger__icon" aria-hidden="true">
											<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>
										</span>
									</button>
									<div id="<?php echo esc_attr( $backend_panel_id ); ?>" class="logistica-role-permissions-panel-source" hidden>
										<div
											class="logistica-frontend-menu-picker logistica-frontend-menu-picker--compact"
											role="group"
											data-role-permissions-picker
											data-panel-total="<?php echo esc_attr( (string) $backend_total ); ?>"
										>
											<?php foreach ( $config_tabs as $slug => $label ) : ?>
												<label class="logistica-frontend-menu-picker__item">
													<input
														type="checkbox"
														name="role_permissions[<?php echo esc_attr( $role_slug ); ?>][backend][]"
														value="<?php echo esc_attr( $slug ); ?>"
														<?php checked( in_array( $slug, $backend_selected, true ) ); ?>
													/>
													<span><?php echo esc_html( $label ); ?></span>
												</label>
											<?php endforeach; ?>
										</div>
									</div>
								</td>
								<td class="logistica-role-permissions-table__panel">
									<?php $frontend_panel_id = 'logistica-role-perms-' . $role_slug . '-frontend'; ?>
									<button
										type="button"
										class="logistica-role-permissions-trigger"
										data-role-permissions-open
										aria-controls="<?php echo esc_attr( $frontend_panel_id ); ?>"
										aria-expanded="false"
										data-role-label="<?php echo esc_attr( $role_data['label'] ); ?>"
										data-panel-label="<?php esc_attr_e( 'Panel público (legacy)', 'logistica' ); ?>"
									>
										<span class="logistica-role-permissions-trigger__title"><?php esc_html_e( 'Panel público (legacy)', 'logistica' ); ?></span>
										<span class="logistica-role-permissions-trigger__meta" data-role-permissions-summary><?php echo esc_html( $frontend_summary ); ?></span>
										<span class="logistica-role-permissions-trigger__icon" aria-hidden="true">
											<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>
										</span>
									</button>
									<div id="<?php echo esc_attr( $frontend_panel_id ); ?>" class="logistica-role-permissions-panel-source" hidden>
										<div
											class="logistica-frontend-menu-picker logistica-frontend-menu-picker--compact"
											role="group"
											data-role-permissions-picker
											data-panel-total="<?php echo esc_attr( (string) $frontend_total ); ?>"
										>
											<?php foreach ( $frontend_choices as $slug => $label ) : ?>
												<label class="logistica-frontend-menu-picker__item">
													<input
														type="checkbox"
														name="role_permissions[<?php echo esc_attr( $role_slug ); ?>][frontend][]"
														value="<?php echo esc_attr( $slug ); ?>"
														<?php checked( in_array( $slug, $frontend_selected, true ) ); ?>
													/>
													<span><?php echo esc_html( $label ); ?></span>
												</label>
											<?php endforeach; ?>
										</div>
									</div>
								</td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>

			<p class="logistica-configuracion-card__actions">
				<button class="button button-primary" type="submit"><?php esc_html_e( 'Guardar roles y permisos', 'logistica' ); ?></button>
			</p>

			<div class="logistica-role-permissions-modal" data-role-permissions-modal data-summary-format="<?php echo esc_attr( __( '%1$d de %2$d activas', 'logistica' ) ); ?>" hidden>
				<div class="logistica-role-permissions-modal__backdrop" data-role-permissions-close aria-hidden="true"></div>
				<div
					class="logistica-role-permissions-modal__panel"
					role="dialog"
					aria-modal="true"
					aria-labelledby="logistica-role-permissions-modal-title"
				>
					<header class="logistica-role-permissions-modal__head">
						<div class="logistica-role-permissions-modal__head-copy">
							<h3 id="logistica-role-permissions-modal-title" data-role-permissions-modal-title></h3>
							<p data-role-permissions-modal-subtitle></p>
						</div>
						<button type="button" class="logistica-role-permissions-modal__close" data-role-permissions-close aria-label="<?php esc_attr_e( 'Cerrar', 'logistica' ); ?>">&times;</button>
					</header>
					<div class="logistica-role-permissions-modal__body" data-role-permissions-modal-body></div>
					<footer class="logistica-role-permissions-modal__foot">
						<button type="button" class="button button-primary" data-role-permissions-close><?php esc_html_e( 'Listo', 'logistica' ); ?></button>
					</footer>
				</div>
			</div>
		</form>
	</div>
</section>

<section id="logistica-config-usuarios" class="logistica-configuracion-card logistica-configuracion-card--users logistica-configuracion-section">
	<div class="logistica-configuracion-card__head">
		<h3><?php esc_html_e( 'Usuarios con rol JB', 'logistica' ); ?></h3>
		<p class="description">
			<?php if ( defined( 'LOGISTICA_STANDALONE' ) && LOGISTICA_STANDALONE ) : ?>
				<?php esc_html_e( 'Asigna el rol operativo y las pestañas personalizadas de cada usuario.', 'logistica' ); ?>
			<?php else : ?>
				<?php esc_html_e( 'Asigna el rol operativo desde Usuarios → Editar usuario, sección JB Planeación.', 'logistica' ); ?>
			<?php endif; ?>
		</p>
	</div>
	<div class="logistica-configuracion-card__body">
		<?php if ( defined( 'LOGISTICA_STANDALONE' ) && LOGISTICA_STANDALONE ) : ?>
			<p class="logistica-configuracion-card__actions">
				<a class="button button-primary" href="<?php echo esc_url( logistica_new_user_url( 'logistica-config-usuarios' ) ); ?>"><?php esc_html_e( 'Agregar usuario', 'logistica' ); ?></a>
			</p>
		<?php endif; ?>
		<div class="logistica-table-wrap logistica-table-wrap--responsive">
			<table class="widefat striped logistica-config-users-table logistica-config-responsive-table">
				<thead>
					<tr>
						<th><?php esc_html_e( 'Usuario', 'logistica' ); ?></th>
						<th><?php esc_html_e( 'Rol JB', 'logistica' ); ?></th>
						<th class="logistica-user-row-actions__head"><?php esc_html_e( 'Acciones', 'logistica' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php
					if ( defined( 'LOGISTICA_STANDALONE' ) && LOGISTICA_STANDALONE ) {
						$jb_users = get_users(
							array(
								'orderby' => 'display_name',
								'order'   => 'ASC',
							)
						);
					} else {
						$jb_users = get_users(
							array(
								'role__in' => array_keys( $role_definitions ),
								'orderby'  => 'display_name',
								'order'    => 'ASC',
							)
						);
					}
					if ( empty( $jb_users ) ) :
						?>
						<tr><td colspan="3"><?php esc_html_e( 'Aún no hay usuarios con roles JB asignados.', 'logistica' ); ?></td></tr>
					<?php else : ?>
						<?php foreach ( $jb_users as $jb_user ) : ?>
							<?php
							$user_label = trim( $jb_user->display_name . ' (' . $jb_user->user_login . ')' );
							$can_delete = ( defined( 'LOGISTICA_STANDALONE' ) && LOGISTICA_STANDALONE )
								&& $current_user_id !== (int) $jb_user->ID;
							?>
							<tr class="logistica-config-users-row">
								<td class="logistica-config-users-row__user" data-label="<?php esc_attr_e( 'Usuario', 'logistica' ); ?>">
									<span class="logistica-config-users-row__name"><?php echo esc_html( $jb_user->display_name ); ?></span>
									<span class="logistica-config-users-row__login"><?php echo esc_html( $jb_user->user_login ); ?></span>
								</td>
								<td class="logistica-config-users-row__role" data-label="<?php esc_attr_e( 'Rol JB', 'logistica' ); ?>">
									<span class="logistica-config-users-row__role-badge"><?php echo esc_html( Logistica_Roles::get_user_role_label( $jb_user->ID ) ); ?></span>
								</td>
								<td class="logistica-user-row-actions logistica-config-users-row__actions logistica-config-responsive-table__actions" data-label="<?php esc_attr_e( 'Acciones', 'logistica' ); ?>">
									<div class="logistica-user-row-actions__group">
										<a
											class="logistica-user-row-actions__btn logistica-user-row-actions__btn--edit logistica-user-row-actions__btn--icon"
											href="<?php echo esc_url( get_edit_user_link( $jb_user->ID, 'logistica-config-usuarios' ) ); ?>"
											aria-label="<?php echo esc_attr( sprintf( __( 'Editar %s', 'logistica' ), $user_label ) ); ?>"
											title="<?php esc_attr_e( 'Editar', 'logistica' ); ?>"
										>
											<span class="screen-reader-text"><?php esc_html_e( 'Editar', 'logistica' ); ?></span>
											<span class="logistica-user-row-actions__btn-icon" aria-hidden="true">
												<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>
											</span>
										</a>
										<?php if ( $can_delete ) : ?>
											<form
												method="post"
												action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
												class="logistica-user-delete-form"
												data-user-label="<?php echo esc_attr( $user_label ); ?>"
											>
												<input type="hidden" name="action" value="logistica_delete_user_jb">
												<input type="hidden" name="user_id" value="<?php echo esc_attr( (string) $jb_user->ID ); ?>">
												<input type="hidden" name="logistica_redirect_to" value="<?php echo esc_url( $users_section_url ); ?>">
												<?php wp_nonce_field( 'logistica_delete_user_jb_' . $jb_user->ID ); ?>
												<button
													type="submit"
													class="logistica-user-row-actions__btn logistica-user-row-actions__btn--delete logistica-user-row-actions__btn--icon"
													data-logistica-delete-user
													aria-label="<?php echo esc_attr( sprintf( __( 'Eliminar %s', 'logistica' ), $user_label ) ); ?>"
													title="<?php esc_attr_e( 'Eliminar', 'logistica' ); ?>"
												>
													<span class="screen-reader-text"><?php esc_html_e( 'Eliminar', 'logistica' ); ?></span>
													<span class="logistica-user-row-actions__btn-icon" aria-hidden="true">
														<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>
													</span>
												</button>
											</form>
										<?php endif; ?>
									</div>
								</td>
							</tr>
						<?php endforeach; ?>
					<?php endif; ?>
				</tbody>
			</table>
		</div>
	</div>
</section>
