<ul class="list-group">

	<li class="list-group-item">
		<h4>Ventas por Canales</h4>

		<ul class="nav nav-pills alt-pills float-right mini-labels">
			<form method="get">

				<li class="nav-item float-left mr-3">
					<label>Periodo</label>
					<?php $periodo = $_GET['periodo'] ?? ''; ?>
					<select name ="periodo" id="periodo" class="form-control">
						<option value="">Periodo</option>

						<option value="week" <?= $periodo === 'week' ? 'selected' : '' ?>>Esta semana</option>
						<option value="month" <?= $periodo === 'month' ? 'selected' : '' ?>>Este mes</option>

						<option disabled>──────────</option>
						<?php
							foreach ($meses_ventas as $k => $v) {
								$selected = '';
								if (!empty($periodo)) {
									if ($periodo == $v) {
										$selected =' selected="selected"';
									}
								}
								echo '<option value="' . $v . '"' . $selected . '>' . mtt($v) . '</option>';
							}
						?>
					</select>

				</li>

				<li class="nav-item float-left mr-3">
					<label>Desde</label>
					<input type="date" name="fecha_desde" id="fecha_desde" class="form-control" value="<?= $_GET['fecha_desde'] ?? '' ?>">
				</li>

				<li class="nav-item float-left mr-3">
					<label>Hasta</label>
					<input type="date" name="fecha_hasta" id="fecha_hasta" class="form-control"value="<?= $_GET['fecha_hasta'] ?? '' ?>">
				</li>

				<li class="nav-item float-left mr-3">
					<label>Canal</label>
					<select name ="id_canal" class="form-control select-canal">
						<option>Todos</option>
						<?php
							$c = $_GET['id_canal'];
							foreach ($canales as $k => $v) {
								$selected = '';
								if (!empty($c)) {
									if ($c == $k) {
										$selected =' selected="selected"';
									}
								}
								echo '<option value="' . $k . '"' . $selected . '>' . $v . '</option>';
							}
						?>
					</select>
				</li>

				<li class="nav-item float-left mr-3">
					<label>Proveedor</label>
					<select name ="id_proveedor" class="form-control select-id-proveedor">
						<option>Todos</option>
						<?php
							$p = $_GET['id_proveedor'];
							foreach($distribuidores as $k => $v) {
								$selected = '';
								if (!empty($p)) {
									if ($p == $k) {
										$selected =' selected="selected"';
									}
								}
								echo '<option value="' . $k . '"' . $selected . '>' . $v . '</option>';
							}
						?>
					</select>
				</li>

				<li class="nav-item float-left mr-3">
					<label></label>
					<button type="submit" class="btn btn-primary d-block">
						<i class="fa fa-search"></i>
					</button>
				</li>

			</form>
		</ul>
	</li>

	<li class="list-group-item">

		<h5>Ventas totales: <strong><?= clp($total_tienda)?></strong></h5>
				

		<div class="table-responsive">
			<table class="table table-striped">
				<thead>
					<tr>
						<th>Categoría</th>
						<th class="text-right">Ventas ($)</th>
						<th class="text-center">% del total</th>
						<th class="text-center">Ranking</th>
					</tr>
				</thead>
				<tbody>

					<?php $ranking = 1; ?>
					<?php foreach ($total_categorias as $row): ?>
						<tr>
							<td>
								<?= htmlspecialchars($row['categoria']) ?><br>
							</td>

							<td class="text-right">
								<?= clp($row['total_vendido']) ?>
							</td>

							<td class="text-center">
								<?= round($row['porcentaje_tienda']) ?>%
							</td>

							<td class="text-center">
								<?php
									$badge = 'badge-primary';
									if ($ranking === 1) $badge = 'badge-success';
									if ($ranking >= 10) $badge = 'badge-danger';
								?>
								<span class="badge <?= $badge ?>">#<?= $ranking ?></span>
							</td>
						</tr>
						<?php $ranking++; ?>
					<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<?php
			if (!empty($total_ubicaciones)) {
		?>
			<div class="table-responsive">
				<table class="table table-striped">
					<thead>
						<tr>
							<th>Ubicación</th>
							<th class="text-right">Ventas ($)</th>
							<th class="text-center">% del total</th>
							<th class="text-center">Ranking</th>
						</tr>
					</thead>
					<tbody>

						<?php $ranking = 1; ?>
						<?php foreach ($total_ubicaciones as $row): ?>
							<tr>
								<td>
									<?= htmlspecialchars($row['ubicacion']) ?><br>
									<span class="badge badge-light">
										<?= htmlspecialchars($row['categoria_top']) ?>
									</span>
								</td>

								<td class="text-right">
									<?= clp($row['total_vendido']) ?>
								</td>

								<td class="text-center">
									<?= round($row['porcentaje_tienda']) ?>%
								</td>

								<td class="text-center">
									<?php
										$badge = 'badge-primary';
										if ($ranking === 1) $badge = 'badge-success';
										if ($ranking >= 10) $badge = 'badge-danger';
									?>
									<span class="badge <?= $badge ?>">#<?= $ranking ?></span>
								</td>
							</tr>
							<?php $ranking++; ?>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>
		<?php } ?>
	</li>

