<?php
if ((isset($_COOKIE['id']) && $_COOKIE['id'] != '') &&
	(isset($_COOKIE['usuario']) && $_COOKIE['usuario'] != '')
):
	header("Location: mesas.php");
	die();
endif;

require 'conexao.php';
require 'config.php';
require 'includes/limpar_session.php';

$pdo  = Conexao::getInstance();
$sql = "SELECT b_pdv_coletivo FROM empresas LIMIT 1";
$stm = $pdo->prepare($sql);
$stm->execute();
$empresa = $stm->fetch(PDO::FETCH_OBJ);

if ($empresa->b_pdv_coletivo):
	$pdo  = Conexao::getInstance();
	$sql = "SELECT id_caixa FROM caixa WHERE id_situacao = 4";
	$stm = $pdo->prepare($sql);
	$stm->execute();
	$caixa = $stm->fetch(PDO::FETCH_OBJ);
else:
	$pdo  = Conexao::getInstance();
	$sql = "SELECT id_caixa FROM caixa WHERE id_situacao = 4 AND (terminal = '" . SERVIDOR . "')";
	$stm = $pdo->prepare($sql);
	$stm->execute();
	$caixa = $stm->fetch(PDO::FETCH_OBJ);
endif;

$sql = "SELECT usu_003, usu_002 FROM usuarios WHERE sit_001 = 4 AND b_funcao_garcom = TRUE ORDER BY usu_002";
$stm = $pdo->prepare($sql);
$stm->execute();
$usuarios = $stm->fetchAll(PDO::FETCH_OBJ);

?>
<!DOCTYPE html>
<html>

