<?php
// Inicia a sessão uma única vez no topo do arquivo
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Verifica se há uma mensagem de erro na sessão e a exibe
$error_message = '';
if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']); // Limpa a mensagem após exibir
}

// Se o método da requisição for POST (formulário enviado)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = $_POST['email'];
    $senha = $_POST['senha'];
    $baseName = str_replace("@", "_", $email);

    // O nome do subdiretório e do arquivo TXT será o mesmo
    $userSubDirName = $baseName;
    $userFileName = $baseName . ".txt";

    // 2. Constrói o caminho completo para o arquivo.
    $filePath = "agora2/login/usuarios/" . $userSubDirName . "/" . $userFileName;

    if (file_exists($filePath)) {
        $data = json_decode(file_get_contents($filePath), true);

        // Verifique se $data['senha'] existe antes de usar password_verify
        if (isset($data['senha']) && password_verify($senha, $data['senha'])) {
            if (isset($data['verificado']) && $data['verificado']) {
                // Login bem-sucedido
                $_SESSION['usuario'] = $email;
                
                // NOVO: Define o nome do usuário na sessão
                if (isset($data['nome'])) {
                    $_SESSION['nomeUsuarioLogado'] = $data['nome'];
                }

                // Define o caminho para o diretório de comentários do usuário
                $_SESSION['comentariosDirPath'] = 'agora2/login/usuarios/' . str_replace("@", "_", $email) . 'agora2/login/comentarios/';
                
                header("Location: agora2/login/dashboard.php");
                exit;
            } else {
                // E-mail não verificado
                $_SESSION['error_message'] = "E-mail não verificado. Por favor, verifique seu e-mail primeiro.";
            }
        } else {
            // E-mail ou senha incorretos
            $_SESSION['error_message'] = "E-mail ou senha incorretos.";
        }
    } else {
        // E-mail ou senha incorretos (arquivo não encontrado)
        $_SESSION['error_message'] = "E-mail ou senha incorretos.";
    }

    // Redireciona para a própria página de login para exibir o erro
    header("Location: index.php"); // Altere 'index.php' se o nome do seu arquivo for diferente
    exit;
}

// O restante do HTML
?>



<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Código da Net: Transparência e Liberdade Digital</title>

<!-- Inclui o rodízio automático de temas (Da Vinci, Van Gogh, Picasso, Matisse, Mármore) -->
    <?php include 'index-TEMA.php'; ?>
 <link rel="stylesheet" href="styles0.css">
 </head>

<body>
    <video autoplay muted loop class="video-fundo-body">
        <source src="../../fundo.mp4" type="video/mp4">
        Seu navegador não suporta o elemento de vídeo.
    </video>

   
   <div class="container">
   
        

     <div class="container22">
            <div class="header00-content">
        <table>
            <tr>
                <td>
                
                <div class="logo000">Ágora Virtu@l</div>
                                   
               
                </td>
            </tr>
        </table>
    </div>
           </div>
           
            
           
       
    <div class="header" id="topo" >

        
        
        
    <table>
        <tr>
        <td colspan="2">
            <div class="image-flex-container">
                <img src="img/the-thinker-5240391_640.png"
                     alt="rdc"
                     width="15%"
                     height="15%"
                     longdesc="https://alogicadarede.com.br" />

                <img src="img/ai-generated-8686520_640.jpg"
                     alt="rdc"
                     width="30%"
                     height="30%"
                     longdesc="https://alogicadarede.com.br" />
            </div>
        </td>
       
    </tr>

        
        
        <tr><td>
        
        
                <form method="POST" class="button">
                    <?php if (!empty($error_message)): ?>
        <p style="color: red; font-weight: bold;"><?php echo htmlspecialchars($error_message); ?></p>
    <?php endif; ?>
            <div class="input-group">
                      
                <input type="email" id="email" name="email" required  placeholder="E-mail">
            </div>
            <div class="input-group">
               
                <input type="password" id="senha" name="senha" required placeholder="Senha">
            </div>
            <button type="submit" class="buttonC"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1.2em" height="1.2em" fill="currentColor" style="vertical-align: middle; margin-right: 6px; margin-bottom: 2px;">
  <!-- Rosto e Corpo -->
  <path d="M9 9c1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3 1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V16h14v-1.5c0-2.33-4.67-3.5-7-3.5z"/>
  <!-- Ondas Sonoras -->
  <path d="M16.76 5.36l-1.68 1.69c.84 1.18 1.3 2.6 1.3 4.06s-.46 2.88-1.3 4.06l1.68 1.69c1.23-1.64 1.94-3.66 1.94-5.75s-.71-4.11-1.94-5.75zM20.15 2.01l-1.68 1.69C20.5 5.75 21.6 8.78 21.6 12s-1.1 6.25-3.13 8.3l1.68 1.69C22.61 19.53 24 15.93 24 12s-1.39-7.53-3.85-9.99z"/>
</svg> ENTRAR <br/> <span class="warning-18">+18, Apenas Adultos </span></button>
            
        </form>
        </td></tr>
        
