<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php
$rule = is_array($rule) ? $rule : array();
$selected_template_id = (int) set_value('template_id', isset($rule['template_id']) ? $rule['template_id'] : 0);
$selected_assignment_mode = set_value('assignment_mode', isset($rule['assignment_mode']) ? $rule['assignment_mode'] : 'employee');
$selected_group_mode = set_value('group_distribution_mode', isset($rule['group_distribution_mode']) ? $rule['group_distribution_mode'] : 'all_members');
$selected_distribution = set_value('distribution_algorithm', isset($rule['distribution_algorithm']) ? $rule['distribution_algorithm'] : 'random');
$selected_recurrence = set_value('recurrence_type', isset($rule['recurrence_type']) ? $rule['recurrence_type'] : 'one_time');
$selected_ignored_item_ids = !empty($_POST['ignored_item_ids']) ? array_map('intval', (array) $_POST['ignored_item_ids']) : $ignored_item_ids;
$template_items_map = array();
foreach ($templates as $template)
{
	$template_items_map[(int) $template['id']] = array();
	foreach ((array) (isset($template['assignable_items']) ? $template['assignable_items'] : array()) as $item)
	{
		$template_items_map[(int) $template['id']][] = array(
			'id' => isset($item['id']) ? (int) $item['id'] : 0,
			'name' => isset($item['name']) ? $item['name'] : '',
			'is_child' => !empty($item['parent_item_id']) ? 1 : 0,
		);
	}
}
?>
<style>
.task-selector-list {
	display: grid;
	gap: 10px;
	padding: 14px;
	border-radius: 18px;
	background: var(--card);
}

.task-selector-option {
	display: grid;
	grid-template-columns: 28px minmax(0, 1fr);
	align-items: center;
	gap: 14px;
	padding: 12px 14px;
	border-radius: 18px;
	background: rgba(255, 255, 255, 0.78);
	border: 1px solid rgba(77, 116, 195, 0.12);
	justify-content: start;
}

.task-selector-option.is-selected {
	background: rgba(77, 116, 195, 0.08);
}

.task-selector-box {
	position: relative;
	width: 28px;
	height: 28px;
	flex: 0 0 28px;
}

.task-selector-box input {
	position: absolute;
	inset: 0;
	opacity: 0;
	margin: 0;
	cursor: pointer;
}

.task-selector-mark {
	width: 28px;
	height: 28px;
	border-radius: 10px;
	border: 2px solid rgba(77, 116, 195, 0.35);
	background: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: inset 0 1px 2px rgba(20, 41, 64, 0.08);
	transition: all 0.18s ease;
}

.task-selector-mark::after {
	content: '';
	width: 8px;
	height: 14px;
	border-right: 3px solid transparent;
	border-bottom: 3px solid transparent;
	transform: rotate(45deg) translate(-1px, -1px);
	transition: all 0.18s ease;
}

.task-selector-box input:checked + .task-selector-mark {
	background: var(--theme);
	border-color: var(--theme);
	box-shadow: 0 10px 18px rgba(77, 116, 195, 0.22);
}

.task-selector-box input:checked + .task-selector-mark::after {
	border-right-color: #fff;
	border-bottom-color: #fff;
}

.task-selector-label {
	display: block;
	font-size: calc(0.96rem * var(--app-text-size));
	font-weight: 800;
	color: var(--ink);
	line-height: 1.25;
	text-align: left;
}