<head>
	<title>Comanda Eletrônica</title>
	<?php require 'includes/inc_head.php'; ?>
	<style>
		body {
			background: #f0f2f8;
		}

		.login-wrapper {
			min-height: 70vh;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 24px 16px;
			box-sizing: border-box;
		}

		.login-logo {
			text-align: center;
			margin-bottom: 18px;
		}

		.login-logo h1 {
			color: #3f51b5;
			font-size: 52px;
			font-weight: 900;
			letter-spacing: -1px;
			margin: 0;
			padding: 0;
		}

		.login-logo p.subtitulo {
			color: #888;
			font-size: 13px;
			font-weight: 600;
			letter-spacing: 2px;
			text-transform: uppercase;
			margin: 4px 0 2px;
		}

		.login-logo p.versao {
			color: #bbb;
			font-size: 13px;
			margin: 0;
		}

		.login-card {
			background: #fff;
			border: 1px solid #e0e3eb;
			border-radius: 16px;
			box-shadow: 0 4px 24px rgba(0, 0, 0, 0.07);
			width: 100%;
			max-width: 380px;
			padding: 28px 24px 24px;
			box-sizing: border-box;
		}

		.login-card .alert-caixa {
			background: #fff5f5;
			border: 1.5px solid #f5c6c6;
			border-radius: 10px;
			padding: 16px;
			color: #c0392b;
			font-size: 13px;
			font-weight: 600;
			text-align: center;
			line-height: 1.5;
		}

		.login-field {
			display: flex;
			flex-direction: column;
			gap: 6px;
			margin-bottom: 16px;
		}

		.login-field label {
			font-size: 12px;
			font-weight: 700;
			color: #666;
			text-transform: uppercase;
			letter-spacing: 0.5px;
			display: block !important;
			width: auto !important;
		}

		.login-field select,
		.login-field input {
			width: 100%;
			padding: 12px 14px;
			border: 1.5px solid #e0e3eb;
			border-radius: 10px;
			font-size: 15px;
			background: #fafbfd;
			outline: none;
			box-sizing: border-box;
			transition: border-color 0.2s;
		}

		.login-field select:focus,
		.login-field input:focus {
			border-color: #3f51b5;
			background: #fff;
		}

		.login-btn {
			display: block;
			width: 100%;
			height: 50px;
			border: none;
			border-radius: 12px;
			background: #3f51b5;
			color: #fff;
			font-size: 15px;
			font-weight: 700;
			letter-spacing: 0.5px;
			cursor: pointer;
			text-align: center;
			line-height: 50px;
			margin-top: 8px;
			transition: background 0.2s;
			box-sizing: border-box;
		}

		.login-btn:active {
			background: #303f9f;
		}

		.login-btn i {
			font-size: 20px;
		}

		.remember-row {
			display: flex;
			align-items: center;
			gap: 10px;
			margin-bottom: 16px;
			cursor: pointer;
		}

		.remember-row input[type=checkbox] {
			width: 18px;
			height: 18px;
			accent-color: #3f51b5;
			cursor: pointer;
			flex-shrink: 0;
		}

		.remember-row span {
			font-size: 13px;
			color: #666;
			font-weight: 500;
		}

		/* ===== Sync Overlay ===== */
		.sync-overlay {
			position: fixed;
			inset: 0;
			background: rgba(15, 17, 30, 0.82);
			backdrop-filter: blur(8px);
			-webkit-backdrop-filter: blur(8px);
			z-index: 9999;
			display: flex;
			align-items: center;
			justify-content: center;
			opacity: 0;
			visibility: hidden;
			transition: opacity 0.35s ease, visibility 0.35s ease;
		}

		.sync-overlay.active {
			opacity: 1;
			visibility: visible;
		}

		.sync-card {
			background: #fff;
			border-radius: 20px;
			padding: 36px 32px 32px;
			width: 92%;
			max-width: 340px;
			box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
			text-align: center;
			transform: translateY(20px) scale(0.96);
			transition: transform 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
		}

		.sync-overlay.active .sync-card {
			transform: translateY(0) scale(1);
		}

		.sync-spinner {
			width: 56px;
			height: 56px;
			margin: 0 auto 20px;
			position: relative;
		}

		.sync-spinner::before,
		.sync-spinner::after {
			content: '';
			position: absolute;
			inset: 0;
			border-radius: 50%;
			border: 3px solid transparent;
		}

		.sync-spinner::before {
			border-top-color: #3f51b5;
			border-right-color: #3f51b5;
			animation: syncSpin 1s linear infinite;
		}

		.sync-spinner::after {
			inset: 6px;
			border-bottom-color: #7986cb;
			border-left-color: #7986cb;
			animation: syncSpin 1.5s linear infinite reverse;
		}

		.sync-icon {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			font-size: 22px;
			color: #3f51b5;
			animation: syncPulse 2s ease-in-out infinite;
		}

		@keyframes syncSpin {
			to {
				transform: rotate(360deg);
			}
		}

		@keyframes syncPulse {

			0%,
			100% {
				opacity: 1;
				transform: translate(-50%, -50%) scale(1);
			}

			50% {
				opacity: 0.5;
				transform: translate(-50%, -50%) scale(0.85);
			}
		}

		.sync-title {
			font-size: 16px;
			font-weight: 700;
			color: #1a1f36;
			margin: 0 0 4px;
		}

		.sync-subtitle {
			font-size: 13px;
			color: #8892b0;
			margin: 0 0 24px;
			font-weight: 500;
		}

		.sync-progress-track {
			background: #e8ecf4;
			border-radius: 8px;
			height: 6px;
			width: 100%;
			overflow: hidden;
			margin-bottom: 20px;
		}

		.sync-progress-bar {
			height: 100%;
			border-radius: 8px;
			background: linear-gradient(90deg, #3f51b5, #7c4dff);
			width: 0%;
			transition: width 0.5s cubic-bezier(0.4, 0, 0.2, 1);
			position: relative;
		}

		.sync-progress-bar::after {
			content: '';
			position: absolute;
			inset: 0;
			background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
			animation: shimmer 1.5s ease-in-out infinite;
		}

		@keyframes shimmer {
			0% {
				transform: translateX(-100%);
			}

			100% {
				transform: translateX(100%);
			}
		}

		.sync-steps {
			display: flex;
			flex-direction: column;
			gap: 10px;
			text-align: left;
		}

		.sync-step {
			display: flex;
			align-items: center;
			gap: 10px;
			font-size: 13px;
			color: #b0b8cc;
			font-weight: 500;
			transition: color 0.3s ease;
		}

		.sync-step .step-icon {
			width: 24px;
			height: 24px;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 14px;
			background: #eef0f6;
			color: #b0b8cc;
			transition: all 0.3s ease;
			flex-shrink: 0;
		}

		.sync-step.active {
			color: #3f51b5;
		}

		.sync-step.active .step-icon {
			background: #e8eaf6;
			color: #3f51b5;
			animation: stepBounce 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
		}

		.sync-step.done {
			color: #43a047;
		}

		.sync-step.done .step-icon {
			background: #e8f5e9;
			color: #43a047;
		}

		@keyframes stepBounce {
			0% {
				transform: scale(0.7);
			}

			100% {
				transform: scale(1);
			}
		}

		/* ── Dark Mode Toggle ── */
		.theme-toggle-login {
			display: inline-flex;
			align-items: center;
			gap: 8px;
			margin-top: 14px;
			padding: 8px 18px;
			border-radius: 24px;
			border: 1.5px solid #e0e3eb;
			background: rgba(255, 255, 255, 0.7);
			cursor: pointer;
			transition: all 0.25s ease;
			font-size: 13px;
			font-weight: 600;
			color: #666;
			user-select: none;
			-webkit-tap-highlight-color: transparent;
		}

		.theme-toggle-login:active {
			transform: scale(0.96);
		}

		.theme-toggle-login i {
			font-size: 20px;
			color: #3f51b5;
			transition: transform 0.3s ease;
		}

		.theme-toggle-login:hover i {
			transform: rotate(30deg);
		}

		[data-theme="dark"] .theme-toggle-login {
			border-color: var(--border-color);
			background: rgba(30, 30, 30, 0.7);
			color: var(--text-secondary);
		}

		[data-theme="dark"] .theme-toggle-login i {
			color: #ffc107;
		}

		/* ── Dark Theme Overrides ── */
		[data-theme="dark"] body {
			background: var(--bg-body);
		}

		[data-theme="dark"] .login-logo h1 {
			color: var(--color-primary);
		}

		[data-theme="dark"] .login-logo p.subtitulo {
			color: var(--text-secondary);
		}

		[data-theme="dark"] .login-logo p.versao {
			color: var(--text-label);
		}

		[data-theme="dark"] .login-card {
			background: var(--bg-card);
			border-color: var(--border-color);
			box-shadow: 0 4px 24px rgba(0, 0, 0, 0.3);
		}

		[data-theme="dark"] .login-card .alert-caixa {
			background: #3a1515;
			border-color: #6b2020;
			color: #ef9a9a;
		}

		[data-theme="dark"] .login-field label {
			color: var(--text-secondary);
		}

		[data-theme="dark"] .login-field select,
		[data-theme="dark"] .login-field input {
			background: var(--bg-input);
			color: var(--text-primary);
			border-color: var(--border-color);
		}

		[data-theme="dark"] .login-field select:focus,
		[data-theme="dark"] .login-field input:focus {
			background: var(--bg-surface);
			border-color: var(--color-primary);
		}

		[data-theme="dark"] .login-btn {
			background: var(--color-primary);
		}

		[data-theme="dark"] .login-btn:active {
			background: var(--color-primary-dark);
		}

		[data-theme="dark"] .remember-row span {
			color: var(--text-secondary);
		}

		/* Sync overlay */
		[data-theme="dark"] .sync-card {
			background: var(--bg-card);
		}

		[data-theme="dark"] .sync-title {
			color: var(--text-primary);
		}

		[data-theme="dark"] .sync-subtitle {
			color: var(--text-secondary);
		}

		[data-theme="dark"] .sync-progress-track {
			background: var(--border-color);
		}

		[data-theme="dark"] .sync-step {
			color: var(--text-label);
		}

		[data-theme="dark"] .sync-step .step-icon {
			background: var(--bg-surface);
			color: var(--text-label);
		}

		[data-theme="dark"] .sync-step.active {
			color: var(--color-primary);
		}

		[data-theme="dark"] .sync-step.active .step-icon {
			background: #1a237e;
			color: var(--color-primary);
		}

		[data-theme="dark"] .sync-step.done {
			color: #66bb6a;
		}

		[data-theme="dark"] .sync-step.done .step-icon {
			background: #1b3a1d;
			color: #66bb6a;
		}
	</style>
</head>

<body>
	<div class="mdl-layout mdl-js-layout">
		<main class="mdl-layout__content">
			<div class="login-wrapper">
				<div class="login-logo">
					<h1>W-FOOD</h1>
					<p class="subtitulo">Comanda Eletrônica</p>
					<p class="versao"><?= VERSAO ?></p>
					<button type="button" class="theme-toggle-login" id="btnThemeToggleLogin">
						<i class="material-icons" id="themeIconLogin">brightness_6</i>
						<span id="themeLabelLogin">Tema Escuro</span>
					</button>
				</div>

				<div class="login-card">
					<?php if (empty($caixa)) : ?>
						<div class="alert-caixa">
							<i class="material-icons" style="font-size:32px;display:block;margin-bottom:8px;">warning</i>
							<?php if ($empresa->b_pdv_coletivo) : ?>
								O caixa ainda não foi aberto hoje!
							<?php else : ?>
								O caixa ainda não foi aberto hoje no servidor:<br><br>
								Nome do Servidor:<strong> <?= SERVIDOR ?></strong>
							<?php endif; ?>
							<br><span style="color:#999;font-weight:400;font-size:12px;"><br>Use o sistema W-FOOD para abrir o caixa.</span>
						</div>
					<?php else : ?>
						<form id='formulario'>
							<div class="login-field">
								<label for="usuario">Usuário</label>
								<select id="usuario" required>
									<option value="">Selecione...</option>
									<?php foreach ($usuarios as $usuario) : ?>
										<option value="<?= $usuario->usu_003 ?>"><?= $usuario->usu_002 ?></option>
									<?php endforeach; ?>
								</select>
							</div>
							<div class="login-field">
								<label for="senha">Senha</label>
								<input type="password" id="senha" placeholder="Digite sua senha" autocomplete="off">
							</div> <label class="remember-row" for="lembrar">
								<input type="checkbox" id="lembrar">
								<span>Lembrar meu usuário e senha</span>
							</label>
							<button type="submit" id="entrar" class="login-btn">
								ENTRAR
							</button>
						</form>
					<?php endif; ?>
				</div>
			</div>
		</main>
	</div>

	<!-- Sync Overlay -->
	<div class="sync-overlay" id="syncOverlay" role="alert" aria-live="polite" aria-label="Sincronizando dados">
		<div class="sync-card">
			<div class="sync-spinner">
				<i class="material-icons sync-icon">sync</i>
			</div>
			<p class="sync-title">Sincronizando dados</p>
			<p class="sync-subtitle" id="syncSubtitle">Preparando...</p>
			<div class="sync-progress-track">
				<div class="sync-progress-bar" id="syncProgressBar"></div>
			</div>
			<div class="sync-steps">
				<div class="sync-step" id="stepCategorias">
					<span class="step-icon"><i class="material-icons" style="font-size:14px">category</i></span>
					<span>Categorias</span>
				</div>
				<div class="sync-step" id="stepProdutos">
					<span class="step-icon"><i class="material-icons" style="font-size:14px">restaurant_menu</i></span>
					<span>Produtos</span>
				</div>
				<div class="sync-step" id="stepOpcionais">
					<span class="step-icon"><i class="material-icons" style="font-size:14px">tune</i></span>
					<span>Opcionais</span>
				</div>
				<div class="sync-step" id="stepObservacoes">
					<span class="step-icon"><i class="material-icons" style="font-size:14px">notes</i></span>
					<span>Observações</span>
				</div>
			</div>
		</div>
	</div>

	<?php include 'includes/inc_js.php'; ?>
	<script>
		if (localStorage.hasOwnProperty('carrinho')) {
			localStorage.removeItem('carrinho')
		}

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

			// Dark Mode Toggle
			(function() {
				var btn = document.getElementById('btnThemeToggleLogin');
				var icon = document.getElementById('themeIconLogin');
				var label = document.getElementById('themeLabelLogin');
				var current = document.documentElement.getAttribute('data-theme') || 'light';

				function updateUI(theme) {
					if (theme === 'dark') {
						icon.textContent = 'brightness_7';
						label.textContent = 'Tema Claro';
					} else {
						icon.textContent = 'brightness_6';
						label.textContent = 'Tema Escuro';
					}
				}
				updateUI(current);

				if (btn) {
					btn.addEventListener('click', function() {
						var cur = document.documentElement.getAttribute('data-theme');
						var next = (cur === 'dark') ? 'light' : 'dark';
						document.documentElement.setAttribute('data-theme', next);
						localStorage.setItem('wfood-theme', next);
						updateUI(next);
					});
				}
			})();

			// Restaurar dados salvos
			var savedUsuario = localStorage.getItem('login_usuario')
			var savedSenha = localStorage.getItem('login_senha')
			if (savedUsuario && savedSenha) {
				$('#usuario').val(savedUsuario)
				$('#senha').val(savedSenha)
				$('#lembrar').prop('checked', true)
			}

			$('#formulario').submit(function(event) {
				var usuario = $('#usuario').val();
				var senha = $('#senha').val();
				var lembrar = $('#lembrar').prop('checked');

				if (lembrar) {
					localStorage.setItem('login_usuario', usuario)
					localStorage.setItem('login_senha', senha)
				} else {
					localStorage.removeItem('login_usuario')
					localStorage.removeItem('login_senha')
				}

				if (usuario != '' && senha != '') {
					$.ajax({
						url: 'login.php',
						type: 'POST',
						dataType: 'JSON',
						data: {
							usuario: usuario,
							senha: senha
						},
						beforeSend: function() {
							ProcessingModal.show({});
						},
						success: function(retorno) {
							ProcessingModal.hide();
							if (retorno.status == '1') {

								// Mostrar overlay de sincronização
								var $overlay = $('#syncOverlay');
								var $bar = $('#syncProgressBar');
								var $subtitle = $('#syncSubtitle');

								function setSyncStep(stepId, text, progress) {
									$('.sync-step.active').removeClass('active').addClass('done');
									$('#' + stepId).addClass('active');
									$subtitle.text(text);
									$bar.css('width', progress + '%');
								}

								$overlay.addClass('active');

								setSyncStep('stepCategorias', 'Baixando categorias...', 10);
								$.get('pesquisa_categoria_json.php', function(data, status, xhr) {
									if (xhr.status == 200) {
										localStorage.setItem('categorias', data);

										setSyncStep('stepProdutos', 'Baixando produtos...', 35);
										$.get('pesquisa_produto_json.php', function(data, status, xhr) {
											if (xhr.status == 200) {
												localStorage.setItem('produtos', data)

												setSyncStep('stepOpcionais', 'Baixando opcionais...', 60);
												$.get('pesquisa_opcional_json.php', function(data, status, xhr) {
													if (xhr.status == 200) {
														localStorage.setItem('opcionais', data)

														setSyncStep('stepObservacoes', 'Baixando observações...', 85);
														$.get('pesquisa_observacao_json.php', function(data, status, xhr) {
															if (xhr.status == 200) {
																localStorage.setItem('observacoes', data)

																$('.sync-step.active').removeClass('active').addClass('done');
																$bar.css('width', '100%');
																$subtitle.text('Tudo pronto!');

																setTimeout(function() {
																	window.location.href = retorno.url;
																}, 400);
															}
														})
													}
												})
											}
										})
									}
								})
							} else {
								swal(
									'Erro',
									retorno.text,
									'error'
								)
							}
						}
					});
				} else {
					swal(
						'Alerta',
						'Informar Usuário e Senha!',
						'warning'
					)
				}

				return false;
			});

		});
	</script>
</body>

</html>