<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<section class="panel">
	<form method="post" action="<?php echo site_url('configuracion/ventas'); ?>" autocomplete="off" style="display:grid; gap:18px;">
		<div class="actions" style="justify-content:flex-start; margin-top:0; margin-bottom:4px;">
			<a class="btn btn-outline" href="<?php echo site_url('configuracion'); ?>">Regresar</a>
		</div>

		<h2 style="margin-bottom:0;">Ventas</h2>
		<p>Define cuantas ventas del dia puede ver la persona en el modulo de ventas y agrega mensajes motivacionales segun el minimo de ventas.</p>

		<div class="field" style="margin-top:0;">
			<label for="sales_daily_limit">Cantidad de ventas diarias visibles</label>
			<input
				id="sales_daily_limit"
				type="number"
				step="1"
				min="1"
				name="sales_daily_limit"
				value="<?php echo htmlspecialchars((string)$sales_daily_limit, ENT_QUOTES, 'UTF-8'); ?>"
			/>
		</div>

		<div style="display:grid; gap:12px;">
			<div style="display:flex; align-items:center; justify-content:space-between; gap:12px;">
				<h3 style="margin:0;">Mensajes motivacionales</h3>
				<button class="btn btn-outline" type="button" id="add-sales-message">Agregar mensaje</button>
			</div>
			<div id="sales-messages-list" data-input-name="sales_messages[]" style="display:grid; gap:10px;">
				<div class="message-empty" style="<?php echo empty($sales_messages) ? '' : 'display:none;'; ?> padding:14px 16px; border-radius:16px; background:var(--panel); color:var(--muted);">
					No hay mensajes cargados.
				</div>
				<?php foreach ($sales_messages as $message) { ?>
					<div class="message-row" style="display:flex; align-items:flex-start; justify-content:space-between; gap:12px; padding:14px 16px; border-radius:16px; background:var(--panel); box-shadow:0 10px 20px rgba(20,41,64,0.06);">
						<div style="flex:1; display:grid; gap:6px;">
							<div class="message-text" style="color:var(--ink); font-size:calc(0.98rem * var(--app-text-size));">
								<?php echo htmlspecialchars(isset($message['text']) ? $message['text'] : '', ENT_QUOTES, 'UTF-8'); ?>
							</div>
							<div class="message-min-sales" style="font-size:calc(0.82rem * var(--app-text-size)); color:var(--muted); font-weight:700;">
								Minimo de ventas: <?php echo (int)(isset($message['min_sales']) ? $message['min_sales'] : 0); ?>
							</div>
						</div>
						<div style="display:flex; gap:8px;">
							<button class="btn btn-outline edit-message-btn" type="button" style="padding:10px 14px;">Editar</button>
						</div>
						<input type="hidden" name="sales_messages[]" value="<?php echo htmlspecialchars(json_encode($message), ENT_QUOTES, 'UTF-8'); ?>" />
					</div>
				<?php } ?>
			</div>
		</div>

		<div class="actions" style="justify-content:flex-end;">
			<button class="btn" type="submit">Guardar</button>
		</div>
	</form>
</section>

