<?php
/**
 * Contenido compartido de la pestaña Configuración (wp-admin y backend ?config=1).
 *
 * @package Logistica
 */

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

if ( ! class_exists( 'Logistica_Roles', false ) || ! Logistica_Roles::user_can_manage_config() ) {
	echo '<div class="logistica-panel"><p>' . esc_html__( 'No tienes permisos para ver esta configuración.', 'logistica' ) . '</p></div>';
	return;
}

$frontend_menu_tabs = Logistica_Settings::get_frontend_menu_tabs();
$menu_choices       = Logistica_Settings::frontend_menu_choices();
$frontend_page_id   = Logistica_Settings::get_frontend_page_id();
$frontend_page_url  = $frontend_page_id ? get_permalink( $frontend_page_id ) : '';
$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();
$config_panel_url   = logistica_config_panel_url();
$menu_order_tabs    = Logistica_Settings::get_operations_menu_order_with_labels();

$config_nav_sections = array();
if ( ! defined( 'LOGISTICA_STANDALONE' ) || ! LOGISTICA_STANDALONE ) {
	$config_nav_sections[] = array(
		'id'    => 'logistica-config-operaciones',
		'label' => __( 'Panel de operaciones', 'logistica' ),
	);
}
$config_nav_sections[] = array(
	'id'    => 'logistica-config-menu-order',
	'label' => __( 'Orden del menú', 'logistica' ),
);
$config_nav_sections[] = array(
	'id'    => 'logistica-config-panel-publico',
	'label' => __( 'Panel público', 'logistica' ),
);
$config_nav_sections[] = array(
	'id'    => 'logistica-config-roles',
	'label' => __( 'Roles y permisos', 'logistica' ),
);
$config_nav_sections[] = array(
	'id'    => 'logistica-config-usuarios',
	'label' => __( 'Usuarios JB', 'logistica' ),
);
$config_nav_sections[] = array(
	'id'    => 'logistica-config-sistema',
	'label' => __( 'Sistema', 'logistica' ),
);
$config_nav_sections[] = array(
	'id'    => 'logistica-config-trazabilidad',
	'label' => __( 'Trazabilidad', 'logistica' ),
);
?>
<div class="logistica-config-section-board logistica-conversion-board is-nav-collapsed" data-conversion-board data-config-section-board>
	<aside class="logistica-conversion-nav" data-conversion-nav aria-label="<?php esc_attr_e( 'Secciones de configuración', 'logistica' ); ?>">
		<div class="logistica-conversion-nav__head">
			<span class="logistica-conversion-nav__title"><?php esc_html_e( 'Navegación', 'logistica' ); ?></span>
			<button
				type="button"
				class="logistica-conversion-nav__toggle"
				data-action="toggle-conversion-nav"
				aria-expanded="false"
				aria-controls="logistica-config-section-nav-list"
				title="<?php esc_attr_e( 'Ocultar menú', 'logistica' ); ?>"
			>
				<span aria-hidden="true">&lsaquo;</span>
				<span class="screen-reader-text"><?php esc_html_e( 'Ocultar navegación de configuración', 'logistica' ); ?></span>
			</button>
		</div>
		<nav id="logistica-config-section-nav-list" data-logistica-config-nav>
			<ul class="logistica-conversion-nav__list">
				<?php foreach ( $config_nav_sections as $config_nav_section ) : ?>
					<li>
						<a
							class="logistica-conversion-nav__link"
							href="#<?php echo esc_attr( $config_nav_section['id'] ); ?>"
							data-config-section-nav="<?php echo esc_attr( $config_nav_section['id'] ); ?>"
						><?php echo esc_html( $config_nav_section['label'] ); ?></a>
					</li>
				<?php endforeach; ?>
			</ul>
		</nav>
	</aside>

	<div class="logistica-config-section-main">
		<button
			type="button"
			class="logistica-conversion-nav-reopen"
			data-action="toggle-conversion-nav"
			aria-expanded="false"
			hidden
		>
			<span aria-hidden="true">&#9776;</span>
			<?php esc_html_e( 'Mostrar menú', 'logistica' ); ?>
		</button>

		<div class="logistica-configuracion-tab">
	<?php if ( isset( $_GET['logistica_status'] ) && 'menu_order_saved' === $_GET['logistica_status'] ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Orden del menú actualizado.', 'logistica' ); ?></p></div>
	<?php endif; ?>
	<?php if ( isset( $_GET['logistica_status'] ) && 'menu_saved' === $_GET['logistica_status'] ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Menú del panel público actualizado.', 'logistica' ); ?></p></div>
	<?php endif; ?>
	<?php if ( isset( $_GET['logistica_status'] ) && 'roles_saved' === $_GET['logistica_status'] ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Roles y permisos actualizados.', 'logistica' ); ?></p></div>
	<?php endif; ?>
	<?php if ( isset( $_GET['logistica_status'] ) && 'user_deleted' === $_GET['logistica_status'] ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Usuario enviado a la papelera de trazabilidad. Puedes restaurarlo desde la sección Trazabilidad.', 'logistica' ); ?></p></div>
	<?php endif; ?>
	<?php
	$user_delete_errors = array(
		'self_delete'     => __( 'No puedes eliminar tu propio usuario.', 'logistica' ),
		'last_admin'      => __( 'No puedes eliminar el último administrador del sistema.', 'logistica' ),
		'already_deleted' => __( 'El usuario ya está en la papelera.', 'logistica' ),
		'not_found'       => __( 'Usuario no encontrado.', 'logistica' ),
		'forbidden'       => __( 'No tienes permisos para eliminar usuarios.', 'logistica' ),
		'unavailable'     => __( 'La eliminación de usuarios no está disponible.', 'logistica' ),
	);
	if ( isset( $_GET['logistica_error'] ) ) {
		$user_delete_error = sanitize_key( wp_unslash( (string) $_GET['logistica_error'] ) );
		if ( isset( $user_delete_errors[ $user_delete_error ] ) ) :
			?>
		<div class="notice notice-error is-dismissible"><p><?php echo esc_html( $user_delete_errors[ $user_delete_error ] ); ?></p></div>
			<?php
		endif;
	}
	?>

	<header class="logistica-configuracion-tab__intro">
		<h2><?php esc_html_e( 'Configuración general', 'logistica' ); ?></h2>
		<p class="description">
			<?php if ( defined( 'LOGISTICA_STANDALONE' ) && LOGISTICA_STANDALONE ) : ?>
				<?php esc_html_e( 'Gestiona el menú del panel público y los permisos por rol.', 'logistica' ); ?>
			<?php else : ?>
				<?php esc_html_e( 'Gestiona el acceso al panel de operaciones, el menú público legacy y los permisos por rol.', 'logistica' ); ?>
			<?php endif; ?>
		</p>
	</header>

	<?php if ( ! defined( 'LOGISTICA_STANDALONE' ) || ! LOGISTICA_STANDALONE ) : ?>
	<section id="logistica-config-operaciones" class="logistica-configuracion-card logistica-configuracion-card--operations logistica-configuracion-section">
		<div class="logistica-configuracion-card__head">
			<h3><?php esc_html_e( 'Panel de operaciones', 'logistica' ); ?></h3>
			<p class="description">
				<?php esc_html_e( 'Página principal del equipo JB. Los usuarios operativos entran aquí sin acceder al escritorio de WordPress.', 'logistica' ); ?>
			</p>
		</div>
		<div class="logistica-configuracion-card__body">
			<?php if ( $backend_page_url ) : ?>
				<p class="logistica-configuracion-card__links">
					<a class="button button-secondary" href="<?php echo esc_url( $backend_page_url ); ?>" target="_blank" rel="noopener noreferrer">
						<?php esc_html_e( 'Abrir operaciones', 'logistica' ); ?>
					</a>
					<a class="button button-link" href="<?php echo esc_url( $config_panel_url ); ?>">
						<?php esc_html_e( 'Abrir configuración en el sitio', 'logistica' ); ?>
					</a>
				</p>
				<p class="description">
					<code><?php echo esc_html( wp_parse_url( $backend_page_url, PHP_URL_PATH ) ?: $backend_page_url ); ?></code>
				</p>
			<?php else : ?>
				<p class="description"><?php esc_html_e( 'Aún no hay página de operaciones asignada. Configúrala en la sección «Roles y permisos».', 'logistica' ); ?></p>
			<?php endif; ?>
		</div>
	</section>
	<?php endif; ?>

	<section id="logistica-config-menu-order" class="logistica-configuracion-card logistica-configuracion-card--menu-order logistica-configuracion-section">
		<div class="logistica-configuracion-card__head">
			<h3><?php esc_html_e( 'Orden del menú', 'logistica' ); ?></h3>
			<p class="description">
				<?php esc_html_e( 'Arrastra las secciones o usa las flechas para definir el orden del menú lateral en el panel de operaciones (jb-planeacion-backend).', 'logistica' ); ?>
			</p>
		</div>
		<div class="logistica-configuracion-card__body">
			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="logistica-menu-order-form">
				<input type="hidden" name="action" value="logistica_save_operations_menu_order">
				<input type="hidden" name="logistica_redirect_to" value="<?php echo esc_url( $config_tab_url ); ?>">
				<?php wp_nonce_field( 'logistica_save_operations_menu_order' ); ?>

				<ol class="logistica-menu-order-list" data-menu-order-list>
					<?php foreach ( $menu_order_tabs as $slug => $label ) : ?>
						<li class="logistica-menu-order-list__item" data-menu-order-item draggable="true">
							<span class="logistica-menu-order-list__handle dashicons dashicons-menu" aria-hidden="true"></span>
							<span class="logistica-menu-order-list__label"><?php echo esc_html( $label ); ?></span>
							<input type="hidden" name="menu_order[]" value="<?php echo esc_attr( $slug ); ?>">
							<span class="logistica-menu-order-list__actions">
								<button type="button" class="button button-small" data-menu-order-action="up" aria-label="<?php esc_attr_e( 'Subir', 'logistica' ); ?>">&#8593;</button>
								<button type="button" class="button button-small" data-menu-order-action="down" aria-label="<?php esc_attr_e( 'Bajar', 'logistica' ); ?>">&#8595;</button>
							</span>
						</li>
					<?php endforeach; ?>
				</ol>

				<p class="logistica-configuracion-card__actions">
					<button class="button button-primary" type="submit"><?php esc_html_e( 'Guardar orden del menú', 'logistica' ); ?></button>
				</p>
			</form>
		</div>
	</section>

	<section id="logistica-config-panel-publico" class="logistica-configuracion-card logistica-configuracion-card--legacy logistica-configuracion-section">
		<div class="logistica-configuracion-card__head">
			<h3><?php esc_html_e( 'Panel público (legacy)', 'logistica' ); ?></h3>
			<p class="description">
				<?php if ( defined( 'LOGISTICA_STANDALONE' ) && LOGISTICA_STANDALONE ) : ?>
					<?php esc_html_e( 'Configura las pestañas visibles en el panel público.', 'logistica' ); ?>
				<?php else : ?>
					<?php
					echo wp_kses_post(
						sprintf(
							/* translators: 1: shortcode, 2: backend slug */
							__( 'Opcional: página con shortcode %1$s. El panel principal de operaciones es %2$s.', 'logistica' ),
							'<code>[logistica_panel]</code>',
							'<code>jb-planeacion-backend</code>'
						)
					);
					?>
				<?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-frontend-menu-form">
				<input type="hidden" name="action" value="logistica_save_frontend_menu">
				<input type="hidden" name="logistica_redirect_to" value="<?php echo esc_url( $config_tab_url ); ?>">
				<?php wp_nonce_field( 'logistica_save_frontend_menu' ); ?>

				<?php if ( defined( 'LOGISTICA_STANDALONE' ) && LOGISTICA_STANDALONE ) : ?>
					<input type="hidden" name="frontend_page_id" value="<?php echo esc_attr( (string) max( 2, (int) $frontend_page_id ) ); ?>">
				<?php else : ?>
				<div class="logistica-frontend-page-picker">
					<label for="logistica-frontend-page-id-config">
						<strong><?php esc_html_e( 'Página del inventario', 'logistica' ); ?></strong>
					</label>
					<?php
					wp_dropdown_pages(
						array(
							'name'              => 'frontend_page_id',
							'id'                => 'logistica-frontend-page-id-config',
							'selected'          => $frontend_page_id,
							'show_option_none'  => __( '— Seleccionar página —', 'logistica' ),
							'option_none_value' => '0',
						)
					);
					?>
					<?php if ( $frontend_page_url ) : ?>
						<p class="description">
							<a href="<?php echo esc_url( $frontend_page_url ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Ver página', 'logistica' ); ?></a>
						</p>
					<?php endif; ?>
				</div>
				<?php endif; ?>

				<fieldset class="logistica-configuracion-menu-fieldset">
					<legend class="screen-reader-text"><?php esc_html_e( 'Secciones visibles en el panel público', 'logistica' ); ?></legend>
					<p class="description logistica-configuracion-menu-fieldset__hint">
						<?php esc_html_e( 'Marca las pestañas que aparecerán en el menú del panel público. Debe quedar al menos una activa.', 'logistica' ); ?>
					</p>
					<div class="logistica-frontend-menu-picker logistica-frontend-menu-picker--config" role="group">
						<?php foreach ( $menu_choices as $slug => $label ) : ?>
							<label class="logistica-frontend-menu-picker__item">
								<input
									type="checkbox"
									name="frontend_menu_tabs[]"
									value="<?php echo esc_attr( $slug ); ?>"
									<?php checked( in_array( $slug, $frontend_menu_tabs, true ) ); ?>
								/>
								<span><?php echo esc_html( $label ); ?></span>
							</label>
						<?php endforeach; ?>
					</div>
				</fieldset>

				<p class="logistica-configuracion-card__actions">
					<button class="button button-primary" type="submit"><?php esc_html_e( 'Guardar panel público', 'logistica' ); ?></button>
				</p>
			</form>
		</div>
	</section>

	<?php include LOGISTICA_PLUGIN_DIR . 'admin/views/partials/roles-settings.php'; ?>

	<section id="logistica-config-sistema" class="logistica-configuracion-card logistica-configuracion-card--system logistica-configuracion-section">
		<div class="logistica-configuracion-card__head">
			<h3><?php esc_html_e( 'Información del sistema', 'logistica' ); ?></h3>
			<p class="description"><?php esc_html_e( 'Referencia técnica del plugin (solo lectura).', 'logistica' ); ?></p>
		</div>
		<div class="logistica-configuracion-card__body">
			<div class="logistica-table-wrap">
				<table class="widefat striped logistica-configuracion-system-table">
					<tbody>
						<tr>
							<th scope="row"><?php esc_html_e( 'Versión', 'logistica' ); ?></th>
							<td><?php echo esc_html( LOGISTICA_VERSION ); ?></td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Panel operativo', 'logistica' ); ?></th>
							<td>
								<?php if ( $backend_page_url ) : ?>
									<a href="<?php echo esc_url( $backend_page_url ); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html( $backend_page_url ); ?></a>
								<?php else : ?>
									<?php esc_html_e( 'Sin asignar', 'logistica' ); ?>
								<?php endif; ?>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Tabla inventario bodega', 'logistica' ); ?></th>
							<td><code><?php echo esc_html( Logistica_Database::table( 'inventario_bodega' ) ); ?></code></td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Tabla conversiones', 'logistica' ); ?></th>
							<td><code><?php echo esc_html( Logistica_Database::table( 'conversiones' ) ); ?></code></td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Tabla auditoría', 'logistica' ); ?></th>
							<td><code><?php echo esc_html( Logistica_Database::table( 'auditoria' ) ); ?></code></td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Tabla papelera', 'logistica' ); ?></th>
							<td><code><?php echo esc_html( Logistica_Database::table( 'papelera' ) ); ?></code></td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Tabla versiones', 'logistica' ); ?></th>
							<td><code><?php echo esc_html( Logistica_Database::table( 'versiones' ) ); ?></code></td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>
	</section>

	<?php require LOGISTICA_PLUGIN_DIR . 'admin/views/partials/lifecycle-trazabilidad.php'; ?>
		</div>
	</div>
</div>