</ul>


<script>
$(function () {

	function formatDate(date) {
		let d = new Date(date);
		let month = '' + (d.getMonth() + 1);
		let day = '' + d.getDate();
		let year = d.getFullYear();

		if (month.length < 2) month = '0' + month;
		if (day.length < 2) day = '0' + day;

		return [year, month, day].join('-');
	}

	function firstDayOfMonth(year, month) {
		return formatDate(new Date(year, month - 1, 1));
	}

	function lastDayOfMonth(year, month) {
		return formatDate(new Date(year, month, 0));
	}

	// =========================
	// Cambio de PERÍODO
	// =========================
	$('#periodo').on('change', function () {
		let value = $(this).val();
		let today = new Date();

		if (!value) return;

		// Esta semana
		if (value === 'week') {
			let day = today.getDay();
			let diff = today.getDate() - day + (day === 0 ? -6 : 1); // lunes
			let monday = new Date(today.setDate(diff));
			let sunday = new Date(monday);
			sunday.setDate(monday.getDate() + 6);

			$('#fecha_desde').val(formatDate(monday));
			$('#fecha_hasta').val(formatDate(sunday));
			return;
		}

		// Este mes
		if (value === 'month') {
			let year = today.getFullYear();
			let month = today.getMonth() + 1;

			$('#fecha_desde').val(firstDayOfMonth(year, month));
			$('#fecha_hasta').val(lastDayOfMonth(year, month));
			return;
		}

		// Mes específico (formato: YYYYMM)
		if (/^\d{6}$/.test(value)) {
			const year  = parseInt(value.substring(0, 4), 10);
			const month = parseInt(value.substring(4, 6), 10);

			const desde = new Date(year, month - 1, 1);
			const hasta = new Date(year, month, 0);

			$('#fecha_desde').val(desde.toISOString().slice(0, 10));
			$('#fecha_hasta').val(hasta.toISOString().slice(0, 10));
		}

	});

	// =========================
	// Cambio manual DESDE
	// =========================
	$('#fecha_desde').on('change', function () {
		let desde = $(this).val();
		let hasta = $('#fecha_hasta').val();

		if (hasta && desde > hasta) {
			$('#fecha_hasta').val(desde);
		}

		$('#periodo').val('');
	});

	// =========================
	// Cambio manual HASTA
	// =========================
	$('#fecha_hasta').on('change', function () {
		let hasta = $(this).val();
		let desde = $('#fecha_desde').val();

		if (desde && hasta < desde) {
			$('#fecha_desde').val(hasta);
		}

		$('#periodo').val('');
	});

});
</script>