<?php
require 'verifica_cookie.php';
require 'conexao.php';
require 'config.php';

$pdo  = Conexao::getInstance();

function formatarTempo($dataCadastro)
{
	if (empty($dataCadastro)) return '';
	$agora = new DateTime();
	$data  = new DateTime($dataCadastro);
	$diff  = $agora->diff($data);
	$minutos = ($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i;
	if ($minutos < 60) {
		return $minutos . 'min';
	}
	$horas = floor($minutos / 60);
	if ($horas > 99) {
		return $horas . 'h';
	}
	$mins  = $minutos % 60;
	return $horas . 'h' . ($mins > 0 ? ' ' . $mins . 'min' : '');
}

function calcularMinutos($dataCadastro)
{
	if (empty($dataCadastro)) return 0;
	$agora = new DateTime();
	$data  = new DateTime($dataCadastro);
	$diff  = $agora->diff($data);
	return ($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i;
}

$sql = "SELECT v.ven_001, v.ven_027, v.ven_026, COALESCE(v.cli_001, 0) as cli_001, c.cli_002 as nome_cliente ";
$sql .= "FROM venda v LEFT JOIN clientes c ON v.cli_001 = c.cli_001 ";
$sql .= "WHERE v.sit_001 = 8 AND v.ven_024 = 'C' ORDER BY v.ven_026";
$stm = $pdo->prepare($sql);
$stm->execute();
$comandas = $stm->fetchAll(PDO::FETCH_OBJ);

?>
<!DOCTYPE html>
<html>

<head>
	<title>Comanda Eletrônica</title>
	<?php require 'include/head.php'; ?>
	<style>
		.chip-filtro.ativo {
			background: #3f51b5 !important;
			color: #fff !important;
			border-color: #3f51b5 !important;
			box-shadow: 0 2px 8px rgba(63, 81, 181, 0.3) !important;
		}

		.chip-aberta.ativo {
			background: #3f51b5 !important;
			border-color: #3f51b5 !important;
		}

		.chip-pre-fechada.ativo {
			background: #d0a000 !important;
			border-color: #b08000 !important;
			color: #fff !important;
			box-shadow: 0 2px 8px rgba(208, 160, 0, 0.3) !important;
		}

		.secao-header {
			display: flex;
			align-items: center;
			gap: 8px;
			padding: 14px 16px 6px;
			font-weight: 700;
			font-size: 13px;
			text-transform: uppercase;
			letter-spacing: 0.5px;
		}

		.secao-header:not(:first-child) {
			margin-top: 6px;
			border-top: 1px solid #f0f0f0;
		}

		.secao-header .material-icons {
			font-size: 18px;
		}

		.secao-aberta {
			color: #e74c3c;
		}

		.secao-pre-fechada {
			color: #b08000;
		}

		.secao-count {
			background: rgba(0, 0, 0, 0.08);
			border-radius: 10px;
			padding: 1px 8px;
			font-size: 12px;
			margin-left: 2px;
		}

		.secao-vazia {
			grid-column: 1 / -1;
			padding: 4px 16px 12px;
			font-size: 13px;
			color: #bdbdbd;
			white-space: nowrap;
		}

		.filtros-wrapper {
			display: flex;
			gap: 8px;
			padding: 0 12px 10px;
			overflow-x: auto;
			-webkit-overflow-scrolling: touch;
			scrollbar-width: none;
		}

		.filtros-wrapper::-webkit-scrollbar {
			display: none;
		}

		/* ── Dark Theme Overrides ── */
		[data-theme="dark"] #btn-filtro-tempo {
			background: var(--bg-card) !important;
			border-color: var(--color-primary) !important;
			color: var(--color-primary) !important;
		}

		[data-theme="dark"] #modal-filtro-tempo>div {
			background: var(--bg-card) !important;
		}

		[data-theme="dark"] #modal-filtro-tempo>div>div:first-child {
			background: linear-gradient(135deg, #1a237e, #283593) !important;
		}

		[data-theme="dark"] .secao-header:not(:first-child) {
			border-top-color: var(--border-color);
		}

		[data-theme="dark"] .secao-count {
			background: rgba(255, 255, 255, 0.1);
		}

		[data-theme="dark"] .secao-vazia {
			color: var(--text-label);
		}
	</style>
</head>

