<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php
$report_data = isset($report_data) && is_array($report_data) ? $report_data : array();
$calendar_days = isset($report_data['calendar_days']) && is_array($report_data['calendar_days']) ? $report_data['calendar_days'] : array();
$weekdays = array('Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab', 'Dom');
$month_start_weekday = isset($report_data['month_start_weekday']) ? (int)$report_data['month_start_weekday'] : 1;
$leading_blanks = max(0, min(6, $month_start_weekday - 1));
$detail_lookup = array();
$default_detail_date = isset($report_data['default_detail_date']) ? (string)$report_data['default_detail_date'] : '';
foreach ($calendar_days as $day)
{
	$detail_lookup[$day['date']] = $day;
}
$selected_day = ($default_detail_date !== '' && isset($detail_lookup[$default_detail_date])) ? $detail_lookup[$default_detail_date] : null;
if ($selected_day === null)
{
	foreach ($calendar_days as $day)
	{
		if (!empty($day['status']))
		{
			$selected_day = $day;
			break;
		}
	}
}
if ($selected_day === null && !empty($calendar_days))
{
	$selected_day = $calendar_days[0];
}
?>
<section class="panel">
	<div class="actions" style="justify-content:space-between; margin-top:0; margin-bottom:18px; gap:12px;">
		<a class="btn btn-outline" href="<?php echo site_url('metas'); ?>">Regresar</a>
	</div>

	<h2 style="margin-bottom:16px;">Reporte de metas</h2>

	<div style="display:grid; grid-template-columns:repeat(2, minmax(0, 1fr)); gap:12px; margin-bottom:18px;">
		<div style="padding:16px; border-radius:20px; background:var(--panel); box-shadow:0 12px 24px rgba(20,41,64,0.08); display:grid; gap:6px;">
			<div style="font-size:calc(0.8rem * var(--app-text-size)); color:var(--muted); font-weight:800; text-transform:uppercase;">Completadas hoy</div>
			<div style="font-size:calc(1.8rem * var(--app-text-size)); color:var(--ink); font-weight:900;">
				<?php echo (int)(isset($report_data['completed_today']) ? $report_data['completed_today'] : 0); ?>
			</div>
		</div>
		<div style="padding:16px; border-radius:20px; background:var(--panel); box-shadow:0 12px 24px rgba(20,41,64,0.08); display:grid; gap:6px;">
			<div style="font-size:calc(0.8rem * var(--app-text-size)); color:var(--muted); font-weight:800; text-transform:uppercase;">Cumplidas este mes</div>
			<div style="font-size:calc(1.8rem * var(--app-text-size)); color:var(--ink); font-weight:900;">
				<?php echo (int)(isset($report_data['completed_month']) ? $report_data['completed_month'] : 0); ?>
			</div>
		</div>
		<div style="padding:16px; border-radius:20px; background:var(--panel); box-shadow:0 12px 24px rgba(20,41,64,0.08); display:grid; gap:6px;">
			<div style="font-size:calc(0.8rem * var(--app-text-size)); color:var(--muted); font-weight:800; text-transform:uppercase;">Total del mes</div>
			<div style="font-size:calc(1.8rem * var(--app-text-size)); color:var(--ink); font-weight:900;">
				<?php echo (int)(isset($report_data['total_month']) ? $report_data['total_month'] : 0); ?>
			</div>
		</div>
		<div style="padding:16px; border-radius:20px; background:var(--panel); box-shadow:0 12px 24px rgba(20,41,64,0.08); display:grid; gap:6px;">
			<div style="font-size:calc(0.8rem * var(--app-text-size)); color:var(--muted); font-weight:800; text-transform:uppercase;">Cumplimiento del mes</div>
			<div style="font-size:calc(1.8rem * var(--app-text-size)); color:var(--ink); font-weight:900;">
				<?php echo number_format((float)(isset($report_data['completion_percent_month']) ? $report_data['completion_percent_month'] : 0), 1, ',', '.'); ?>%
			</div>
		</div>
		<div style="padding:16px; border-radius:20px; background:var(--panel); box-shadow:0 12px 24px rgba(20,41,64,0.08); display:grid; gap:6px;">
			<div style="font-size:calc(0.8rem * var(--app-text-size)); color:var(--muted); font-weight:800; text-transform:uppercase;">Racha actual</div>
			<div style="font-size:calc(1.8rem * var(--app-text-size)); color:var(--ink); font-weight:900;">
				<?php echo (int)(isset($report_data['current_streak']) ? $report_data['current_streak'] : 0); ?>
			</div>
		</div>
		<div style="padding:16px; border-radius:20px; background:var(--panel); box-shadow:0 12px 24px rgba(20,41,64,0.08); display:grid; gap:6px;">
			<div style="font-size:calc(0.8rem * var(--app-text-size)); color:var(--muted); font-weight:800; text-transform:uppercase;">Mejor racha</div>
			<div style="font-size:calc(1.8rem * var(--app-text-size)); color:var(--ink); font-weight:900;">
				<?php echo (int)(isset($report_data['best_streak']) ? $report_data['best_streak'] : 0); ?>
			</div>
		</div>
	</div>

	<div style="padding:18px 16px; border-radius:24px; background:var(--panel); box-shadow:0 12px 24px rgba(20,41,64,0.08); display:grid; gap:16px;">
		<div style="display:grid; gap:6px;">
			<div style="font-size:calc(1rem * var(--app-text-size)); color:var(--ink); font-weight:900;">
				<?php echo htmlspecialchars(isset($report_data['month_label']) ? $report_data['month_label'] : '', ENT_QUOTES, 'UTF-8'); ?>
			</div>
			<div style="font-size:calc(0.82rem * var(--app-text-size)); color:var(--muted); line-height:1.45;">
				Toca un dia para ver el detalle. Verde: cumplio al menos una meta. Naranja: tuvo avance parcial. Rojo: tuvo movimientos pero no cumplio. Sin color: no hubo movimientos.
			</div>
		</div>

		<div style="display:grid; grid-template-columns:repeat(7, minmax(0, 1fr)); gap:8px;">
			<?php foreach ($weekdays as $weekday) { ?>
				<div style="text-align:center; font-size:calc(0.74rem * var(--app-text-size)); color:var(--muted); font-weight:800; text-transform:uppercase;">
					<?php echo htmlspecialchars($weekday, ENT_QUOTES, 'UTF-8'); ?>
				</div>
			<?php } ?>

			<?php for ($blank = 0; $blank < $leading_blanks; $blank++) { ?>
				<div></div>
			<?php } ?>

			<?php foreach ($calendar_days as $index => $day) { ?>
				<?php
				$bg = '#f2f5f9';
				$ink = '#5d7085';
				if (!empty($day['status']) && $day['status'] === 'success')
				{
					$bg = '#87d96c';
					$ink = '#10331b';
				}
				elseif (!empty($day['status']) && $day['status'] === 'partial')
				{
					$bg = '#f5b357';
					$ink = '#4e2a00';
				}
				elseif (!empty($day['status']) && $day['status'] === 'failed')
				{
					$bg = '#f07c7c';
					$ink = '#4a1212';
				}
				$outline = !empty($day['is_today']) ? '0 0 0 3px rgba(77,116,195,0.35)' : '0 0 0 1px rgba(20,41,64,0.06)';
				$title_bits = array($day['date']);
				if (!$day['is_future'])
				{
					$title_bits[] = 'Completadas: '.(int)$day['completed_count'];
					$title_bits[] = 'Total: '.(int)$day['total_count'];
				}
				$is_selected = $selected_day && $selected_day['date'] === $day['date'];
				?>
				<button
					type="button"
					class="goal-report-day"
					data-date="<?php echo htmlspecialchars($day['date'], ENT_QUOTES, 'UTF-8'); ?>"
					style="min-height:54px; border:0; border-radius:16px; background:<?php echo $bg; ?>; color:<?php echo $ink; ?>; box-shadow:<?php echo $outline; ?>; display:flex; align-items:center; justify-content:center; font-size:calc(1rem * var(--app-text-size)); font-weight:900; <?php echo $is_selected ? 'transform:scale(0.96);' : ''; ?>"
					title="<?php echo htmlspecialchars(implode(' | ', $title_bits), ENT_QUOTES, 'UTF-8'); ?>">
					<?php echo (int)$day['day']; ?>
				</button>
			<?php } ?>
		</div>

		<div id="goal-report-detail" style="padding:16px; border-radius:20px; background:#f8fafc; box-shadow:inset 0 0 0 1px rgba(20,41,64,0.08); display:grid; gap:12px;">
			<?php if ($selected_day) { ?>
				<div style="display:grid; gap:4px;">
					<div id="goal-report-detail-title" style="font-size:calc(0.98rem * var(--app-text-size)); color:var(--ink); font-weight:900;">
						Detalle del <?php echo htmlspecialchars($selected_day['date'], ENT_QUOTES, 'UTF-8'); ?>
					</div>
					<div id="goal-report-detail-subtitle" style="font-size:calc(0.82rem * var(--app-text-size)); color:var(--muted);">
						Completadas: <?php echo (int)$selected_day['completed_count']; ?> de <?php echo (int)$selected_day['total_count']; ?>
					</div>
				</div>
				<div id="goal-report-detail-body" style="display:grid; gap:10px;">
					<?php if (!empty($selected_day['details'])) { ?>
						<?php foreach ($selected_day['details'] as $detail) { ?>
							<?php
							$status_color = '#f07c7c';
							if ($detail['status'] === 'success')
							{
								$status_color = '#87d96c';
							}
							elseif ($detail['status'] === 'partial')
							{
								$status_color = '#f5b357';
							}
							?>
							<div style="padding:12px 14px; border-radius:16px; background:#ffffff; box-shadow:inset 0 0 0 1px rgba(20,41,64,0.08); display:grid; gap:6px;">
								<div style="display:flex; justify-content:space-between; align-items:center; gap:10px;">
									<div style="font-size:calc(0.9rem * var(--app-text-size)); color:var(--ink); font-weight:800;">
										<?php echo htmlspecialchars($detail['name'], ENT_QUOTES, 'UTF-8'); ?>
									</div>
									<span style="display:inline-flex; align-items:center; justify-content:center; padding:6px 10px; border-radius:999px; background:<?php echo $status_color; ?>; color:#ffffff; font-size:calc(0.72rem * var(--app-text-size)); font-weight:800;">
										<?php echo htmlspecialchars($detail['status_label'], ENT_QUOTES, 'UTF-8'); ?>
									</span>
								</div>
								<div style="font-size:calc(0.8rem * var(--app-text-size)); color:var(--muted); font-weight:700;">
									<?php echo htmlspecialchars($detail['summary'], ENT_QUOTES, 'UTF-8'); ?>
								</div>
							</div>
						<?php } ?>
					<?php } else { ?>
						<div style="padding:14px; border-radius:16px; background:#ffffff; box-shadow:inset 0 0 0 1px rgba(20,41,64,0.08); font-size:calc(0.84rem * var(--app-text-size)); color:var(--muted); text-align:center;">
							<?php echo !empty($selected_day['movement_count']) ? 'Ese dia hubo movimientos, pero no habia metas evaluables para este empleado.' : 'Ese dia no hubo movimientos.'; ?>
						</div>
					<?php } ?>
				</div>
			<?php } ?>
		</div>
	</div>
