<?php
//Nota para mim mesmo, para melhoria no javascript:
//quando o usário aperta 'enter', o formulário dá evento de submit (botaoGerarPix) -- eu quero que vá para a proxima etapa (sim, eu sei q só usamos celular mas gosto de aprimoramentos)
//Depois eu ajeito isso. o que importa atualmente é a validação, que já temos.
//      - NLO

include_once('../nlo-config.php');

// Pega CPF (ou "document") via GET
if (isset($_GET['cpf']) && !empty($_GET['cpf'])) {
    $cpf = urldecode($_GET['cpf']);
} elseif (isset($_GET['document']) && !empty($_GET['document'])) {
    $cpf = urldecode($_GET['document']);
};

if (isset($_GET['email']) && !empty($_GET['email'])) {
    $email = urldecode($_GET['email']);
};

// Pega CPF (ou "document") via GET
if (isset($_GET['nome']) && !empty($_GET['nome'])) {
    $nome = urldecode($_GET['nome']);
} elseif (isset($_GET['name']) && !empty($_GET['name'])) {
    $nome = urldecode($_GET['name']);
};

// Pega número de telefone (ou "phone") via GET
if (isset($_GET['telefone']) && !empty($_GET['telefone'])) {
    $telefone = urldecode($_GET['telefone']);
} elseif (isset($_GET['phone']) && !empty($_GET['phone'])) {
    $telefone = urldecode($_GET['phone']);
} elseif (isset($_GET['telephone']) && !empty($_GET['telephone'])) {
    $telefone = urldecode($_GET['telephone']);
};

$upsell = $upsell . "?cpf=" . urlencode($cpf) . "&nome=" . urlencode($nome) . "&telefone=" . urlencode($telefone) . "&email=" . urlencode($email);
?>

<!DOCTYPE html>
<html lang="pt-BR">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Oferta Especial - Checkout</title>
    <meta name="description" content="Plataforma de pagamentos" />
    <!-- <link
      rel="icon"
      href="favicon.png"
      type="image/png"
    /> -->
	<!-- <link rel="icon" type="image/x-icon" href="./images/favicon.ico" /> -->
    <link rel="stylesheet" href="css/styles-new.css" />
    <link
      href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
      rel="stylesheet"
    />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap"
      rel="stylesheet"
    />
    <script src="https://unpkg.com/@phosphor-icons/web"></script>
    <?php
    
    if($track_fb_pixel == 1){ ?>
    <!-- Meta Pixel Code -->
    <script>
      !function(f,b,e,v,n,t,s)
      {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
      n.callMethod.apply(n,arguments):n.queue.push(arguments)};
      if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
      n.queue=[];t=b.createElement(e);t.async=!0;
      t.src='https://connect.facebook.net/en_US/fbevents.js';
      s=b.getElementsByTagName(e)[0];
      s.parentNode.insertBefore(t,s)}(window, document,'script');
    
      fbq('init', '<?php echo $fb_pixel; ?>'); // Substitua com o ID do seu pixel
      fbq('track', 'PageView');
    </script>
    <noscript>
      <img height="1" width="1" style="display:none"
           src="https://www.facebook.com/tr?id=<?php echo $fb_pixel; ?>&ev=PageView&noscript=1"/>
    </noscript>
    <!-- End Meta Pixel Code -->
    <?php }; ?>
  </head>
  <body class="font-inter">
    <main class="bg-gray-100">
      <div id="checkoutForm">
		<?php if($logo_ativo == 1){ ?>
        <div style="display:flex; text-align: center; padding: 10px 0; background: #f3f3f3; width:100%; justify-content:center; align-items: center; padding: 1.5rem 15px; justify-content: space-between">
          <img src="<?php echo $logo_url; ?>" style="height: 64px; max-width: 150px; object-fit: contain;" />
          <img src="./images/pagamento_seguro.svg" />
        </div>
		<?php }; ?>
		<?php if($exibir_texto == 1){; ?>
			<div class="texto-promocional" style="font-weight:400; padding:16px; background-color:<?php echo $texto_fundo; ?>; margin-bottom:24px">
				<span><?php echo $texto; ?></span>
			</div>
		<?php }; ?>
		<?php if($banner_ativo == 1){ ?>
	    <div class="banner" style="width:100%;height:auto; line-height:0; margin: 0.8rem 0">
          <img style="width:100%" src="<?php echo $banner_url; ?>">
        </div>
		<?php }; ?>
        <div class="container" style="padding-top:0">
          <aside class="cart-summary" style="padding:1rem">
