<?php
/**
 * Configuración administrativa del panel operativo (solo wp-admin).
 *
 * @package Logistica
 */

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

$compra_statuses   = Logistica_Settings::get_compra_statuses();
$panel_holidays     = Logistica_Settings::get_panel_holidays();

if ( ! logistica_is_tabbed_shell() ) {
	logistica_admin_header( __( 'Inicio', 'logistica' ) );
}
?>
<?php if ( isset( $_GET['logistica_status'] ) && 'panel_saved' === $_GET['logistica_status'] ) : ?>
	<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Configuración de Inicio guardada correctamente.', 'logistica' ); ?></p></div>
<?php endif; ?>

<section class="logistica-panel logistica-panel-admin-settings">
	<h2><?php esc_html_e( 'Cotizaciones y compras', 'logistica' ); ?></h2>
	<p><?php esc_html_e( 'Opciones del campo «Estado» al crear o modificar una cotización en Inicio.', 'logistica' ); ?></p>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="logistica-panel-compra-statuses-form">
		<input type="hidden" name="action" value="logistica_save_panel_settings">
		<?php wp_nonce_field( 'logistica_save_panel_settings' ); ?>

		<div class="logistica-table-wrap">
			<table class="widefat striped logistica-panel-compra-statuses-table" data-panel-compra-statuses-table>
				<thead>
					<tr>
						<th scope="col"><?php esc_html_e( 'Etiqueta visible', 'logistica' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Clave interna', 'logistica' ); ?></th>
						<th scope="col" class="logistica-panel-compra-statuses-table__actions"><?php esc_html_e( 'Acciones', 'logistica' ); ?></th>
					</tr>
				</thead>
				<tbody data-panel-compra-statuses-rows>
					<?php foreach ( $compra_statuses as $key => $label ) : ?>
						<tr data-panel-compra-status-row>
							<td>
								<label class="screen-reader-text" for="compra-status-label-<?php echo esc_attr( $key ); ?>"><?php esc_html_e( 'Etiqueta', 'logistica' ); ?></label>
								<input
									type="text"
									class="regular-text"
									id="compra-status-label-<?php echo esc_attr( $key ); ?>"
									name="compra_statuses[][label]"
									value="<?php echo esc_attr( $label ); ?>"
									required
								>
							</td>
							<td>
								<input type="hidden" name="compra_statuses[][key]" value="<?php echo esc_attr( $key ); ?>">
								<code><?php echo esc_html( $key ); ?></code>
							</td>
							<td class="logistica-panel-compra-statuses-table__actions">
								<button type="button" class="button button-link-delete" data-panel-compra-status-remove aria-label="<?php esc_attr_e( 'Eliminar estado', 'logistica' ); ?>">
									<?php esc_html_e( 'Eliminar', 'logistica' ); ?>
								</button>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		</div>

		<p class="logistica-panel-compra-statuses-form__tools">
			<button type="button" class="button" data-panel-compra-status-add><?php esc_html_e( 'Añadir estado', 'logistica' ); ?></button>
		</p>
		<p class="description"><?php esc_html_e( 'La clave interna se genera al guardar una fila nueva. Si cambias solo la etiqueta, las cotizaciones existentes conservan su estado.', 'logistica' ); ?></p>

		<h2><?php esc_html_e( 'Lista chequeo — festivos', 'logistica' ); ?></h2>
		<p><?php esc_html_e( 'Define qué días se marcan automáticamente como «Festivo» en el checklist. Si un usuario cambia un día a «Laborable» en el panel, esa elección prevalece hasta que vuelva a marcarlo como festivo.', 'logistica' ); ?></p>

		<fieldset class="logistica-panel-holidays-options">
			<label>
				<input type="checkbox" name="panel_holidays[auto_sundays]" value="1" <?php checked( ! empty( $panel_holidays['auto_sundays'] ) ); ?>>
				<?php esc_html_e( 'Marcar todos los domingos como festivo', 'logistica' ); ?>
			</label>
		</fieldset>

		<h3><?php esc_html_e( 'Festivos adicionales', 'logistica' ); ?></h3>
		<p class="description"><?php esc_html_e( 'Añade cierres o días especiales de la empresa (paros, jornadas, etc.).', 'logistica' ); ?></p>

		<div class="logistica-table-wrap">
			<table class="widefat striped logistica-panel-holidays-table" data-panel-extra-holidays-table>
				<thead>
					<tr>
						<th scope="col"><?php esc_html_e( 'Fecha', 'logistica' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Descripción (opcional)', 'logistica' ); ?></th>
						<th scope="col" class="logistica-panel-compra-statuses-table__actions"><?php esc_html_e( 'Acciones', 'logistica' ); ?></th>
					</tr>
				</thead>
				<tbody data-panel-extra-holidays-rows>
					<?php foreach ( (array) ( $panel_holidays['extra_holidays'] ?? array() ) as $index => $row ) : ?>
						<tr data-panel-extra-holiday-row>
							<td>
								<input type="date" name="panel_holidays[extra_holidays][<?php echo esc_attr( (string) $index ); ?>][date]" value="<?php echo esc_attr( $row['date'] ?? '' ); ?>" required>
							</td>
							<td>
								<input type="text" class="regular-text" name="panel_holidays[extra_holidays][<?php echo esc_attr( (string) $index ); ?>][label]" value="<?php echo esc_attr( $row['label'] ?? '' ); ?>" placeholder="<?php esc_attr_e( 'Ej. Paro planta', 'logistica' ); ?>">
							</td>
							<td class="logistica-panel-compra-statuses-table__actions">
								<button type="button" class="button button-link-delete" data-panel-extra-holiday-remove><?php esc_html_e( 'Eliminar', 'logistica' ); ?></button>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<p class="logistica-panel-compra-statuses-form__tools">
			<button type="button" class="button" data-panel-extra-holiday-add><?php esc_html_e( 'Añadir festivo', 'logistica' ); ?></button>
		</p>

		<p><button type="submit" class="button button-primary"><?php esc_html_e( 'Guardar configuración', 'logistica' ); ?></button></p>
	</form>
</section>

<template id="logistica-panel-compra-status-row-template">
	<tr data-panel-compra-status-row>
		<td>
			<input type="text" class="regular-text" name="compra_statuses[][label]" value="" required placeholder="<?php esc_attr_e( 'Ej. En tránsito', 'logistica' ); ?>">
		</td>
		<td>
			<input type="hidden" name="compra_statuses[][key]" value="">
			<span class="description"><?php esc_html_e( 'Se asigna al guardar', 'logistica' ); ?></span>
		</td>
		<td class="logistica-panel-compra-statuses-table__actions">
			<button type="button" class="button button-link-delete" data-panel-compra-status-remove aria-label="<?php esc_attr_e( 'Eliminar estado', 'logistica' ); ?>">
				<?php esc_html_e( 'Eliminar', 'logistica' ); ?>
			</button>
		</td>
	</tr>
</template>

<template id="logistica-panel-extra-holiday-row-template">
	<tr data-panel-extra-holiday-row>
		<td><input type="date" name="panel_holidays[extra_holidays][][date]" value="" required></td>
		<td><input type="text" class="regular-text" name="panel_holidays[extra_holidays][][label]" value="" placeholder="<?php esc_attr_e( 'Ej. Paro planta', 'logistica' ); ?>"></td>
		<td class="logistica-panel-compra-statuses-table__actions">
			<button type="button" class="button button-link-delete" data-panel-extra-holiday-remove><?php esc_html_e( 'Eliminar', 'logistica' ); ?></button>
		</td>
	</tr>
</template>

<script>
(function () {
	'use strict';

	var table = document.querySelector('[data-panel-compra-statuses-table]');
	if (!table) {
		return;
	}

	var tbody = table.querySelector('[data-panel-compra-statuses-rows]');
	var template = document.getElementById('logistica-panel-compra-status-row-template');

	function bindRow(row) {
		var removeBtn = row.querySelector('[data-panel-compra-status-remove]');
		if (!removeBtn || removeBtn.dataset.bound === '1') {
			return;
		}
		removeBtn.dataset.bound = '1';
		removeBtn.addEventListener('click', function () {
			var rows = tbody.querySelectorAll('[data-panel-compra-status-row]');
			if (rows.length <= 1) {
				window.alert('<?php echo esc_js( __( 'Debe quedar al menos un estado.', 'logistica' ) ); ?>');
				return;
			}
			row.remove();
		});
	}

	tbody.querySelectorAll('[data-panel-compra-status-row]').forEach(bindRow);

	var addBtn = document.querySelector('[data-panel-compra-status-add]');
	if (addBtn && template) {
		addBtn.addEventListener('click', function () {
			var clone = template.content.cloneNode(true);
			var row = clone.querySelector('[data-panel-compra-status-row]');
			tbody.appendChild(clone);
			if (row) {
				bindRow(row);
				var input = row.querySelector('input[type="text"]');
				if (input) {
					input.focus();
				}
			}
		});
	}

	function bindHolidayRow(row, removeSelector) {
		var removeBtn = row.querySelector(removeSelector);
		if (!removeBtn || removeBtn.dataset.bound === '1') {
			return;
		}
		removeBtn.dataset.bound = '1';
		removeBtn.addEventListener('click', function () {
			row.remove();
		});
	}

	function initHolidayTable(tableSelector, tbodySelector, addSelector, templateId, rowSelector, removeSelector) {
		var table = document.querySelector(tableSelector);
		var template = document.getElementById(templateId);
		if (!table || !template) {
			return;
		}

		var tbody = table.querySelector(tbodySelector);
		if (!tbody) {
			return;
		}

		tbody.querySelectorAll(rowSelector).forEach(function (row) {
			bindHolidayRow(row, removeSelector);
		});

		var addBtn = document.querySelector(addSelector);
		if (!addBtn) {
			return;
		}

		addBtn.addEventListener('click', function () {
			var clone = template.content.cloneNode(true);
			var row = clone.querySelector(rowSelector);
			tbody.appendChild(clone);
			if (row) {
				bindHolidayRow(row, removeSelector);
				var input = row.querySelector('input');
				if (input) {
					input.focus();
				}
			}
		});
	}

	initHolidayTable(
		'[data-panel-extra-holidays-table]',
		'[data-panel-extra-holidays-rows]',
		'[data-panel-extra-holiday-add]',
		'logistica-panel-extra-holiday-row-template',
		'[data-panel-extra-holiday-row]',
		'[data-panel-extra-holiday-remove]'
	);
})();
</script>
<?php
if ( ! logistica_is_tabbed_shell() ) {
	logistica_admin_footer();
}