<tr>
  <td colspan="2" style="text-align: center; padding: 5px 0;">
    <div style="display: flex; align-items: center; justify-content: center; gap: 12px; flex-wrap: wrap;">
      
      <!-- Botão Na Rua (com largura horizontal estritamente limitada ao conteúdo) -->
      <a href="anonimo.php" target="_self" class="button" style="padding: 1px 5px !important; font-size: 0.65em !important; min-width: unset !important; width: max-content !important; display: inline-flex !important; align-items: center !important; margin: 0 !important; line-height: 1.1 !important;">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="0.85em" height="0.85em" fill="currentColor" style="vertical-align: middle; margin-right: 2px;">
          <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
        </svg>Na Rua
      </a>

      <!-- Cadastro -->
      <a href="agora2/login/cadastrar.php" class="button-cinza" style="display: inline-flex; align-items: center; font-size: 0.75em; margin: 0; padding: 0;">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1.1em" height="1.1em" fill="currentColor" style="vertical-align: middle; margin-right: 3px;">
          <path d="M12 2C9.24 2 7 4.24 7 7c0 1.62.77 3.06 1.96 3.99L8 20h8l-1.96-9.01C15.23 10.06 16 8.62 16 7c0-2.76-2.24-5-5-5zm0 2c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3z"/>
        </svg>Cadastro
      </a>

      <!-- Recuperar Senha -->
      <a href="agora2/login/recuperar_senha.php" class="button-recuperar-senha" style="font-size: 0.65em; margin: 0; padding: 0;">Recuperar Senha</a>

    </div>
  </td>
</tr>
</table>
        
       
    </div> 
    
     <div class="container22">
    
 
     <span class="piscando">
            <p class="logo0"> <?php include 'exibir-pensamento.php'; ?>
     </span> 
    
   </div>
     
     
     </div>
     
     <div class="header0">
         <p class="shazan">®© Sh@z@n</p>
    </div>
    
     <p></p>.
          
    
    </div>
    
    </br></br>
    

<script>
document.addEventListener('DOMContentLoaded', () => {
    const formElement = document.getElementById('comment-form');
    const originalFormParent = formElement.parentNode;

    document.querySelectorAll('.responder-link').forEach(link => {
        link.addEventListener('click', (event) => {
            event.preventDefault();
            const parentId = event.target.getAttribute('data-id');
            const targetContainer = document.getElementById(`resposta-target-${parentId}`);
            
            if (targetContainer) {
                targetContainer.appendChild(formElement);
                document.getElementById('parent_id').value = parentId;
                document.getElementById('cancel-reply').style.display = 'inline-block';
                document.getElementById('comentario').focus();
            } else {
                console.error(`Container alvo com ID resposta-target-${parentId} não encontrado.`);
            }
        });
    });

    const cancelButton = document.getElementById('cancel-reply');
    if (cancelButton) {
        cancelButton.addEventListener('click', () => {
            originalFormParent.appendChild(formElement);
            document.getElementById('parent_id').value = '';
            cancelButton.style.display = 'none';
            document.getElementById('comentario').value = '';
        });
    }

    // === NOVO SCRIPT PARA EXPANSÃO DE 10 EM 10 ===
    document.querySelectorAll('.toggle-respostas').forEach(button => {
        const hiddenContainer = button.previousElementSibling;
        const hiddenReplies = hiddenContainer.querySelectorAll('.resposta-escondida');
        const totalHidden = parseInt(button.dataset.totalHidden, 10);
        const STEP = 10;
        let visibleCount = 0;

        // Função para mostrar as próximas N respostas
        const showNextBatch = () => {
            const start = visibleCount;
            const end = Math.min(visibleCount + STEP, totalHidden);
            for (let i = start; i < end; i++) {
                hiddenReplies[i].style.display = 'block';
            }
            visibleCount = end;
        };

        // Função para atualizar o texto do botão
        const updateButtonText = () => {
            const remaining = totalHidden - visibleCount;
            if (remaining > 0) {
                button.textContent = `Mostrar mais ${Math.min(STEP, remaining)} / Total ${totalHidden}`;
            } else {
                button.textContent = 'Esconder respostas';
            }
        };

        // Adiciona o evento de clique
        button.addEventListener('click', (event) => {
            event.preventDefault();
            if (visibleCount < totalHidden) {
                showNextBatch();
                updateButtonText();
            } else {
                // Esconder todas as respostas e resetar o estado
                hiddenReplies.forEach(reply => reply.style.display = 'none');
                visibleCount = 0;
                updateButtonText();
            }
        });

        // Oculta todas as respostas inicialmente
        hiddenReplies.forEach(reply => reply.style.display = 'none');
    });
});
</script>

     
    <?php if (isset($_SESSION['error_message'])): ?>
        <div id="error-box" class="error-message">
            <p><?php echo htmlspecialchars($_SESSION['error_message']); ?></p>
            <p>Tente novamente em <span id="countdown">5</span> segundos...</p>
        </div>
        <script>
            let countdownElement = document.getElementById('countdown');
            let timeLeft = 5;
            let timer = setInterval(function() {
                timeLeft--;
                countdownElement.textContent = timeLeft;
                if (timeLeft <= 0) {
                    clearInterval(timer);
                    document.getElementById('error-box').style.display = 'none';
                }
            }, 1000);
        </script>
        <?php unset($_SESSION['error_message']); // Limpa a sessão após exibir ?>
    <?php endif; ?>

</body>
</html>