<section>
              <div class="cart-header">
                <h2>Seu carrinho</h2>
               
              </div>
              <!-- <div class="cart-item" style="/* border-bottom: 1px solid #e5e7eb; */ padding-bottom: 1rem;margin-bottom: 0.5rem;">
                <div class="item-details">
                  <div class="item-image">
                    <img src="images/sedex.png">
                  </div>
                  <div class="item-info">
                    <span class="item-name">Envio selecionado</span>
                    <div class="item-meta">
                      <span>Cartão 4700 Limite</span>
                    </div>
                  </div>
			  <div class="cart-total">
                <span class="p-amount">1 un.</span>
              </div>
                </div>
              </div> -->
            <div class="cart-item" style="border-bottom: 1px solid #e5e7eb;padding-bottom: 1rem;margin-bottom: 0.5rem;">
                <div class="item-details">
                  <div class="item-image" style="border-radius:4px">
                    <img src="<?php echo $produto_img; ?>">
                  </div>
                  <div class="item-info">
                    <span class="item-name"><?php echo $produto_nome; ?></span>
                    <div class="item-meta">
                      <span><?php echo $produto_desc; ?></span>
                    </div>
                  </div>

              <!-- <div class="cart-subtotal">
                <span>Subtotal</span>
                <span>R$ 00,00</span>
              </div>
              <div class="cart-shipping" id="cartShipping" style="display: none;">
                <span>Frete</span>
                <span id="shippingValue">R$ 32,82</span>
              </div> -->
			  <div class="cart-total">
                <!-- <span>Total</span>-->
                <span class="p-amount">1 un.</span>
                <!-- <div class="input-number">

                    <button class="btn-sub">
                        <img src="https://pay.pagamentostiktok.shop/assets/img/minus.svg">
                    </button>

                    <input type="number" value="1" min="1" max="99" step="1">
                    <button type="button" class="btn-add">
                        <img src="https://pay.pagamentostiktok.shop/assets/img/plus.svg">
                    </button>

                </div> -->
              </div>
                </div>
              </div>
              <div class="cart-subtotal" style="margin-top:1rem; justify-content:unset; flex-direction:column">
                <div style="display:flex;justify-content:space-between">
                <span style="
    font-weight: 400;
    font-size: 14px;
    color: #585858;
">Subtotal</span>
                <span style="
    font-weight: 400;
    font-size: 14px;
    color: #585858;