.task-selector-content {
	display: block;
	min-width: 0;
}
</style>
<section class="panel">
	<form method="post" action="" 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/tareas'); ?>">Regresar</a>
		</div>

		<h2 style="margin-bottom:0;"><?php echo !empty($rule['id']) ? 'Editar tarea' : 'Nueva tarea'; ?></h2>
		<?php if (validation_errors()) { ?>
			<div style="padding:12px 14px; border-radius:16px; background:#fdecec; color:#8a1f1f; font-weight:700;">
				<?php echo validation_errors('', ' '); ?>
			</div>
		<?php } ?>

		<div class="field" style="margin-top:0;">
			<label for="title">Nombre de la tarea</label>
			<input id="title" type="text" name="title" value="<?php echo htmlspecialchars(set_value('title', isset($rule['title']) ? $rule['title'] : ''), ENT_QUOTES, 'UTF-8'); ?>" placeholder="Ejemplo: Revisar vitrinas de apertura" />
		</div>

		<div class="field" style="margin-top:0;">
			<label for="template_id">Plantilla</label>
			<select id="template_id" name="template_id">
				<option value="">Selecciona una plantilla</option>
				<?php foreach ($templates as $template) { ?>
					<option value="<?php echo (int) $template['id']; ?>" <?php echo $selected_template_id === (int) $template['id'] ? 'selected' : ''; ?>>
						<?php echo htmlspecialchars($template['name'], ENT_QUOTES, 'UTF-8'); ?>
					</option>
				<?php } ?>
			</select>
		</div>

		<label style="display:flex; align-items:center; gap:10px; font-weight:700; color:var(--ink);">
			<input type="checkbox" name="is_active" value="1" <?php echo set_checkbox('is_active', '1', !isset($rule['is_active']) || !empty($rule['is_active'])); ?> />
			<span>Tarea activa</span>
		</label>

		<div class="field" style="margin-top:0;">
			<label for="assignment_mode">Asignar a</label>
			<select id="assignment_mode" name="assignment_mode">
				<option value="employee" <?php echo $selected_assignment_mode === 'employee' ? 'selected' : ''; ?>>Persona individual</option>
				<option value="group" <?php echo $selected_assignment_mode === 'group' ? 'selected' : ''; ?>>Grupo</option>
			</select>
		</div>

		<div class="field" id="employee-wrapper" style="margin-top:0; <?php echo $selected_assignment_mode === 'employee' ? '' : 'display:none;'; ?>">
			<label for="employee_id">Empleado</label>
			<select id="employee_id" name="employee_id">
				<option value="">Selecciona un empleado</option>
				<?php foreach ($employees as $employee) { ?>
					<option value="<?php echo (int) $employee['person_id']; ?>" <?php echo (int) set_value('employee_id', isset($rule['employee_id']) ? $rule['employee_id'] : 0) === (int) $employee['person_id'] ? 'selected' : ''; ?>>
						<?php echo htmlspecialchars($employee['full_name'], ENT_QUOTES, 'UTF-8'); ?>
					</option>
				<?php } ?>
			</select>
		</div>

		<div id="group-wrapper" style="<?php echo $selected_assignment_mode === 'group' ? '' : 'display:none;'; ?>">
			<div class="field" style="margin-top:0;">
				<label for="group_id">Grupo</label>
				<select id="group_id" name="group_id">
					<option value="">Selecciona un grupo</option>
					<?php foreach ($groups as $group) { ?>
						<option value="<?php echo (int) $group['id']; ?>" <?php echo (int) set_value('group_id', isset($rule['group_id']) ? $rule['group_id'] : 0) === (int) $group['id'] ? 'selected' : ''; ?>>
							<?php echo htmlspecialchars($group['name'], ENT_QUOTES, 'UTF-8'); ?>
						</option>
					<?php } ?>
				</select>
			</div>

			<div class="field" style="margin-top:0;">
				<label for="group_distribution_mode">Modo de grupo</label>
				<select id="group_distribution_mode" name="group_distribution_mode">
					<option value="all_members" <?php echo $selected_group_mode === 'all_members' ? 'selected' : ''; ?>>Asignar todas a todos</option>
					<option value="distributed" <?php echo $selected_group_mode === 'distributed' ? 'selected' : ''; ?>>Distribuir subtareas</option>
				</select>
			</div>

			<div class="field" id="distribution-wrapper" style="margin-top:0; <?php echo $selected_group_mode === 'distributed' ? '' : 'display:none;'; ?>">
				<label for="distribution_algorithm">Distribucion</label>
				<select id="distribution_algorithm" name="distribution_algorithm">
					<option value="random" <?php echo $selected_distribution === 'random' ? 'selected' : ''; ?>>Aleatoria</option>
					<option value="fair_rotation" <?php echo $selected_distribution === 'fair_rotation' ? 'selected' : ''; ?>>Rotacion justa</option>
				</select>
			</div>
		</div>

		<div class="field" style="margin-top:0;">
			<label for="recurrence_type">Tipo de tarea</label>
			<select id="recurrence_type" name="recurrence_type">
				<option value="one_time" <?php echo $selected_recurrence === 'one_time' ? 'selected' : ''; ?>>Unica</option>
				<option value="daily" <?php echo $selected_recurrence === 'daily' ? 'selected' : ''; ?>>Diaria</option>
				<option value="weekly" <?php echo $selected_recurrence === 'weekly' ? 'selected' : ''; ?>>Semanal</option>
				<option value="monthly" <?php echo $selected_recurrence === 'monthly' ? 'selected' : ''; ?>>Mensual</option>
				<option value="quarterly" <?php echo $selected_recurrence === 'quarterly' ? 'selected' : ''; ?>>Trimestral</option>
				<option value="semiannual" <?php echo $selected_recurrence === 'semiannual' ? 'selected' : ''; ?>>Semestral</option>
				<option value="annual" <?php echo $selected_recurrence === 'annual' ? 'selected' : ''; ?>>Anual</option>
				<option value="special_date" <?php echo $selected_recurrence === 'special_date' ? 'selected' : ''; ?>>Fecha especial</option>
			</select>
		</div>

		<div class="field" id="one-time-wrapper" style="margin-top:0; <?php echo $selected_recurrence === 'one_time' ? '' : 'display:none;'; ?>">
			<label for="one_time_date">Fecha unica</label>
			<input id="one_time_date" type="date" name="one_time_date" value="<?php echo htmlspecialchars(set_value('one_time_date', isset($rule['one_time_date']) ? $rule['one_time_date'] : ''), ENT_QUOTES, 'UTF-8'); ?>" />
		</div>

		<div id="range-wrapper" style="<?php echo in_array($selected_recurrence, array('daily', 'weekly', 'monthly', 'quarterly', 'semiannual', 'annual'), TRUE) ? '' : 'display:none;'; ?>">
			<div class="field" style="margin-top:0;">
				<label for="starts_on">Fecha base de inicio</label>
				<input id="starts_on" type="date" name="starts_on" value="<?php echo htmlspecialchars(set_value('starts_on', isset($rule['starts_on']) ? $rule['starts_on'] : ''), ENT_QUOTES, 'UTF-8'); ?>" />
			</div>

			<div class="field" style="margin-top:0;">
				<label for="ends_on">Fecha final opcional</label>
				<input id="ends_on" type="date" name="ends_on" value="<?php echo htmlspecialchars(set_value('ends_on', isset($rule['ends_on']) ? $rule['ends_on'] : ''), ENT_QUOTES, 'UTF-8'); ?>" />
			</div>
		</div>

		<div class="field" id="special-date-wrapper" style="margin-top:0; <?php echo $selected_recurrence === 'special_date' ? '' : 'display:none;'; ?>">
			<label for="special_date_code">Fecha especial</label>
			<select id="special_date_code" name="special_date_code">
				<option value="">Selecciona una fecha especial</option>
				<?php foreach ($special_dates as $special_date) { ?>
					<option value="<?php echo htmlspecialchars($special_date['code'], ENT_QUOTES, 'UTF-8'); ?>" <?php echo set_value('special_date_code', isset($rule['special_date_code']) ? $rule['special_date_code'] : '') === $special_date['code'] ? 'selected' : ''; ?>>
						<?php echo htmlspecialchars($special_date['category'].' - '.$special_date['name'], ENT_QUOTES, 'UTF-8'); ?>
					</option>
				<?php } ?>
			</select>

			<div class="field" style="margin-top:12px;">
				<label for="special_date_lead_days">Dias de anticipacion</label>
				<input id="special_date_lead_days" type="number" min="0" step="1" name="special_date_lead_days" value="<?php echo htmlspecialchars(set_value('special_date_lead_days', isset($rule['special_date_lead_days']) ? $rule['special_date_lead_days'] : 0), ENT_QUOTES, 'UTF-8'); ?>" />
				<div style="margin-top:6px; font-size:calc(0.84rem * var(--app-text-size)); color:var(--muted);">
					Si colocas 10 y la fecha especial cae el 15/03/2026, la tarea se generara el 05/03/2026.
				</div>
			</div>
		</div>

		<div class="field" style="margin-top:0;">
			<label>Subtareas a incluir</label>
			<div id="ignored-items-wrapper" class="task-selector-list"></div>
			<div style="margin-top:6px; font-size:calc(0.84rem * var(--app-text-size)); color:var(--muted);">
				Deja marcadas las subtareas que quieras asignar. Las que quites no se incluiran en esta tarea.
			</div>
		</div>

		<label style="display:flex; align-items:center; gap:10px; font-weight:700; color:var(--ink);">
			<input type="checkbox" name="requires_note_on_complete" value="1" <?php echo set_checkbox('requires_note_on_complete', '1', !empty($rule['requires_note_on_complete'])); ?> />
			<span>Exigir nota al terminar</span>
		</label>

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

