<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php
$goal = is_array($goal) ? $goal : array();
$scope_type = isset($goal['scope_type']) ? $goal['scope_type'] : 'general';
$employee_mode = isset($goal['employee_mode']) ? $goal['employee_mode'] : 'global';
$selected_group_ids = !empty($goal['group_ids']) && is_array($goal['group_ids']) ? array_map('intval', $goal['group_ids']) : (!empty($goal['group_id']) ? array((int)$goal['group_id']) : array());
if (!empty($_POST['group_ids']) && is_array($_POST['group_ids']))
{
	$selected_group_ids = array_map('intval', $_POST['group_ids']);
}
$target_scope = isset($goal['target_scope']) ? $goal['target_scope'] : 'individual';
?>
<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/metas'); ?>">Regresar</a>
		</div>

		<h2 style="margin-bottom:0;"><?php echo !empty($goal['id']) ? 'Editar meta' : 'Nueva meta'; ?></h2>
		<?php if (!empty($goal_error)) { ?>
			<div class="notice" style="margin:0;"><?php echo htmlspecialchars($goal_error, ENT_QUOTES, 'UTF-8'); ?></div>
		<?php } ?>

		<div style="display:grid; gap:16px;">
			<div class="field" style="margin-top:0;">
				<label for="name">Nombre</label>
				<input id="name" type="text" name="name" value="<?php echo htmlspecialchars(set_value('name', isset($goal['name']) ? $goal['name'] : ''), ENT_QUOTES, 'UTF-8'); ?>" />
			</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($goal['is_active']) || !empty($goal['is_active'])); ?> />
				<span>Meta activa</span>
			</label>

			<div style="display:grid; gap:14px;">
				<div class="field" style="margin-top:0;">
					<label for="period_type">Periodo</label>
					<select id="period_type" name="period_type">
						<?php foreach ($goal_options['period_types'] as $value => $label) { ?>
							<option value="<?php echo htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); ?>" <?php echo set_select('period_type', $value, (isset($goal['period_type']) ? $goal['period_type'] : 'daily') === $value); ?>>
								<?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div id="custom-period-wrapper" style="<?php echo (isset($goal['period_type']) && $goal['period_type'] === 'custom') ? '' : 'display:none;'; ?>">
					<div class="field" style="margin-top:0;">
						<label for="custom_period_start_date">Fecha inicial del periodo</label>
						<input id="custom_period_start_date" type="date" name="custom_period_start_date" value="<?php echo htmlspecialchars(set_value('custom_period_start_date', isset($goal['custom_period_start_date']) ? $goal['custom_period_start_date'] : ''), ENT_QUOTES, 'UTF-8'); ?>" />
					</div>

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

				<label style="display:flex; align-items:center; gap:10px; font-weight:700; color:var(--ink);">
					<input type="checkbox" id="run_once" name="run_once" value="1" <?php echo set_checkbox('run_once', '1', !empty($goal['run_once'])); ?> />
					<span>Correr meta solo una vez</span>
				</label>

				<div id="run-once-options" style="<?php echo !empty($goal['run_once']) ? '' : 'display:none;'; ?>">
					<div class="field" style="margin-top:0;">
						<label for="run_once_mode">Duracion</label>
						<select id="run_once_mode" name="run_once_mode">
							<?php foreach ($goal_options['run_once_modes'] as $value => $label) { ?>
								<option value="<?php echo htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); ?>" <?php echo set_select('run_once_mode', $value, (isset($goal['run_once_mode']) ? $goal['run_once_mode'] : 'period') === $value); ?>>
									<?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>
								</option>
							<?php } ?>
						</select>
					</div>

					<div id="run-once-custom-dates" style="<?php echo (!empty($goal['run_once']) && isset($goal['run_once_mode']) && $goal['run_once_mode'] === 'custom') ? '' : 'display:none;'; ?>">
						<div class="field" style="margin-top:0;">
							<label for="run_once_start_date">Fecha inicial</label>
							<input id="run_once_start_date" type="date" name="run_once_start_date" value="<?php echo htmlspecialchars(set_value('run_once_start_date', isset($goal['run_once_start_date']) ? $goal['run_once_start_date'] : ''), ENT_QUOTES, 'UTF-8'); ?>" />
						</div>

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

				<div class="field" style="margin-top:0;">
					<label for="scope_type">Filtro</label>
					<select id="scope_type" name="scope_type">
						<?php foreach ($goal_options['scope_types'] as $value => $label) { ?>
							<option value="<?php echo htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); ?>" <?php echo set_select('scope_type', $value, $scope_type === $value); ?>>
								<?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div id="scope-category-wrapper" class="field" style="margin-top:0; <?php echo $scope_type === 'category' ? '' : 'display:none;'; ?>">
					<label for="scope_category_id">Categoria</label>
					<select id="scope_category_id" name="scope_category_id">
						<option value="">Selecciona una categoria</option>
						<?php foreach ($goal_options['categories'] as $row) { ?>
							<option value="<?php echo (int)$row['id']; ?>" <?php echo set_select('scope_category_id', (string)$row['id'], $scope_type === 'category' && isset($goal['scope_id']) && (int)$goal['scope_id'] === (int)$row['id']); ?>>
								<?php echo htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div id="scope-item-wrapper" class="field" style="margin-top:0; <?php echo $scope_type === 'item' ? '' : 'display:none;'; ?>">
					<label for="scope_item_id">Articulo</label>
					<select id="scope_item_id" name="scope_item_id">
						<option value="">Selecciona un articulo</option>
						<?php foreach ($goal_options['items'] as $row) { ?>
							<option value="<?php echo (int)$row['item_id']; ?>" <?php echo set_select('scope_item_id', (string)$row['item_id'], $scope_type === 'item' && isset($goal['scope_id']) && (int)$goal['scope_id'] === (int)$row['item_id']); ?>>
								<?php echo htmlspecialchars($row['name'].(!empty($row['item_number']) ? ' - '.$row['item_number'] : ''), ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div id="scope-manufacturer-wrapper" class="field" style="margin-top:0; <?php echo $scope_type === 'manufacturer' ? '' : 'display:none;'; ?>">
					<label for="scope_manufacturer_id">Fabricante</label>
					<select id="scope_manufacturer_id" name="scope_manufacturer_id">
						<option value="">Selecciona un fabricante</option>
						<?php foreach ($goal_options['manufacturers'] as $row) { ?>
							<option value="<?php echo (int)$row['id']; ?>" <?php echo set_select('scope_manufacturer_id', (string)$row['id'], $scope_type === 'manufacturer' && isset($goal['scope_id']) && (int)$goal['scope_id'] === (int)$row['id']); ?>>
								<?php echo htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div id="scope-supplier-wrapper" class="field" style="margin-top:0; <?php echo $scope_type === 'supplier' ? '' : 'display:none;'; ?>">
					<label for="scope_supplier_id">Proveedor</label>
					<select id="scope_supplier_id" name="scope_supplier_id">
						<option value="">Selecciona un proveedor</option>
						<?php foreach ($goal_options['suppliers'] as $row) { ?>
							<option value="<?php echo (int)$row['id']; ?>" <?php echo set_select('scope_supplier_id', (string)$row['id'], $scope_type === 'supplier' && isset($goal['scope_id']) && (int)$goal['scope_id'] === (int)$row['id']); ?>>
								<?php echo htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div class="field" style="margin-top:0;">
					<label for="metric_type">Medicion</label>
					<select id="metric_type" name="metric_type">
						<?php foreach ($goal_options['metric_types'] as $value => $label) { ?>
							<option value="<?php echo htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); ?>" <?php echo set_select('metric_type', $value, (isset($goal['metric_type']) ? $goal['metric_type'] : 'amount') === $value); ?>>
								<?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div class="field" style="margin-top:0;">
					<label for="goal_method">Metodo</label>
					<select id="goal_method" name="goal_method">
						<?php foreach ($goal_options['goal_methods'] as $value => $label) { ?>
							<option value="<?php echo htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); ?>" <?php echo set_select('goal_method', $value, (isset($goal['goal_method']) ? $goal['goal_method'] : 'fixed') === $value); ?>>
								<?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div id="goal-amount-wrapper" class="field" style="margin-top:0;">
					<label for="goal_amount">Monto objetivo</label>
					<input id="goal_amount" type="number" step="0.01" min="0" name="goal_amount" value="<?php echo htmlspecialchars(set_value('goal_amount', isset($goal['goal_amount']) ? number_format((float)$goal['goal_amount'], 2, '.', '') : '0.00'), ENT_QUOTES, 'UTF-8'); ?>" />
				</div>

				<div id="goal-percent-wrapper" class="field" style="margin-top:0; <?php echo (isset($goal['goal_method']) && $goal['goal_method'] === 'last_year_same_period_plus_percent') ? '' : 'display:none;'; ?>">
					<label for="goal_percent">Porcentaje adicional</label>
					<input id="goal_percent" type="number" step="0.01" min="0" name="goal_percent" value="<?php echo htmlspecialchars(set_value('goal_percent', isset($goal['goal_percent']) ? number_format((float)$goal['goal_percent'], 2, '.', '') : '0.00'), ENT_QUOTES, 'UTF-8'); ?>" />
				</div>

				<div class="field" style="margin-top:0;">
					<label for="display_mode">Estilo</label>
					<select id="display_mode" name="display_mode">
						<?php foreach ($goal_options['display_modes'] as $value => $label) { ?>
							<option value="<?php echo htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); ?>" <?php echo set_select('display_mode', $value, (isset($goal['display_mode']) ? $goal['display_mode'] : 'bar') === $value); ?>>
								<?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div class="field" style="margin-top:0;">
					<label for="employee_mode">Aplicacion</label>
					<select id="employee_mode" name="employee_mode">
						<?php foreach ($goal_options['employee_modes'] as $value => $label) { ?>
							<option value="<?php echo htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); ?>" <?php echo set_select('employee_mode', $value, $employee_mode === $value); ?>>
								<?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div id="employee-id-wrapper" class="field" style="margin-top:0; <?php echo $employee_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 ($goal_options['employees'] as $row) { ?>
							<option value="<?php echo (int)$row['person_id']; ?>" <?php echo set_select('employee_id', (string)$row['person_id'], $employee_mode === 'employee' && isset($goal['employee_id']) && (int)$goal['employee_id'] === (int)$row['person_id']); ?>>
								<?php echo htmlspecialchars($row['full_name'], ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div id="group-id-wrapper" class="field" style="margin-top:0; <?php echo $employee_mode === 'group' ? '' : 'display:none;'; ?>">
					<label>Grupos</label>
					<div style="display:grid; gap:10px; padding:14px; border-radius:18px; background:var(--panel-soft);">
						<?php foreach ($goal_options['groups'] as $row) { ?>
							<label style="display:flex; align-items:center; gap:10px; font-weight:700; color:var(--ink);">
								<input type="checkbox" name="group_ids[]" value="<?php echo (int)$row['id']; ?>" <?php echo in_array((int)$row['id'], $selected_group_ids, TRUE) ? 'checked' : ''; ?> />
								<span style="display:inline-flex; width:12px; height:12px; border-radius:999px; background:<?php echo htmlspecialchars(!empty($row['color']) ? $row['color'] : '#4d74c3', ENT_QUOTES, 'UTF-8'); ?>;"></span>
								<span><?php echo htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8'); ?></span>
							</label>
						<?php } ?>
					</div>
				</div>

				<div id="target-scope-wrapper" class="field" style="margin-top:0; <?php echo $employee_mode === 'group' ? '' : 'display:none;'; ?>">
					<label for="target_scope">Modo del grupo</label>
					<select id="target_scope" name="target_scope">
						<?php foreach ($goal_options['target_scopes'] as $value => $label) { ?>
							<option value="<?php echo htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); ?>" <?php echo set_select('target_scope', $value, $target_scope === $value); ?>>
								<?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>
							</option>
						<?php } ?>
					</select>
				</div>

				<div class="field" style="margin-top:0;">
					<label for="sort_order">Orden</label>
					<input id="sort_order" type="number" step="1" min="0" name="sort_order" value="<?php echo htmlspecialchars(set_value('sort_order', isset($goal['sort_order']) ? (int)$goal['sort_order'] : 0), ENT_QUOTES, 'UTF-8'); ?>" />
				</div>
			</div>
		</div>

		<div class="actions" style="justify-content:flex-end;">
			<button class="btn" type="submit">Guardar</button>
		</div>
	</form>
</section>
<script>
document.addEventListener('DOMContentLoaded', function () {
	var scopeType = document.getElementById('scope_type');
	var periodType = document.getElementById('period_type');
	var employeeMode = document.getElementById('employee_mode');
	var goalMethod = document.getElementById('goal_method');
	var runOnce = document.getElementById('run_once');
	var runOnceMode = document.getElementById('run_once_mode');
	var customPeriodWrapper = document.getElementById('custom-period-wrapper');
	var scopeWrappers = {
		category: document.getElementById('scope-category-wrapper'),
		item: document.getElementById('scope-item-wrapper'),
		manufacturer: document.getElementById('scope-manufacturer-wrapper'),
		supplier: document.getElementById('scope-supplier-wrapper')
	};
	var employeeWrapper = document.getElementById('employee-id-wrapper');
	var groupWrapper = document.getElementById('group-id-wrapper');
	var targetScopeWrapper = document.getElementById('target-scope-wrapper');
	var amountWrapper = document.getElementById('goal-amount-wrapper');
	var percentWrapper = document.getElementById('goal-percent-wrapper');
	var runOnceOptions = document.getElementById('run-once-options');
	var runOnceCustomDates = document.getElementById('run-once-custom-dates');

	var syncScope = function () {
		Object.keys(scopeWrappers).forEach(function (key) {
			if (scopeWrappers[key]) {
				scopeWrappers[key].style.display = scopeType && scopeType.value === key ? 'block' : 'none';
			}
		});
	};

	var syncPeriod = function () {
		if (customPeriodWrapper) {
			customPeriodWrapper.style.display = periodType && periodType.value === 'custom' ? 'block' : 'none';
		}
		if (runOnceMode && periodType && periodType.value === 'custom' && runOnceMode.value === 'period') {
			runOnceMode.value = 'custom';
		}
		syncRunOnce();
	};

	var syncEmployee = function () {
		if (employeeWrapper) {
			employeeWrapper.style.display = employeeMode && employeeMode.value === 'employee' ? 'block' : 'none';
		}
		if (groupWrapper) {
			groupWrapper.style.display = employeeMode && employeeMode.value === 'group' ? 'block' : 'none';
		}
		if (targetScopeWrapper) {
			targetScopeWrapper.style.display = employeeMode && employeeMode.value === 'group' ? 'block' : 'none';
		}
	};

	var syncMethod = function () {
		if (percentWrapper) {
			percentWrapper.style.display = goalMethod && goalMethod.value === 'last_year_same_period_plus_percent' ? 'block' : 'none';
		}
		if (amountWrapper) {
			amountWrapper.style.display = goalMethod && (goalMethod.value === 'fixed' || goalMethod.value === 'competitive_target') ? 'block' : 'none';
		}
	};

	var syncRunOnce = function () {
		var enabled = runOnce && runOnce.checked;
		if (runOnceOptions) {
			runOnceOptions.style.display = enabled ? 'block' : 'none';
		}
		if (runOnceCustomDates) {
			runOnceCustomDates.style.display = enabled && runOnceMode && runOnceMode.value === 'custom' ? 'block' : 'none';
		}
	};

	if (scopeType) {
		scopeType.addEventListener('change', syncScope);
	}
	if (periodType) {
		periodType.addEventListener('change', syncPeriod);
	}
	if (employeeMode) {
		employeeMode.addEventListener('change', syncEmployee);
	}
	if (goalMethod) {
		goalMethod.addEventListener('change', syncMethod);
	}
	if (runOnce) {
		runOnce.addEventListener('change', syncRunOnce);
	}
	if (runOnceMode) {
		runOnceMode.addEventListener('change', syncRunOnce);
	}

	syncScope();
	syncPeriod();
	syncEmployee();
	syncMethod();
	syncRunOnce();
});
</script>