"><?php echo $valor_exibicao; ?></span>
                </div>

                <?php if($frete_ativo == 1){ ?>
                <div style="display:flex;justify-content:space-between">
                <span style="
    font-weight: 400;
    font-size: 14px;
    color: #585858;
">Frete</span>
                <span id="valorFrete" style="
    font-weight: 400;
    font-size: 14px;
    color: #585858;
">-</span>
                </div>
                <?php }; ?>
              </div>
              <div class="cart-total">
                <span>Total</span>
                <strong id="totalValue"><?php echo $valor_exibicao; ?></strong>
              </div></section>
          </aside>
          <form class="checkout-form" id="paymentForm">
            <!-- Added step progress indicator -->
			<div class="checkout-steps">
				<div class="step active" data-step="1">
					<div class="step-number">1</div>
					<div class="step-label">Identificação</div>
				</div>

				<?php if ($frete_ativo == 1) { ?>
				<div class="step" data-step="2">
					<div class="step-number">2</div>
					<div class="step-label">Entrega</div>
				</div>
				<?php }; ?>
				<div class="step" data-step="<?php echo ($frete_ativo == 1) ? '3' : '2'; ?>">
					<div class="step-number"><?php echo ($frete_ativo == 1) ? '3' : '2'; ?></div>
					<div class="step-label">Pagamento</div>
				</div>
			</div>

            <!-- Step 1: Identification -->
            <div class="step-content" id="step1" style="display: block;">
              <div class="form-section" style="padding:1rem">
                <h2>Identificação</h2>
                <div class="form-grid">
                  <div class="form-group">
                    <label for="email">E-mail</label>
                    <div class="email-input-wrapper">
                      <input
                        type="email"
                        id="email"
                        name="email"
                        placeholder="email@gmail.com"
                        required
                        autocomplete="off"
                      <?php if($email && !empty($email)){echo "value='$email'";}; ?>
                      />
                      <div id="emailSuggestions" class="email-suggestions"></div>
                    </div>
                  </div>
                  <div class="form-group">
                    <label for="phone">Telefone</label>
                    <input
                      type="tel"
                      id="phone"
                      name="phone"
                      placeholder="(99) 99999-9999"
                      <?php if($telefone && !empty($telefone)){echo "value='$telefone'";}; ?>
                      required
                    />
                  </div>
                  <div class="form-group">
                    <label for="name">Nome completo</label>
                    <input
                      type="text"
                      id="name"
                      name="name"
                      placeholder="Seu nome completo"
                      <?php if($nome && !empty($nome)){echo "value='$nome'";}; ?>
                      required
                      maxlength="30"
                    />
                  </div>
                  <div class="form-group">
                    <label for="cpf">CPF</label>
                    <input
                      type="text"
                      id="cpf"
                      name="cpf"
                      placeholder="123.456.789-12"
                      <?php if($cpf && !empty($cpf)){echo "value='$cpf'";}; ?>
                      required
                    />
                  </div>
                </div>
					<div class="dados-seguros">
						<span>Usamos seus dados de forma 100% segura para garantir a sua satisfação:</span>
						<ul>
							<li>
								<img src="./images/checkmarkSecurity.svg">
								<span>Enviar o seu comprovante de compra e pagamento;</span>
							</li>
							<li>
								<img src="./images/checkmarkSecurity.svg">
								<span>Ativar a sua garantia de devolução caso não fique satisfeito;</span>
							</li>
							<li>
								<img src="./images/checkmarkSecurity.svg">
								<span>Acompanhar o andamento do seu pedido;</span>
							</li>
						</ul>
					</div>
				<div class="step-buttons">
					<button id="botaoEntrega" type="button" class="step-button next-step" data-next="2"><?php echo ($frete_ativo == 1) ? 'Ir para a Entrega' : 'Ir para o Pagamento' ?></button>
				</div>
              </div>
            </div>

            <?php if($frete_ativo == 1){ ?>
            <!-- Step 2: Delivery -->
            <div class="step-content" id="step2" style="display: none;">
              <div class="form-section" style="padding:1rem">
                <h2>Endereço de entrega</h2>
                  <div class="form-group">
                    <label for="cep">CEP</label>
                    <input
                      type="text"
                      id="cep"
                      name="cep"
                      placeholder="00000-000"
                      required
                      maxlength="9"
                    />
                    <div id="cepError" class="error-message" style="display: none;"></div>
                  </div>
                
                <!-- Address fields (initially hidden) -->
                <div id="addressFields" style="display: none;">
                  <div class="form-grid">
                    <div class="form-group">
                      <label for="street">Endereço</label>
                      <input
                        type="text"
                        id="street"
                        name="street"
                        placeholder="Rua/Avenida"
                        readonly
                      />
                    </div>
                    <div class="form-group">
                      <label for="number">Número</label>
                      <input
                        type="text"
                        id="number"
                        name="number"
                        placeholder="Número"
                        required
                      />
                    </div>
                    <div class="form-group">
                      <label for="neighborhood">Bairro</label>
                      <input
                        type="text"
                        id="neighborhood"
                        name="neighborhood"
                        placeholder="Bairro"
                        readonly
                      />
                    </div>
                    <div class="form-group">
                      <label for="complement">Complemento</label>
                      <input
                        type="text"
                        id="complement"
                        name="complement"
                        placeholder="Apartamento, bloco, etc."
                      />
                    </div>
                    <div class="form-group">
                      <label for="city">Cidade</label>
                      <input
                        type="text"
                        id="city"
                        name="city"
                        placeholder="Cidade"
                        readonly
                      />
                    </div>
                    <div class="form-group">
                      <label for="state">Estado</label>
                      <input
                        type="text"
                        id="state"
                        name="state"
                        placeholder="Estado"
                        readonly
                      />
                    </div>
                  </div> <!-- fim grid -->

                  <!-- Delivery options using PHP data -->
                  <div class="delivery-options">
                    <h3>Escolha a forma de entrega</h3>
                    
                    <?php foreach($fretes as $index => $frete): ?>
                    <div class="delivery-option <?php echo $index === 0 ? 'selected' : ''; ?>" data-price="<?php echo number_format($frete['valor'], 2, '.', ''); ?>" data-name="<?php echo $frete['nome']; ?>">
                      <?php if($index === 0): ?>
                      <div class="delivery-badge recommended">Recomendado</div>
                      <?php endif; ?>
                      <div class="delivery-info">
                        <div class="delivery-left">
                          <input type="radio" name="delivery" value="<?php echo strtolower($frete['nome']); ?>" <?php echo $index === 0 ? 'checked' : ''; ?>>
                          <div class="delivery-details">
                            <div class="delivery-name">
                              <span class="delivery-icon"><?php echo $index === 0 ? '📦' : ($index === 1 ? '🚚' : '⚡'); ?></span>
                              <?php echo $frete['nome']; ?>
                            </div>
                            <div class="delivery-time"><?php echo $frete['prazo_estimado']; ?></div>
                          </div>
                        </div>
                        <div class="delivery-price">
                          <span class="price-label">R$</span>
                          <span class="price-value"><?php echo number_format($frete['valor'], 2, ',', '.'); ?></span>
                        </div>
                      </div>
                    </div>
                    <?php endforeach; ?>
                  </div>
                </div>

				<div class="frete-container">
				  <div class="frete-title">
					Escolha o melhor frete para você
				  </div>

				  <div class="frete-info">
					<span class="aviso-principal">
					  Preencha seu CEP para encontrar o melhor frete
					</span>
					<span class="aviso-secundario">
					  Após preenchido, encontraremos as melhores opções pra você
					</span>
				  </div>

				  <p class="frete-observacao">
					  A previsão de entrega pode variar de acordo com a região e facilidade de acesso ao seu endereço
				  </p>
				</div>

                <div class="step-buttons">
                  <button type="button" class="step-button next-step" data-next="3" id="continueToPayment" disabled>Ir para o Pagamento</button>
                  <button type="button" class="step-button prev-step" data-prev="1">Voltar</button>
                </div>
              </div>
            </div>
            <?php }; ?>

            <!-- Step 3: Payment -->
            <div class="step-content" id="<?php echo ($frete_ativo == 1) ? 'step3' : 'step2'; ?>" style="display: none;">
              <div class="form-section payment-section" style="padding:1rem">
                <h2>Pagamento</h2>
                <div class="payment-method">
                  <div class="payment-option">
                    <img
                      src="images/card-pix.svg"
                      alt="PIX"
                      class="payment-icon"
                    />
                    <span class="payment-label">PIX</span>
                  </div>
                </div>
                <div style="border: 1px solid #ddd; padding: 1rem; margin-bottom:16px; border-radius:4px"><span style="font-family: Inter;
    font-style: normal;
    font-weight: 400;
    font-size: 16px;
    color: #7e7e7e;
    text-align: left;">
                        Ao selecionar o Pix, você será encaminhado para um ambiente seguro para finalizar
                        seu pagamento.
                    </span></div>
                
                <div class="step-buttons">
                  <button type="button" class="step-button prev-step" data-prev="<?php echo ($frete_ativo == 1) ? '2' : '1'; ?>">Voltar</button>
                  <button id="botaoGerarPix" type="submit" class="submit-button" style="background-color:#23d07d;padding:16px 24px; cursor:pointer; border-radius: 4px; text-transform: uppercase; font: normal normal 700 16px / 20px Inter;">Gerar PIX</button>
                </div>
              </div>
            </div>
          </form>
			<?php if($prova_social_ativa == 1){ ?>
				<div class="prova-social-container" style="background-color:white;border-radius:12px; padding:1rem; margin-top:0">
					<?php
                		$total = count($provas_sociais);
                		foreach ($provas_sociais as $index => $prova){ ?>
					<div class="prova-social" style="padding:0">
					  <div class="avatar">
						<img src="<?php echo $prova['avatar']; ?>" alt="Avatar">
					  </div>
					  <div class="conteudo">
						<div class="estrelas">
						  <span class="estrela-icon">★</span><span class="estrela-icon">★</span><span class="estrela-icon">★</span><span class="estrela-icon">★</span><span class="estrela-icon">★</span>
						</div>
						<div class="nome"><?php echo $prova['nome']; ?></div>
						<div class="mensagem"><?php echo $prova['mensagem']; ?></div>
					  </div>
					</div>
			<?php 
			if ($index < $total - 1) {
				echo '<hr style="/*margin-top: 1rem; margin-bottom: 1rem;*/ border: 0; border-top: 1px solid rgba(0, 0, 0, .1); width: 100%; box-sizing: content-box; height: 0; overflow: visible;">';
			}
			?>
		<?php }; ?>
				</div>
			<?php }; ?>
        </div>
      </div>


      <!-- Tela do PIX (inicialmente oculta) -->
		<?php if($logo_ativo == 1){ ?>
        <div id="pixscreenheader" style="display:flex; text-align: center; background: white; width:100%; justify-content:center; align-items: center; padding: 5px 30px; justify-content: space-between; display:none">
          <img src="<?php echo $logo_url; ?>" style="height: 64px; max-width: 150px; object-fit: contain;">
          <img src="./images/pagamento_seguro.svg">
        </div>
		<?php }; ?>
      <div id="pixScreen" style="display: none">
        <h2 style="font: normal normal bold 18px / 23px Inter; color: #4b4b4b">
          Falta pouco! Para finalizar a compra, efetue o pagamento com PIX!
        </h2>
		<div class="pix-container">
			<div class="qr-code-container" style="background: white;border-radius: 8px;border: 1px solid #9f9f9f; display: none">
			  <div id="qrcode"></div>
			</div>

            <p class="pix-copy-text" style="
                font: normal normal normal 16px/18px Inter;
                color: black;
            ">
			   Copie a chave abaixo e utilize a <br>opção <b>PIX Copia e Cola</b>:
			</p>

			<div class="pix-code-container">
			  <input type="text" id="pixCode" readonly style="background: white;
    font: normal normal normal 16px / 18px Inter;
    border: 1px solid #9f9f9f;
    padding: 13px 15px;
    border-radius: 8px;" />
			  <button id="copyPixButton" class="copy-button" style="border-radius: 4px;padding: 14px 28px;">
				<svg viewBox="0 0 24 24" width="24" height="24">
				  <path
					d="M20 2H10c-1.103 0-2 .897-2 2v4H4c-1.103 0-2 .897-2 2v10c0 1.103.897 2 2 2h10c1.103 0 2-.897 2-2v-4h4c1.103 0 2-.897 2-2V4c0-1.103-.897-2-2-2zM4 20V10h10l.002 10H4zm16-6h-4v-4c0-1.103-.897-2-2-2h-4V4h10v10z"
				  ></path>
				</svg>
				COPIAR CÓDIGO
			  </button>
			</div>
		</div>
					<div class="payment-instructions" style="margin-top:1.3rem">