<div id="sales-message-modal" class="modal-backdrop" style="display:none;">
	<div class="modal-card" style="width:min(560px, calc(100vw - 28px));">
		<h3 id="sales-message-modal-title" style="margin-bottom:12px;">Agregar mensaje</h3>
		<div class="field" style="margin-top:0;">
			<label for="sales-message-input">Mensaje</label>
			<textarea id="sales-message-input" rows="4" placeholder="Escribe un mensaje motivacional"></textarea>
		</div>
		<div class="field" style="margin-top:0;">
			<label for="sales-message-min-sales">Minimo de ventas</label>
			<input id="sales-message-min-sales" type="number" min="0" step="1" value="0" />
		</div>
		<div class="actions" style="justify-content:flex-end;">
			<button class="btn btn-outline" type="button" id="sales-message-cancel">Cancelar</button>
			<button class="btn" type="button" id="sales-message-save">Guardar</button>
		</div>
	</div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
	var modal = document.getElementById('sales-message-modal');
	var modalTitle = document.getElementById('sales-message-modal-title');
	var modalInput = document.getElementById('sales-message-input');
	var modalMinSales = document.getElementById('sales-message-min-sales');
	var modalCancel = document.getElementById('sales-message-cancel');
	var modalSave = document.getElementById('sales-message-save');
	var addSalesButton = document.getElementById('add-sales-message');
	var currentList = null;
	var currentRow = null;

	var updateEmptyState = function (list) {
		if (!list) {
			return;
		}
		var empty = list.querySelector('.message-empty');
		var rows = list.querySelectorAll('.message-row');
		if (empty) {
			empty.style.display = rows.length ? 'none' : '';
		}
	};

	var openModal = function (title, list, row) {
		currentList = list;
		currentRow = row || null;
		if (modalTitle) {
			modalTitle.textContent = title;
		}
		if (modalInput) {
			if (currentRow) {
				var hidden = currentRow.querySelector('input[type="hidden"]');
				var payload = hidden ? JSON.parse(hidden.value || '{}') : {};
				modalInput.value = payload.text || '';
				if (modalMinSales) {
					modalMinSales.value = payload.min_sales || 0;
				}
			} else {
				modalInput.value = '';
				if (modalMinSales) {
					modalMinSales.value = 0;
				}
			}
			modalInput.focus();
			modalInput.select();
		}
		if (modal) {
			modal.style.display = 'flex';
		}
	};

	var closeModal = function () {
		if (modal) {
			modal.style.display = 'none';
		}
		currentList = null;
		currentRow = null;
	};

	var buildRow = function (text, minSales, inputName) {
		var row = document.createElement('div');
		row.className = 'message-row';
		row.style.display = 'flex';
		row.style.alignItems = 'flex-start';
		row.style.justifyContent = 'space-between';
		row.style.gap = '12px';
		row.style.padding = '14px 16px';
		row.style.borderRadius = '16px';
		row.style.background = 'var(--panel)';
		row.style.boxShadow = '0 10px 20px rgba(20,41,64,0.06)';

		var content = document.createElement('div');
		content.style.flex = '1';
		content.style.display = 'grid';
		content.style.gap = '6px';

		var textNode = document.createElement('div');
		textNode.className = 'message-text';
		textNode.style.color = 'var(--ink)';
		textNode.style.fontSize = 'calc(0.98rem * var(--app-text-size))';
		textNode.textContent = text;
		content.appendChild(textNode);

		var minNode = document.createElement('div');
		minNode.className = 'message-min-sales';
		minNode.style.fontSize = 'calc(0.82rem * var(--app-text-size))';
		minNode.style.color = 'var(--muted)';
		minNode.style.fontWeight = '700';
		minNode.textContent = 'Minimo de ventas: ' + minSales;
		content.appendChild(minNode);

		row.appendChild(content);

		var actions = document.createElement('div');
		actions.style.display = 'flex';
		actions.style.gap = '8px';
		var editButton = document.createElement('button');
		editButton.className = 'btn btn-outline edit-message-btn';
		editButton.type = 'button';
		editButton.style.padding = '10px 14px';
		editButton.textContent = 'Editar';
		actions.appendChild(editButton);
		row.appendChild(actions);

		var hidden = document.createElement('input');
		hidden.type = 'hidden';
		hidden.name = inputName;
		hidden.value = JSON.stringify({ text: text, min_sales: minSales });
		row.appendChild(hidden);

		return row;
	};

	if (addSalesButton) {
		addSalesButton.addEventListener('click', function () {
			openModal('Agregar mensaje', document.getElementById('sales-messages-list'), null);
		});
	}

	document.addEventListener('click', function (event) {
		var button = event.target.closest('.edit-message-btn');
		if (!button) {
			return;
		}
		var row = button.closest('.message-row');
		var list = button.closest('[data-input-name]');
		if (!row || !list) {
			return;
		}
		openModal('Editar mensaje', list, row);
	});

	if (modalCancel) {
		modalCancel.addEventListener('click', closeModal);
	}

	if (modal) {
		modal.addEventListener('click', function (event) {
			if (event.target === modal) {
				closeModal();
			}
		});
	}

	if (modalSave) {
		modalSave.addEventListener('click', function () {
			if (!currentList || !modalInput) {
				return;
			}

			var text = modalInput.value.trim();
			var minSales = modalMinSales ? parseInt(modalMinSales.value || '0', 10) : 0;
			var inputName = currentList.getAttribute('data-input-name');
			if (isNaN(minSales) || minSales < 0) {
				minSales = 0;
			}

			if (currentRow) {
				if (text === '') {
					currentRow.remove();
				} else {
					var textNode = currentRow.querySelector('.message-text');
					var minNode = currentRow.querySelector('.message-min-sales');
					var hidden = currentRow.querySelector('input[type="hidden"]');
					if (textNode) {
						textNode.textContent = text;
					}
					if (minNode) {
						minNode.textContent = 'Minimo de ventas: ' + minSales;
					}
					if (hidden) {
						hidden.value = JSON.stringify({ text: text, min_sales: minSales });
					}
				}
			} else if (text !== '') {
				currentList.appendChild(buildRow(text, minSales, inputName));
			}

			updateEmptyState(currentList);
			closeModal();
		});
	}

	Array.prototype.slice.call(document.querySelectorAll('[data-input-name]')).forEach(updateEmptyState);
});
</script>