<script>
document.addEventListener('DOMContentLoaded', function () {
	var templateSelect = document.getElementById('template_id');
	var assignmentMode = document.getElementById('assignment_mode');
	var groupMode = document.getElementById('group_distribution_mode');
	var recurrenceType = document.getElementById('recurrence_type');
	var employeeWrapper = document.getElementById('employee-wrapper');
	var groupWrapper = document.getElementById('group-wrapper');
	var distributionWrapper = document.getElementById('distribution-wrapper');
	var oneTimeWrapper = document.getElementById('one-time-wrapper');
	var rangeWrapper = document.getElementById('range-wrapper');
	var specialDateWrapper = document.getElementById('special-date-wrapper');
	var ignoredWrapper = document.getElementById('ignored-items-wrapper');
	var templateItemsMap = <?php echo json_encode($template_items_map); ?>;
	var selectedIgnoredItemIds = <?php echo json_encode(array_values($selected_ignored_item_ids)); ?>;
	var buildIgnoredHiddenInputs = function () {
		Array.prototype.slice.call(document.querySelectorAll('.js-ignored-hidden')).forEach(function (node) {
			node.remove();
		});
		Array.prototype.slice.call(ignoredWrapper.querySelectorAll('.js-selectable-item')).forEach(function (checkbox) {
			if (checkbox.checked) {
				return;
			}
			var hiddenInput = document.createElement('input');
			hiddenInput.type = 'hidden';
			hiddenInput.name = 'ignored_item_ids[]';
			hiddenInput.value = checkbox.getAttribute('data-item-id') || '';
			hiddenInput.className = 'js-ignored-hidden';
			form.appendChild(hiddenInput);
		});
	};

	var syncAssignmentMode = function () {
		var isGroup = assignmentMode && assignmentMode.value === 'group';
		if (employeeWrapper) {
			employeeWrapper.style.display = isGroup ? 'none' : 'block';
		}
		if (groupWrapper) {
			groupWrapper.style.display = isGroup ? 'block' : 'none';
		}
		syncGroupMode();
	};

	var syncGroupMode = function () {
		var showDistribution = assignmentMode && assignmentMode.value === 'group' && groupMode && groupMode.value === 'distributed';
		if (distributionWrapper) {
			distributionWrapper.style.display = showDistribution ? 'block' : 'none';
		}
	};

	var syncRecurrence = function () {
		var value = recurrenceType ? recurrenceType.value : 'one_time';
		if (oneTimeWrapper) {
			oneTimeWrapper.style.display = value === 'one_time' ? 'block' : 'none';
		}
		if (rangeWrapper) {
			rangeWrapper.style.display = ['daily', 'weekly', 'monthly', 'quarterly', 'semiannual', 'annual'].indexOf(value) >= 0 ? 'block' : 'none';
		}
		if (specialDateWrapper) {
			specialDateWrapper.style.display = value === 'special_date' ? 'block' : 'none';
		}
	};

	var renderIgnoredItems = function () {
		var templateId = templateSelect ? templateSelect.value : '';
		var items = templateItemsMap[templateId] || [];
		if (!ignoredWrapper) {
			return;
		}
		if (!items.length) {
			ignoredWrapper.innerHTML = '<div style="font-size:calc(0.88rem * var(--app-text-size)); color:var(--muted);">Esta plantilla no tiene subtareas configuradas.</div>';
			return;
		}
		ignoredWrapper.innerHTML = items.map(function (item) {
			var checked = selectedIgnoredItemIds.indexOf(parseInt(item.id, 10)) === -1 ? 'checked' : '';
			var label = (item.is_child ? '- ' : '') + item.name;
			var selectedClass = checked ? ' is-selected' : '';
			return '<label class="task-selector-option' + selectedClass + '"><span class="task-selector-box"><input class="js-selectable-item" type="checkbox" data-item-id="' + item.id + '" ' + checked + ' /><span class="task-selector-mark"></span></span><span class="task-selector-content" style="padding-left:' + (item.is_child ? '18px' : '0') + ';"><span class="task-selector-label">' + label + '</span></span></label>';
		}).join('');
	};

	if (templateSelect) {
		templateSelect.addEventListener('change', function () {
			selectedIgnoredItemIds = [];
			renderIgnoredItems();
		});
	}
	if (assignmentMode) {
		assignmentMode.addEventListener('change', syncAssignmentMode);
	}
	if (groupMode) {
		groupMode.addEventListener('change', syncGroupMode);
	}
	if (recurrenceType) {
		recurrenceType.addEventListener('change', syncRecurrence);
	}
	if (ignoredWrapper) {
		ignoredWrapper.addEventListener('change', function (event) {
			var checkbox = event.target;
			if (!checkbox.classList.contains('js-selectable-item')) {
				return;
			}
			var row = checkbox.closest('.task-selector-option');
			if (row) {
				row.classList.toggle('is-selected', checkbox.checked);
			}
		});
	}
	if (form) {
		form.addEventListener('submit', function () {
			buildIgnoredHiddenInputs();
		});
	}

	syncAssignmentMode();
	syncRecurrence();
	renderIgnoredItems();
});
</script>
