<?php
/**
 * Configuración de la pestaña Ayuda.
 *
 * @package Logistica
 */

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

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

$help_settings     = Logistica_Settings::get_help_settings();
$content_mode      = (string) ( $help_settings['content_mode'] ?? 'default' );
$sections_json     = (string) ( $help_settings['sections_json'] ?? '' );
$config_tab_url    = logistica_config_panel_url( 'logistica-ayuda' );
$operations_url    = logistica_operations_panel_url( 'logistica-ayuda' );
$default_json      = wp_json_encode( Logistica_Help::default_sections(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );

if ( '' === trim( $sections_json ) ) {
	$sections_json = $default_json;
}
?>
<?php if ( isset( $_GET['logistica_status'] ) && 'help_saved' === $_GET['logistica_status'] ) : ?>
	<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Contenido de ayuda actualizado.', 'logistica' ); ?></p></div>
<?php endif; ?>

<section class="logistica-panel logistica-help-config">
	<header class="logistica-page-toolbar__intro">
		<h2><?php esc_html_e( 'Ayuda del sistema', 'logistica' ); ?></h2>
		<p class="description">
			<?php esc_html_e( 'Personaliza el encabezado y el contenido que ven los usuarios en la pestaña Ayuda.', 'logistica' ); ?>
			<a href="<?php echo esc_url( $operations_url ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Vista previa en operaciones', 'logistica' ); ?></a>
		</p>
	</header>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="logistica-help-config-form">
		<input type="hidden" name="action" value="logistica_save_help_settings">
		<input type="hidden" name="logistica_redirect_to" value="<?php echo esc_url( $config_tab_url ); ?>">
		<?php wp_nonce_field( 'logistica_save_help_settings' ); ?>

		<div class="logistica-configuracion-card logistica-help-config__card">
			<div class="logistica-configuracion-card__head">
				<h3><?php esc_html_e( 'Encabezado', 'logistica' ); ?></h3>
			</div>
			<div class="logistica-configuracion-card__body">
				<p>
					<label for="logistica-help-hero-title"><strong><?php esc_html_e( 'Título', 'logistica' ); ?></strong></label><br>
					<input type="text" class="large-text" id="logistica-help-hero-title" name="hero_title" value="<?php echo esc_attr( (string) ( $help_settings['hero_title'] ?? '' ) ); ?>" placeholder="<?php esc_attr_e( 'Ayuda de JB Planeación', 'logistica' ); ?>">
				</p>
				<p>
					<label for="logistica-help-hero-intro"><strong><?php esc_html_e( 'Descripción', 'logistica' ); ?></strong></label><br>
					<textarea class="large-text" id="logistica-help-hero-intro" name="hero_intro" rows="3" placeholder="<?php esc_attr_e( 'Guía completa para usar JB Planeación…', 'logistica' ); ?>"><?php echo esc_textarea( (string) ( $help_settings['hero_intro'] ?? '' ) ); ?></textarea>
				</p>
			</div>
		</div>

		<div class="logistica-configuracion-card logistica-help-config__card">
			<div class="logistica-configuracion-card__head">
				<h3><?php esc_html_e( 'Contenido de la guía', 'logistica' ); ?></h3>
				<p class="description"><?php esc_html_e( 'Elige cómo se muestran las secciones debajo del encabezado.', 'logistica' ); ?></p>
			</div>
			<div class="logistica-configuracion-card__body">
				<fieldset class="logistica-help-config__modes">
					<legend class="screen-reader-text"><?php esc_html_e( 'Modo de contenido', 'logistica' ); ?></legend>
					<label class="logistica-help-config__mode">
						<input type="radio" name="content_mode" value="default" <?php checked( $content_mode, 'default' ); ?> data-help-content-mode>
						<span>
							<strong><?php esc_html_e( 'Guía integrada del plugin', 'logistica' ); ?></strong>
							<small><?php esc_html_e( 'Índice y secciones predeterminadas (se actualizan con el plugin).', 'logistica' ); ?></small>
						</span>
					</label>
					<label class="logistica-help-config__mode">
						<input type="radio" name="content_mode" value="html" <?php checked( $content_mode, 'html' ); ?> data-help-content-mode>
						<span>
							<strong><?php esc_html_e( 'HTML personalizado', 'logistica' ); ?></strong>
							<small><?php esc_html_e( 'Reemplaza las secciones por tu propio contenido.', 'logistica' ); ?></small>
						</span>
					</label>
					<label class="logistica-help-config__mode">
						<input type="radio" name="content_mode" value="json" <?php checked( $content_mode, 'json' ); ?> data-help-content-mode>
						<span>
							<strong><?php esc_html_e( 'Secciones avanzadas (JSON)', 'logistica' ); ?></strong>
							<small><?php esc_html_e( 'Edita la estructura completa: títulos, listas y tablas.', 'logistica' ); ?></small>
						</span>
					</label>
				</fieldset>

				<div class="logistica-help-config__panel" data-help-panel="html" <?php echo 'html' === $content_mode ? '' : 'hidden'; ?>>
					<label for="logistica-help-custom-html"><strong><?php esc_html_e( 'Contenido HTML', 'logistica' ); ?></strong></label>
					<?php
					wp_editor(
						(string) ( $help_settings['custom_html'] ?? '' ),
						'logistica_help_custom_html',
						array(
							'textarea_name' => 'custom_html',
							'textarea_rows' => 14,
							'media_buttons' => true,
							'teeny'         => false,
							'quicktags'     => true,
						)
					);
					?>
				</div>

				<div class="logistica-help-config__panel" data-help-panel="json" <?php echo 'json' === $content_mode ? '' : 'hidden'; ?>>
					<p class="description">
						<?php esc_html_e( 'Cada sección puede incluir id, title, intro, list, notes, tab_slug, table y examples. Usa «Cargar predeterminado» para partir de la guía actual.', 'logistica' ); ?>
					</p>
					<p>
						<button type="button" class="button" data-help-load-default-json><?php esc_html_e( 'Cargar contenido predeterminado', 'logistica' ); ?></button>
					</p>
					<textarea class="large-text code logistica-help-config__json" id="logistica-help-sections-json" name="sections_json" rows="18" data-help-default-json="<?php echo esc_attr( $default_json ); ?>"><?php echo esc_textarea( $sections_json ); ?></textarea>
				</div>

				<div class="logistica-help-config__panel" data-help-panel="default" <?php echo 'default' === $content_mode ? '' : 'hidden'; ?>>
					<p class="description"><?php esc_html_e( 'Se mostrará la guía completa con índice y todas las secciones del plugin.', 'logistica' ); ?></p>
				</div>
			</div>
		</div>

		<p class="logistica-configuracion-card__actions">
			<button type="submit" class="button button-primary"><?php esc_html_e( 'Guardar ayuda', 'logistica' ); ?></button>
			<button type="submit" class="button" name="help_reset_defaults" value="1" onclick="return confirm('<?php echo esc_js( __( '¿Restaurar el contenido de ayuda predeterminado?', 'logistica' ) ); ?>');"><?php esc_html_e( 'Restaurar predeterminado', 'logistica' ); ?></button>
		</p>
	</form>
</section>

<script>
(function () {
	var form = document.querySelector('.logistica-help-config-form');
	if (!form) {
		return;
	}
	function syncPanels() {
		var mode = form.querySelector('input[name="content_mode"]:checked');
		var value = mode ? mode.value : 'default';
		form.querySelectorAll('[data-help-panel]').forEach(function (panel) {
			panel.hidden = panel.getAttribute('data-help-panel') !== value;
		});
	}
	form.querySelectorAll('[data-help-content-mode]').forEach(function (input) {
		input.addEventListener('change', syncPanels);
	});
	var loadBtn = form.querySelector('[data-help-load-default-json]');
	var jsonField = form.querySelector('#logistica-help-sections-json');
	if (loadBtn && jsonField) {
		loadBtn.addEventListener('click', function () {
			jsonField.value = jsonField.getAttribute('data-help-default-json') || '';
		});
	}
})();
</script>