<h3 style="
    text-align: center;
    font-weight: 400;
    margin-bottom: 20px; color:#393939;
">Valor a ser pago: <span style="color:#41c286; font-weight:600; margin-left:10px" id="totalPixScreen"></span></h3>
			  <h3>Instruções para pagamento</h3>
			  <div class="instruction-step">
				<div class="step-icon">
				  <i class="ph ph-bank"></i>
				</div>
				<p>Abra o app do seu banco e entre no ambiente Pix</p>
			  </div>
			  <div class="instruction-step">
				<div class="step-icon">
				  <i class="ph ph-qr-code"></i>
				</div>
				<p>
				  Escolha Pagar com QR Code e aponte a câmera para o código ao lado.
				</p>
			  </div>
			  <div class="instruction-step">
				<div class="step-icon">
				  <i class="ph ph-check-circle"></i>
				</div>
				<p>Confirme as informações e finalize seu pagamento.</p>
			  </div>
			</div>
      </div>

      <!-- Adicione após o form e antes da tela do PIX -->
      <div id="loadingScreen" class="loading-screen" style="display: none">
        <div class="loading-content">
          <div class="loading-spinner"></div>
          <h2>Gerando seu PIX...</h2>
          <p>Aguarde um momento</p>
        </div>
      </div>
    </main>

    <footer>
      <button class="security-button">