<body>
	<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">

		<?php require 'include/menu.php'; ?>

		<div class="mdl-grid">
			<a href='javascript:void(0)' class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored btn-blue center-block">
				Adicionar Comanda
				<i class="material-icons">add_circle</i>
			</a>
			<hr>
			<div style="padding:0 8px 10px; display:flex; align-items:center;">
				<button id="btn-filtro-tempo" type="button" style="display:flex; align-items:center; gap:4px; padding:8px 14px; border-radius:20px; border:2px solid #3f51b5; background:#fff; color:#3f51b5; font-size:13px; font-weight:700; cursor:pointer; white-space:nowrap; box-shadow:0 1px 4px rgba(0,0,0,.1); transition:all .2s;">
					<i class="material-icons" style="font-size:18px;">schedule</i>
					<span id="btn-filtro-tempo-label">Tempo</span>
				</button>
			</div>
			<?php foreach ($comandas as $comanda):
				$n_comanda = $comanda->ven_026;
				$sql = "SELECT ven_009 as subtotal,  ((ven_009 * 0.10) + ven_009) as total, (ven_009 * 0.10) as servico, ven_001 ";
				$sql .= "FROM venda ";
				$sql .= "WHERE ven_026 = {$n_comanda} AND ven_024 = 'C' AND sit_001 = 8 ";
				$stm = $pdo->prepare($sql);
				$stm->execute();
				$totalizadores = $stm->fetch(PDO::FETCH_OBJ);

				$stmTempo = $pdo->prepare("SELECT MAX(data_cadastro) as ultimo_pedido FROM vendaitem WHERE ven_001 = :venda AND sit_001 = 4");
				$stmTempo->execute([':venda' => $totalizadores->ven_001]);
				$ultimoPedido = $stmTempo->fetch(PDO::FETCH_OBJ);
				$tempoFormatado = formatarTempo($ultimoPedido->ultimo_pedido ?? '');
				$tempoMinutos = calcularMinutos($ultimoPedido->ultimo_pedido ?? '');
			?>
				<div class="mdl-card mdl-shadow--4dp comanda" data-tempo-min="<?= $tempoMinutos ?>">
					<div class="mdl-card__title">
						<h4 class="mdl-card__supporting-text">
							Comanda <?= $comanda->ven_026 ?> | <?= $comanda->ven_027 ?>
							<?php if (!empty($comanda->cli_001) && $comanda->cli_001 > 0 && !empty($comanda->nome_cliente)): ?>
								<br><small style="font-size:12px; color:#3f51b5;"><i class="material-icons" style="font-size:14px; vertical-align:middle;">person</i> <?= htmlspecialchars($comanda->nome_cliente) ?></small>
							<?php endif; ?>
						</h4>
						<a href="comanda.php?comanda=<?= $comanda->ven_026 ?>&cliente=<?= $comanda->ven_027 ?>">
							<i class="material-icons green">search</i>
						</a>
					</div>
					<span>
						<?php if (TAXA_COMANDA): ?>
							Valor R$ <?= number_format($totalizadores->total, 2, ',', '.') ?>
						<?php else: ?>
							Valor R$ <?= number_format($totalizadores->subtotal, 2, ',', '.') ?>
						<?php endif; ?>
					</span>
					<?php if (!empty($tempoFormatado)): ?>
						<span style="display:block; font-size:8px; color:#999; padding:2px 16px 6px; text-transform:lowercase;">
							<i class="material-icons" style="font-size:8px; vertical-align:middle;">schedule</i> <?= $tempoFormatado ?>
						</span>
					<?php endif; ?>
				</div>
			<?php endforeach; ?>
		</div>
	</div>
	<dialog class="mdl-dialog">
		<form>
			<div class="mdl-dialog__content">
				<p>
				<h5>Abrir Comanda</h5>
				<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
					<input class="mdl-textfield__input" type="text" id="cliente" required>
					<label class="mdl-textfield__label" for="sample3">Nome do Cliente (* Obrigatório)</label>
				</div>
				</p>
			</div>
			<div class="mdl-dialog__actions">
				<button type="button" class="mdl-button close">Cancelar</button>
				<button type="button" class="mdl-button mdl-button--raised mdl-button--colored pedido">Lançar Item</button>
			</div>
		</form>
	</dialog>

	<!-- Modal Filtro Tempo -->
	<div id="modal-filtro-tempo" style="display:none; position:fixed; inset:0; z-index:9999; background:rgba(0,0,0,.4); backdrop-filter:blur(4px); -webkit-backdrop-filter:blur(4px); align-items:center; justify-content:center;">
		<div style="background:#fff; border-radius:16px; width:90%; max-width:360px; box-shadow:0 8px 32px rgba(0,0,0,.25); overflow:hidden;">
			<div style="background:linear-gradient(135deg,#3f51b5,#5c6bc0); padding:18px 20px; display:flex; align-items:center; justify-content:space-between;">
				<div>
					<div style="display:flex; align-items:center; gap:8px; color:#fff; font-size:17px; font-weight:700;"><i class="material-icons" style="font-size:22px;">schedule</i> Filtro por Tempo</div>
					<div style="color:rgba(255,255,255,.8); font-size:12px; margin-top:4px;">Sem novos pedidos há mais de...</div>
				</div>
				<button id="modal-tempo-close" type="button" style="background:rgba(255,255,255,.15); border:none; cursor:pointer; padding:6px; border-radius:50%;"><i class="material-icons" style="color:#fff; font-size:20px;">close</i></button>
			</div>
			<div style="padding:20px; display:grid; grid-template-columns:1fr 1fr; gap:10px;">
				<button class="tempo-opt" data-tempo="0" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#e8eaf6; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">visibility</i> Todos</button>
				<button class="tempo-opt" data-tempo="10" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 10 min</button>
				<button class="tempo-opt" data-tempo="20" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 20 min</button>
				<button class="tempo-opt" data-tempo="30" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 30 min</button>
				<button class="tempo-opt" data-tempo="40" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 40 min</button>
				<button class="tempo-opt" data-tempo="50" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 50 min</button>
				<button class="tempo-opt" data-tempo="60" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; grid-column:span 2; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 1 hora</button>
			</div>
		</div>
	</div>

	<script src="js/jquery.min.js"></script>
	<script>
		if (localStorage.hasOwnProperty('carrinho')) {
			localStorage.removeItem('carrinho')
		}

		var dialog = document.querySelector('dialog')
		if (!dialog.showModal) {
			dialogPolyfill.registerDialog(dialog);
		}

		// ── Tempo filter (modal) ─────────────────────────────────────
		var tempoFiltroAtivo = 0;

		$('#btn-filtro-tempo').on('click', function() {
			$('#modal-filtro-tempo').css('display', 'flex');
		});
		$('#modal-tempo-close').on('click', function() {
			$('#modal-filtro-tempo').hide();
		});
		$('#modal-filtro-tempo').on('click', function(e) {
			if (e.target === this) $(this).hide();
		});

		$('.tempo-opt').on('click', function() {
			tempoFiltroAtivo = parseInt($(this).data('tempo')) || 0;
			$('.tempo-opt').css({
				border: '2px solid #c5cae9',
				background: '#f5f5ff',
				color: '#3f51b5'
			});
			$(this).css({
				border: '2px solid #3f51b5',
				background: '#e8eaf6',
				color: '#3f51b5'
			});
			if (tempoFiltroAtivo === 0) {
				$('#btn-filtro-tempo-label').text('Tempo');
				$('#btn-filtro-tempo').css({
					background: '#fff',
					color: '#3f51b5'
				});
			} else {
				var lbl = tempoFiltroAtivo >= 60 ? '> ' + Math.floor(tempoFiltroAtivo / 60) + 'h' : '> ' + tempoFiltroAtivo + 'min';
				$('#btn-filtro-tempo-label').text(lbl);
				$('#btn-filtro-tempo').css({
					background: '#3f51b5',
					color: '#fff'
				});
			}
			$('#modal-filtro-tempo').hide();
			$('.comanda[data-tempo-min]').each(function() {
				var tMin = parseInt($(this).attr('data-tempo-min')) || 0;
				$(this).toggle(tempoFiltroAtivo === 0 || tMin >= tempoFiltroAtivo);
			});
		});

		jQuery(document).ready(function($) {

			$('.mdl-js-button').click(function(event) {
				dialog.showModal();
			});

			$('.close').click(function(event) {
				dialog.close();
			});

			$('.pedido').click(function(event) {
				var cliente = $('#cliente').val();

				if (cliente != '') {
					dialog.close();
					window.location = 'comanda.php?cliente=' + cliente;
				}
			});

		});
	</script>
</body>

</html>