</section>

<script>
	(function() {
		var days = <?php echo json_encode($calendar_days); ?>;
		var map = {};
		for (var i = 0; i < days.length; i++) {
			map[days[i].date] = days[i];
		}

		var buttons = document.querySelectorAll('.goal-report-day');
		var title = document.getElementById('goal-report-detail-title');
		var subtitle = document.getElementById('goal-report-detail-subtitle');
		var body = document.getElementById('goal-report-detail-body');

		function escapeHtml(value) {
			return String(value || '')
				.replace(/&/g, '&amp;')
				.replace(/</g, '&lt;')
				.replace(/>/g, '&gt;')
				.replace(/"/g, '&quot;')
				.replace(/'/g, '&#039;');
		}

		function renderStatusColor(status) {
			if (status === 'success') return '#87d96c';
			if (status === 'partial') return '#f5b357';
			return '#f07c7c';
		}

		function setSelected(date) {
			for (var i = 0; i < buttons.length; i++) {
				buttons[i].style.transform = buttons[i].getAttribute('data-date') === date ? 'scale(0.96)' : '';
			}
		}

		function renderDay(day) {
			if (!day) {
				return;
			}

			setSelected(day.date);
			if (title) {
				title.textContent = 'Detalle del ' + day.date;
			}
			if (subtitle) {
				subtitle.textContent = 'Completadas: ' + day.completed_count + ' de ' + day.total_count;
			}
			if (!body) {
				return;
			}

			if (!day.details || !day.details.length) {
				body.innerHTML = '<div style="padding:14px; border-radius:16px; background:#ffffff; box-shadow:inset 0 0 0 1px rgba(20,41,64,0.08); font-size:calc(0.84rem * var(--app-text-size)); color:var(--muted); text-align:center;">' +
					(day.movement_count > 0 ? 'Ese dia hubo movimientos, pero no habia metas evaluables para este empleado.' : 'Ese dia no hubo movimientos.') +
					'</div>';
				return;
			}

			var html = '';
			for (var i = 0; i < day.details.length; i++) {
				var detail = day.details[i];
				html += '<div style="padding:12px 14px; border-radius:16px; background:#ffffff; box-shadow:inset 0 0 0 1px rgba(20,41,64,0.08); display:grid; gap:6px;">';
				html += '<div style="display:flex; justify-content:space-between; align-items:center; gap:10px;">';
				html += '<div style="font-size:calc(0.9rem * var(--app-text-size)); color:var(--ink); font-weight:800;">' + escapeHtml(detail.name) + '</div>';
				html += '<span style="display:inline-flex; align-items:center; justify-content:center; padding:6px 10px; border-radius:999px; background:' + renderStatusColor(detail.status) + '; color:#ffffff; font-size:calc(0.72rem * var(--app-text-size)); font-weight:800;">' + escapeHtml(detail.status_label) + '</span>';
				html += '</div>';
				html += '<div style="font-size:calc(0.8rem * var(--app-text-size)); color:var(--muted); font-weight:700;">' + escapeHtml(detail.summary) + '</div>';
				html += '</div>';
			}
			body.innerHTML = html;
		}

		for (var i = 0; i < buttons.length; i++) {
			buttons[i].addEventListener('click', function() {
				var date = this.getAttribute('data-date');
				renderDay(map[date] || null);
			});
		}
	})();
</script>
