<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php
$history_mode = !empty($history_mode);
$history_route = !empty($historical_route) ? (string) $historical_route : ($history_mode ? 'metas' : 'metas/historicas');
?><style>
	.goal-block {
		background: var(--panel);
		border-radius: 18px;
		box-shadow: var(--shadow);
		margin-bottom: 16px;
		overflow: hidden;
	}
	.goal-toolbar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		gap: 12px;
		margin-bottom: 10px;
	}
	.goal-toggle {
		width: 100%;
		border: 0;
		background: transparent;
		padding: 16px 18px;
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		gap: 16px;
		cursor: pointer;
		text-align: left;
	}
	.goal-toggle:hover {
		background: rgba(77, 116, 195, 0.04);
	}
	.goal-title-wrap {
		display: grid;
		gap: 8px;
		min-width: 0;
	}
	.goal-title-wrap h3 {
		margin: 0;
	}
	.goal-meta {
		display: flex;
		flex-wrap: wrap;
		gap: 8px 14px;
		color: var(--muted);
		font-size: 0.9rem;
	}
	.goal-status {
		display: inline-flex;
		align-items: center;
		gap: 8px;
		flex-wrap: wrap;
	}
	.goal-summary {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		justify-content: flex-end;
	}
	.goal-summary-item {
		min-width: 96px;
		padding: 10px 12px;
		border-radius: 14px;
		background: var(--card);
		box-shadow: inset 0 0 0 1px var(--border);
	}
	.goal-summary-item strong,
	.goal-summary-item span {
		display: block;
	}
	.goal-summary-item span {
		color: var(--muted);
		font-size: 0.78rem;
		text-transform: uppercase;
		letter-spacing: 0.04em;
	}
	.goal-summary-item strong {
		margin-top: 4px;
	}
	.goal-chevron {
		width: 38px;
		height: 38px;
		border-radius: 999px;
		background: var(--card);
		box-shadow: inset 0 0 0 1px var(--border);
		display: inline-flex;
		align-items: center;
		justify-content: center;
		font-size: 1.1rem;
		color: var(--ink);
		flex: 0 0 38px;
	}
	.goal-edit {
		position: relative;
		z-index: 2;
	}
	.goal-block.is-open .goal-chevron {
		transform: rotate(180deg);
	}
	.goal-content {
		display: none;
		padding: 0 18px 18px;
	}
	.goal-block.is-open .goal-content {
		display: block;
	}
	table {
		width: 100%;
		border-collapse: collapse;
		background: var(--panel);
		border-radius: 14px;
		overflow: hidden;
		box-shadow: inset 0 0 0 1px var(--border);
	}
	th, td {
		padding: 10px 12px;
		text-align: left;
		border-bottom: 1px solid var(--border);
	}
	th {
		background: var(--card);
		font-size: 0.8rem;
		text-transform: uppercase;
		letter-spacing: 0.04em;
		color: var(--muted);
	}
	tr:last-child td {
		border-bottom: 0;
	}
	.progress {
		height: 8px;
		border-radius: 999px;
		background: rgba(77, 116, 195, 0.15);
		overflow: hidden;
	}
	.progress span {
		display: block;
		height: 100%;
		background: linear-gradient(90deg, #5bbd3b, #2ecc71);
	}
	.goal-empty {
		padding: 14px;
		border-radius: 14px;
		background: var(--card);
		color: var(--muted);
	}
	@media (max-width: 860px) {
		.goal-toggle {
			flex-direction: column;
		}
		.goal-summary {
			justify-content: flex-start;
		}
	}
</style>

<div class="actions" style="justify-content:flex-end; margin-bottom:16px;">
	<a class="btn btn-outline" href="<?php echo site_url($history_route); ?>"><?php echo $history_mode ? 'Ver activas' : 'Metas historicas'; ?></a>
	<?php if (!$history_mode) { ?>
		<a class="btn" href="<?php echo site_url('metas/nueva'); ?>">Agregar meta</a>
	<?php } ?>
	<?php if (!empty($goal_rows) && !$history_mode) { ?>
		<button class="btn btn-outline" type="button" onclick="window.print()">Imprimir</button>
		<a class="btn" href="<?php echo site_url('metas/exportar'); ?>">Exportar CSV</a>
	<?php } ?>
</div>

<?php if (empty($goal_rows)) { ?>
	<div class="panel"><?php echo $history_mode ? 'No hay metas historicas para mostrar.' : 'No hay metas activas para el periodo con empleados activos.'; ?></div>
<?php } else { ?>
	<?php foreach ($goal_rows as $index => $goal) { ?>
		<?php
			$definition = $goal['definition'];
			$metric_label = isset($definition['metric_type']) && $definition['metric_type'] === 'quantity' ? 'Cantidad' : 'Monto';
			$scope_label = isset($definition['scope_type']) ? $definition['scope_type'] : 'general';
			$goal_method = !empty($definition['goal_method']) ? $definition['goal_method'] : 'fixed';
			$rows = !empty($goal['rows']) ? (array) $goal['rows'] : array();
			$is_active = !empty($goal['is_active']);
			$is_available = !empty($goal['is_available']);
			$total_employees = count($rows);
			$avg_progress = 0;
			$best_progress = 0;
			if (!empty($rows))
			{
				$sum_progress = 0;
				foreach ($rows as $row)
				{
					$progress_value = isset($row['progress_percent']) ? (int) $row['progress_percent'] : 0;
					$sum_progress += $progress_value;
					if ($progress_value > $best_progress)
					{
						$best_progress = $progress_value;
					}
				}
				$avg_progress = (int) round($sum_progress / count($rows));
			}
			$block_id = 'goal-block-'.$index;
			$content_id = 'goal-content-'.$index;
		?>
		<div class="goal-block" id="<?php echo $block_id; ?>">
			<button
				class="goal-toggle"
				type="button"
				data-role="goal-toggle"
				data-target="<?php echo $content_id; ?>"
				aria-expanded="false"
				aria-controls="<?php echo $content_id; ?>"
			>
				<div class="goal-title-wrap">
					<div style="display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
						<h3><?php echo htmlspecialchars((string) $definition['name'], ENT_QUOTES, 'UTF-8'); ?></h3>
						<div class="goal-status">
							<span class="badge warning"><?php echo htmlspecialchars((string) $goal_method, ENT_QUOTES, 'UTF-8'); ?></span>
							<span class="badge <?php echo $is_active ? 'success' : 'danger'; ?>">
								<?php echo $is_active ? 'Activa' : 'Inactiva'; ?>
							</span>
							<?php if ($is_active && !$is_available) { ?>
								<span class="badge warning">Fuera de periodo</span>
							<?php } ?>
						</div>
					</div>
					<div class="goal-meta">
						<span><?php echo htmlspecialchars($metric_label, ENT_QUOTES, 'UTF-8'); ?></span>
						<span><?php echo htmlspecialchars($scope_label, ENT_QUOTES, 'UTF-8'); ?></span>
						<span><?php echo date('d/m/Y', strtotime($goal['date_start'])); ?> al <?php echo date('d/m/Y', strtotime($goal['date_end'])); ?></span>
					</div>
				</div>
				<div style="display:flex; align-items:center; gap:12px; flex-wrap:wrap; justify-content:flex-end;">
					<a
						class="btn btn-outline goal-edit"
						href="<?php echo site_url('metas/'.(int) $definition['id']); ?>"
						onclick="event.stopPropagation();"
					>Editar</a>
					<?php if (!$history_mode) { ?>
						<a
							class="btn btn-danger goal-edit"
							href="#"
							onclick="event.stopPropagation(); if (confirm('¿Seguro que quieres deshabilitar esta meta?')) { document.getElementById('goal-disable-<?php echo (int) $definition['id']; ?>').submit(); } return false;"
						>Eliminar</a>
					<?php } ?>
					<div class="goal-summary">
						<div class="goal-summary-item">
							<span>Empleados</span>
							<strong><?php echo (int) $total_employees; ?></strong>
						</div>
						<div class="goal-summary-item">
							<span>Promedio</span>
							<strong><?php echo (int) $avg_progress; ?>%</strong>
						</div>
						<div class="goal-summary-item">
							<span>Mejor avance</span>
							<strong><?php echo (int) $best_progress; ?>%</strong>
						</div>
					</div>
					<span class="goal-chevron">&#9662;</span>
				</div>
			</button>

			<?php if (!$history_mode) { ?>
				<form id="goal-disable-<?php echo (int) $definition['id']; ?>" method="post" action="<?php echo site_url('metas/'.(int) $definition['id'].'/eliminar'); ?>" style="display:none;"></form>
			<?php } ?>

			<div class="goal-content" id="<?php echo $content_id; ?>">
				<?php if (empty($rows)) { ?>
					<div class="goal-empty">
						<?php if (!$is_active) { ?>
							Esta meta esta inactiva.
						<?php } elseif (!$is_available) { ?>
							Esta meta no aplica al periodo seleccionado.
						<?php } else { ?>
							Sin empleados activos aplicables.
						<?php } ?>
					</div>
				<?php } else { ?>
					<div data-role="goal-body"></div>
					<template data-role="goal-template">
						<table>
							<thead>
								<tr>
									<th>Empleado</th>
									<th>Actual</th>
									<th>Meta</th>
									<th>Avance</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ($rows as $row) { ?>
									<tr>
										<td><?php echo htmlspecialchars($row['employee_name'], ENT_QUOTES, 'UTF-8'); ?></td>
										<td><?php echo number_format((float) $row['current_value'], 2, '.', ','); ?></td>
										<td><?php echo number_format((float) $row['target_value'], 2, '.', ','); ?></td>
										<td>
											<div class="progress"><span style="width: <?php echo (int) $row['progress_percent']; ?>%;"></span></div>
											<div class="note" style="margin-top:4px;"><?php echo (int) $row['progress_percent']; ?>%</div>
										</td>
									</tr>
								<?php } ?>
							</tbody>
						</table>
					</template>
				<?php } ?>
			</div>
		</div>
	<?php } ?>
<?php } ?>

<script>
(function () {
	const toggles = document.querySelectorAll('[data-role="goal-toggle"]');

	function mountGoalTable(block) {
		if (!block || block.dataset.loaded === '1') {
			return;
		}
		const content = block.querySelector('[data-role="goal-body"]');
		const template = block.querySelector('template[data-role="goal-template"]');
		if (!content || !template) {
			block.dataset.loaded = '1';
			return;
		}
		content.appendChild(template.content.cloneNode(true));
		block.dataset.loaded = '1';
	}

	toggles.forEach(function (toggle) {
		toggle.addEventListener('click', function () {
			const block = toggle.closest('.goal-block');
			if (!block) {
				return;
			}
			const isOpen = block.classList.contains('is-open');
			if (isOpen) {
				block.classList.remove('is-open');
				toggle.setAttribute('aria-expanded', 'false');
				return;
			}

			mountGoalTable(block);
			block.classList.add('is-open');
			toggle.setAttribute('aria-expanded', 'true');
		});
	});
})();
</script>