<img src="./images/safe.svg" alt="Green Shield Icon" style="margin-right:10px">
        <!-- <svg viewBox="0 0 24 24" class="security-icon">
          <path
            d="M11.488 21.754c.294.157.663.156.957-.001 8.012-4.304 8.581-12.713 8.574-15.104a.988.988 0 0 0-.596-.903l-8.05-3.566a1.005 1.005 0 0 0-.813.001L3.566 5.747a.99.99 0 0 0-.592.892c-.034 2.379.445 10.806 8.514 15.115zM8.674 10.293l2.293 2.293 4.293-4.293 1.414 1.414-5.707 5.707-3.707-3.707 1.414-1.414z"
          ></path>
        </svg> -->
        Ambiente seguro
      </button>
    </footer>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
	<script>
	const upsellUrl = "<?php echo $upsell; ?>";
	const oferta = "<?php echo $oferta; ?>";
    let valorTotal = <?php echo $valor; ?>;
    <?php if($frete_ativo == 1){ ?>
    let deliveryPrice = <?php echo $fretes[0]['valor']; ?>; // Initialize with first delivery option
    const basePrice = <?php echo $valor; ?>; // Convert to centavos
    <?php }; ?>
    let id_transacao = null;

    let currentStep = 1;
    
    function showStep(stepNumber) {
      // Hide all steps
      document.querySelectorAll('.step-content').forEach(step => {
        step.style.display = 'none';
      });
      
      // Show current step
      document.getElementById(`step${stepNumber}`).style.display = 'block';
      
      // Update step indicators
      document.querySelectorAll('.step').forEach((step, index) => {
        step.classList.remove('active', 'completed');
        if (index + 1 < stepNumber) {
          step.classList.add('completed');
        } else if (index + 1 === stepNumber) {
          step.classList.add('active');
        }
      });
      
      currentStep = stepNumber;
    }

    <?php if($frete_ativo == 1){ ?>
    async function lookupCEP(cep) {
      try {
        const response = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
        const data = await response.json();
        
        if (data.erro) {
          throw new Error('CEP não encontrado');
        }
        
        // Fill address fields
        document.getElementById('street').value = data.logradouro;
        document.getElementById('neighborhood').value = data.bairro;
        document.getElementById('city').value = data.localidade;
        document.getElementById('state').value = data.uf;
        
        // Show address fields and delivery options
        document.getElementById('addressFields').style.display = 'block';
        document.getElementById('cepError').style.display = 'none';

        // Update cart values
        updateCartValues();

		validarEnderecoEFrete();
        
        return true;
      } catch (error) {
        document.getElementById('cepError').textContent = 'CEP inválido ou não encontrado';
        document.getElementById('cepError').style.display = 'block';
        document.getElementById('addressFields').style.display = 'none';
        return false;
      }
    }
    <?php }; ?>

    //medida temporária - checkpoint
    <?php if($frete_ativo == 1){ ?>
	function updateCartValues() {
	  const total = basePrice + deliveryPrice;

	  // Exibe os valores já com 2 casas decimais
	  const deliveryFormatted = deliveryPrice.toFixed(2).replace(".", ",");
	  const totalFormatted = total.toFixed(2).replace(".", ",");

	  document.getElementById('valorFrete').textContent = `R$ ${deliveryFormatted}`;
	  document.getElementById('totalValue').textContent = `R$ ${totalFormatted}`;
	  document.getElementById('totalPixScreen').textContent = `R$ ${totalFormatted}`;

	  // Atualiza valorTotal sem a divisão por 100
	  valorTotal = total.toFixed(2);
	}
	<?php }; ?>

	// Função para aplicar máscara de CPF
	function maskCPF(input) {
		let value = input.value.replace(/\D/g, "");
		value = value.replace(/(\d{3})(\d)/, "$1.$2");
		value = value.replace(/(\d{3})(\d)/, "$1.$2");
		value = value.replace(/(\d{3})(\d{1,2})$/, "$1-$2");
		input.value = value;
	}

    // Função para aplicar máscara de telefone
	function maskPhone(input) {
		let value = input.value.replace(/\D/g, "");
		if (value.length > 10) {
			value = value.replace(/^(\d{2})(\d{5})(\d{4}).*/, "($1) $2-$3");
		} else {
			value = value.replace(/^(\d{2})(\d{4})(\d{0,4}).*/, "($1) $2-$3");
		}
		input.value = value;
	}

    <?php if($frete_ativo == 1){ ?>
	function validarEnderecoEFrete() {
	  const cep = document.getElementById('cep').value;
	  const number = document.getElementById('number').value;
	  const addressVisible = document.getElementById('addressFields').style.display !== 'none';

	  const isValidCep = cep && cep.replace(/\D/g, '').length === 8;
	  const isValidNumber = !!number;
	  const isAddressVisible = addressVisible;

	  const hasDeliverySelected = !!document.querySelector('input[name="delivery"]:checked');
	  const isFormValid = isValidCep && isValidNumber && isAddressVisible && hasDeliverySelected;

	  document.getElementById('continueToPayment').disabled = !isFormValid;
	  console.log('validacao de endereco e frete chamada');
		  console.log({
  isValidCep,
  isValidNumber,
  isAddressVisible,
  hasDeliverySelected,
  isFormValid
});
	}
	<?php }; ?>

	// Validação de nome e telefone, habilita/desabilita o botão
	function validarCampos() {
		const nomeInput = document.getElementById("name");
		const phoneInput = document.getElementById("phone");
        const emailInput = document.getElementById("email");
		const cpfInput = document.getElementById("cpf");
		const botaoGerarPix = document.getElementById("botaoGerarPix");

		const nome = nomeInput.value.trim();
		//const nomeValido = /^[A-Za-zÀ-ÿ\s]{7,}$/.test(nome);
        const nomeValido = /^[A-Za-zÀ-ÿ]{2,}(?:\s+[A-Za-zÀ-ÿ]{2,})+$/.test(nome);

		const telefone = phoneInput.value.replace(/\D/g, "");

    	let email = emailInput.value.trim();
    	email = email.replace(/[^\w@.+-]/gi, ''); // Remove caracteres inválidos
    	emailInput.value = email;
    	const emailValido = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email);

		const cpf = cpfInput.value.replace(/\D/g, "");

		botaoGerarPix.disabled = !(nomeValido && (telefone.length === 10 || telefone.length === 11) && emailValido && cpf.length === 11);
		botaoEntrega.disabled = !(nomeValido && (telefone.length === 10 || telefone.length === 11) && emailValido && cpf.length === 11);
		return (nomeValido && (telefone.length === 10 || telefone.length === 11) && emailValido && cpf.length === 11);
	}

	// Adiciona os listeners para os campos
	document.addEventListener("DOMContentLoaded", function () {
      const cpfInput = document.getElementById("cpf");
      const phoneInput = document.getElementById("phone");
      const nomeInput = document.getElementById("name");
      const emailInput = document.getElementById("email");
      <?php if($frete_ativo == 1){ ?>
      const cepInput = document.getElementById("cep");
      <?php }; ?>

		//mascara os valores quando a página carregar
		maskCPF(cpfInput);
		maskPhone(phoneInput);

		cpfInput.addEventListener("input", function () {
			maskCPF(this);
			validarCampos();
		});

		phoneInput.addEventListener("input", function () {
			maskPhone(this);
			validarCampos();
		});

		nomeInput.addEventListener("input", function () {
			this.value = this.value.replace(/[^A-Za-zÀ-ÿ\s]/g, '');
			validarCampos();
		});

        emailInput.addEventListener("input", function () {
            validarCampos();
        });

        <?php if($frete_ativo == 1){ ?>
        cepInput.addEventListener('input', function() {
          let value = this.value.replace(/\D/g, '');
          value = value.replace(/(\d{5})(\d)/, '$1-$2');
          this.value = value;
          
          if (value.replace(/\D/g, '').length === 8) {
            lookupCEP(value.replace(/\D/g, ''));
          } else {
            document.getElementById('addressFields').style.display = 'none';
            document.getElementById('cepError').style.display = 'none';
          }
        });

		document.getElementById("number").addEventListener("input", function(){
			validarEnderecoEFrete();
		});
        <?php }; ?>

        document.addEventListener('click', function(e) {
          if (e.target.classList.contains('next-step')) {
            const nextStep = parseInt(e.target.dataset.next);
            if (validateCurrentStep()) {
              showStep(nextStep);
            }
          }
          
          if (e.target.classList.contains('prev-step')) {
            const prevStep = parseInt(e.target.dataset.prev);
            showStep(prevStep);
          }

          <?php if($frete_ativo == 1){ ?>
          const deliveryOption = e.target.closest('.delivery-option');
          if (deliveryOption) {
            selectDeliveryOption(deliveryOption);
          }
          <?php }; ?>
        });

        <?php if($frete_ativo == 1){ ?>
		function selectDeliveryOption(option) {
		  const radioButton = option.querySelector('input[type="radio"]');
		  radioButton.checked = true;
		  
		  // Agora, usamos parseFloat para garantir que o valor com casas decimais seja mantido
		  deliveryPrice = parseFloat(option.dataset.price);
		  
		  // Remove previous selection
		  document.querySelectorAll('.delivery-option').forEach(opt => {
			opt.classList.remove('selected');
		  });
		  
		  // Add current selection
		  option.classList.add('selected');

		  // Update cart values
		  updateCartValues();
		  
		  validarEnderecoEFrete();
		}
        <?php }; ?>

        function validateCurrentStep() {
          if (currentStep === 1) {
            return validarCampos();
          } else if (currentStep === 2) {
            const cep = document.getElementById('cep').value;
            const number = document.getElementById('number').value;
            const addressVisible = document.getElementById('addressFields').style.display !== 'none';
            
            if (!cep || cep.replace(/\D/g, '').length !== 8) {
              alert('Por favor, insira um CEP válido');
              return false;
            }
            
            if (!addressVisible) {
              alert('Por favor, aguarde o carregamento do endereço');
              return false;
            }
            
            if (!number) {
              alert('Por favor, insira o número do endereço');
              return false;
            }
            
            return true;
          }
          return true;
        }

      // Limita o tamanho máximo dos campos
      cpfInput.maxLength = 14; // 000.000.000-00
      phoneInput.maxLength = 15; // (00) 00000-0000

      validarCampos(); // Valida campos ao carregar página

      //medida temporaria - checkpoint
      <?php if($frete_ativo == 1){ ?>
      updateCartValues();
      <?php }; ?>
	});

	document
	.getElementById("paymentForm")
	.addEventListener("submit", async function (e) {
		e.preventDefault();

		// Mostra a tela de loading
		document.getElementById("loadingScreen").style.display = "flex";

		// Puxar parâmetros
		const params = new URLSearchParams(window.location.search);

		// Remover parâmetros específicos
		params.delete("valor");
		params.delete("email");
		params.delete("name");
		params.delete("nome");
		params.delete("up");
		params.delete("document");
		params.delete("cpf");
		params.delete("telephone");
		params.delete("telefone");

		// Garantir que algo será enviado, mesmo que vazio
		const utmString = params.toString() || "utm_source=direct";

		const formData = {
			acao: "criar",
			oferta: oferta,
			valor: valorTotal,
			nome: document.getElementById("name").value,
			email: document.getElementById("email").value,
			cpf: document.getElementById("cpf").value.replace(/\D/g, ""),
			telefone: document.getElementById("phone").value.replace(/\D/g, ""),
			utm: encodeURIComponent(utmString),
			up: "<?php echo $up; ?>"
		};

		const url = new URL("api/gateway.php", window.location);
		Object.keys(formData).forEach(key => {
			url.searchParams.set(key, formData[key]);
		});

		try {
			const response = await fetch(url);
			const data = await response.json();

			if (data.erro) { //Se houver erro na API
				throw new Error(data.erroMsg || "Erro desconhecido na resposta da API");
			}

			if (data.pixCode && data.payment_id) {
				// Esconde a tela de loading
				document.getElementById("loadingScreen").style.display = "none";
				// Oculta o formulário e mostra a tela do PIX
				document.getElementById("checkoutForm").style.display = "none";
                document.getElementById("pixscreenheader").style.display = "flex";
				document.getElementById("pixScreen").style.display = "block";

				// Gera o QR Code
				new QRCode(document.getElementById("qrcode"), data.pixCode);

				// Preenche o código PIX
				document.getElementById("pixCode").value = data.pixCode;

                id_transacao = data.payment_id;

				// Inicia verificação do pagamento
				startPaymentCheck(data.payment_id);
			}
		} catch (error) {
			// Esconde a tela de loading em caso de erro
			document.getElementById("loadingScreen").style.display = "none";
			console.error("Erro ao gerar PIX:", error);
			alert("Erro ao gerar o PIX: " + error.message + "\nPor favor, tente novamente.");
		}
	});

    // Função para copiar o código PIX
    document
      .getElementById("copyPixButton")
      .addEventListener("click", function () {
        const pixCode = document.getElementById("pixCode");
        pixCode.select();
        document.execCommand("copy");
        this.innerHTML =
          '<svg viewBox="0 0 24 24" width="24" height="24"><path d="M20 2H10c-1.103 0-2 .897-2 2v4H4c-1.103 0-2 .897-2 2v10c0 1.103.897 2 2 2h10c1.103 0 2-.897 2-2v-4h4c1.103 0 2-.897 2-2V4c0-1.103-.897-2-2-2zM4 20V10h10l.002 10H4zm16-6h-4v-4c0-1.103-.897-2-2-2h-4V4h10v10z"></path></svg>COPIADO!';
        setTimeout(() => {
          this.innerHTML =
            '<svg viewBox="0 0 24 24" width="24" height="24"><path d="M20 2H10c-1.103 0-2 .897-2 2v4H4c-1.103 0-2 .897-2 2v10c0 1.103.897 2 2 2h10c1.103 0 2-.897 2-2v-4h4c1.103 0 2-.897 2-2V4c0-1.103-.897-2-2-2zM4 20V10h10l.002 10H4zm16-6h-4v-4c0-1.103-.897-2-2-2h-4V4h10v10z"></path></svg>COPIAR CÓDIGO';
        }, 2000);
      });

	// Função para verificar o status do pagamento
	function startPaymentCheck(payment_id) {
		const checkPayment = async () => {
			const url = new URL("api/gateway.php", window.location);
			url.searchParams.set("acao", "verificar");
			url.searchParams.set("payment_id", payment_id);

			try {
				const response = await fetch(url);
				const data = await response.json();
				const status = data?.status?.toLowerCase();
				if (status === "approved" || status === "completed" || status === "paid") {
                    <?php if($track_fb_pixel == 1){ ?>
                    // Dispara o evento de compra do Facebook
                    if (typeof fbq !== 'undefined') {
                        fbq('track', 'Purchase', {
                            currency: 'BRL',
                            value: Number(valorTotal.toFixed(2)),  // Garante 2 casas decimais como número
                            transaction_id: id_transacao
                        });
                        console.log('✅ Evento de compra enviado para o Facebook Pixel');
                    } else {
                        console.warn('⚠️ Facebook Pixel não disponível para enviar o evento de compra');
                    }
                    <?php }; ?>

					//const params = new URLSearchParams(window.location.search);
					//params.set("upsell", "1");
					//window.location.href = `${upsellUrl}?${params.toString()}`;
                    const upsell = new URL(upsellUrl, window.location.href);
                    const currentParams = new URLSearchParams(window.location.search);

                    // Adiciona os parâmetros da página atual no upsellUrl (sem sobrescrever os já existentes no upsellUrl)
                    for (const [key, value] of currentParams.entries()) {
                    	if (!upsell.searchParams.has(key)) {
                    		upsell.searchParams.set(key, value);
                    	}
                    }

            		// Remover parâmetros específicos
                    upsell.searchParams.delete("up");
                    upsell.searchParams.delete("valor");
            		upsell.searchParams.delete("name");
            		upsell.searchParams.delete("document");
            		upsell.searchParams.delete("telephone");

                    //upsell.searchParams.set("upsell", "1"); // Força o parâmetro upsell=1, mesmo que já exista
                    window.location.href = upsell.toString(); // Redireciona
				}
			} catch (error) {
				console.error("Erro ao verificar pagamento:", error);
			}
		};

		setInterval(checkPayment, 1500); // Verifica se o pix foi pago a cada 10 segundos
	}

    // Lista de domínios comuns
    const emailDomains = [
      "@gmail.com",
      "@hotmail.com",
      "@outlook.com",
      "@yahoo.com",
      "@icloud.com",
    ];

    const emailInput = document.getElementById("email");
    const suggestionsDiv = document.getElementById("emailSuggestions");

    emailInput.addEventListener("input", function (e) {
			validarCampos();
      const value = e.target.value;

      // Limpa sugestões anteriores
      suggestionsDiv.innerHTML = "";

      // Se não tiver @, mostra sugestões
      if (value && !value.includes("@")) {
        emailDomains.forEach((domain) => {
          const suggestion = document.createElement("div");
          suggestion.className = "email-suggestion";
          suggestion.textContent = value + domain;

          suggestion.addEventListener("click", () => {
            emailInput.value = suggestion.textContent;
            suggestionsDiv.innerHTML = "";
            emailInput.focus();
			validarCampos();
          });

          suggestionsDiv.appendChild(suggestion);
        });
      }
    });

    // Fecha sugestões quando clicar fora
    document.addEventListener("click", (e) => {
      if (!e.target.closest(".email-input-wrapper")) {
        suggestionsDiv.innerHTML = "";
      }
    });
	</script>
  </body>
</html>
