<?php
$config = require 'config/config.php';
@ini_set( 'display_errors', '1' );
error_reporting( E_ALL );
session_start();
require "config/db.php"; // conexão com o banco ($conn)

// Se o formulário foi enviado
if ( $_SERVER[ "REQUEST_METHOD" ] === "POST" ) {
  $usuario = trim( $_POST[ "usuario" ] );
  $senha = $_POST[ "senha" ];

  // Buscar usuário pelo email ou CPF
  $sql = "SELECT id, nome_completo, senha, status, ncadastro 
            FROM usuarios 
            WHERE email_principal = ? OR cpf_cnpj = ? 
            LIMIT 1";
  $stmt = $conn->prepare( $sql );
  $stmt->bind_param( "ss", $usuario, $usuario );
  $stmt->execute();
  $result = $stmt->get_result();
  $usuarioData = $result->fetch_assoc();

  if ( $usuarioData ) {
    // Verificar senha com hash
    if ( password_verify( $senha, $usuarioData[ 'senha' ] ) ) {
      // Login bem-sucedido → salva na sessão
      $_SESSION[ 'usuario_id' ] = $usuarioData[ 'id' ];
      $_SESSION[ 'nome_completo' ] = $usuarioData[ 'nome_completo' ];
      $_SESSION[ 'ncadastro' ] = $usuarioData[ 'ncadastro' ];

      // Se não estiver ativo → redireciona para verificação
      if ( $usuarioData[ 'status' ] !== 'ATIVO' ) {
        header( "Location: verificar_usuario.php?ncadastro=" . urlencode( $usuarioData[ 'ncadastro' ] ) );
        exit();
      }

      // Redireciona para o painel
      header( "Location: dashboard.php" );
      exit();
    } else {
      $erro = "Senha incorreta.";
    }
  } else {
    $erro = "Usuário não encontrado.";
  }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>

<!-- Required meta tags -->

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Links Of CSS File -->

<link rel="stylesheet" href="assets/css/sidebar-menu.css">
<link rel="stylesheet" href="assets/css/simplebar.css">
<link rel="stylesheet" href="assets/css/apexcharts.css">
<link rel="stylesheet" href="assets/css/prism.css">
<link rel="stylesheet" href="assets/css/rangeslider.css">
<link rel="stylesheet" href="assets/css/quill.snow.css">
<link rel="stylesheet" href="assets/css/google-icon.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/remixicon@4.5.0/fonts/remixicon.css">
<link rel="stylesheet" href="assets/css/swiper-bundle.min.css">
<link rel="stylesheet" href="assets/css/fullcalendar.main.css">
<link rel="stylesheet" href="assets/css/jsvectormap.min.css">
<link rel="stylesheet" href="assets/css/lightpick.css">
<link rel="stylesheet" href="assets/css/style2.css">

<!-- Favicon -->

<link rel="icon" type="image/png" href="assets/images/favicon.png">

<!-- Title -->

<title>LOGIN - <?php echo "" . $config['nome_do_sistema'] . ""?> - <?php echo "" . $config['instituicao'] . ""?></title>
</head>

<body class="boxed-size">

<!-- Start Preloader Area -->

<div class="preloader" id="preloader">
  <div class="preloader">
    <div class="waviy position-relative"> <span class="d-inline-block">A</span> <span class="d-inline-block">R</span> <span class="d-inline-block">N</span> <span class="d-inline-block">T</span> <span class="d-inline-block">S</span> <span class="d-inline-block">A</span> <span class="d-inline-block">D</span> <span class="d-inline-block">M</span> </div>
  </div>
</div>

<!-- End Preloader Area --> 

<!-- Start Main Content Area -->
<div class="container-fluid min-vh-100 d-flex align-items-center justify-content-center py-5">
  <div class="col-lg-8 col-md-10">
    <div class="card bg-white border-0 rounded-3 shadow-sm p-3">
      <div class="card-body p-4">
        <div class="row align-items-center"> 
          
          <!-- Título principal -->          
          <!-- Imagem à esquerda -->
          <div class="col-lg-6 d-none d-lg-block"> <img src="assets/images/login.jpg" class="rounded-3 w-100" alt="Tela de Login"> </div>
          
          <!-- Formulário à direita -->
          <div class="col-lg-6">
            <div class="mw-480 ms-lg-auto"> 
                <div><h4 align="center"> Login no Sistema - <?php echo $config['nome_do_sistema']; ?> <br>
              <small class="text-muted"><?php echo $config['instituicao']; ?></small> </h4></div><br>
              
              <!-- Boas-vindas -->
              <div class="col-xl-12 mb-4">
                <h5 class="fw-semibold">Bem-vindo(a)!</h5>
                <p class="text-secondary mb-0"> Por favor, insira suas credenciais para acessar sua conta. </p>
              </div>
              <?php if (!empty($erro)): ?>
              <div class="alert alert-danger">
                <?= $erro; ?>
              </div>
              <?php endif; ?>
              
              <!-- Formulário de Login -->
              <form action="" method="POST">
                
                <!-- Campo email/CPF --> 
                <!-- Campo email/CPF/CNPJ -->
                <div class="form-group mb-4">
                  <label for="usuario" class="form-label text-secondary">E-mail ou CPF/CNPJ</label>
                  <div class="position-relative">
                    <input type="text" class="form-control h-55 ps-5" id="usuario" name="usuario" placeholder="Digite seu e-mail ou CPF/CNPJ" autocomplete="off" required>
                    <div class="valid-feedback">Tudo certo!</div>
                    <i class="ri-user-line position-absolute top-50 start-0 translate-middle-y fs-20 text-gray-light ps-20"></i> </div>
                </div>
                
                <!-- Campo senha -->
                <div class="form-group mb-4">
                  <label for="senha" class="form-label text-secondary">Senha</label>
                  <div class="position-relative">
                    <input type="password" class="form-control h-55 ps-5 pe-5" id="senha" name="senha" placeholder="Digite sua senha" required>
                    <div class="valid-feedback">Tudo certo!</div>
                    <i class="ri-lock-password-line position-absolute top-50 start-0 translate-middle-y fs-20 text-gray-light ps-20"></i> <i class="ri-eye-line position-absolute top-50 end-0 translate-middle-y fs-20 text-gray-light pe-0 toggleSenha" style="cursor: pointer;">&nbsp;&nbsp;&nbsp;</i> </div>
                </div>
                
                <!-- Botão Entrar -->
                <div class="form-group mb-4">
                  <button type="submit" class="btn btn-primary fw-medium py-2 px-3 w-100">
                  <div class="d-flex align-items-center justify-content-center py-1"> <i class="material-symbols-outlined text-white fs-20 me-2">login</i> <span>Entrar</span> </div>
                  </button>
                </div>
              </form>
              <script>
                // Mostrar senha enquanto o olho está pressionado
                document.querySelectorAll(".toggleSenha").forEach(function (icon) {
                  const input = document.getElementById("senha");
          
                  icon.addEventListener("mousedown", function () {
                    input.setAttribute("type", "text");
                    this.classList.remove("ri-eye-line");
                    this.classList.add("ri-eye-off-line");
                  });
          
                  icon.addEventListener("mouseup", function () {
                    input.setAttribute("type", "password");
                    this.classList.remove("ri-eye-off-line");
                    this.classList.add("ri-eye-line");
                  });
          
                  // Para mobile (touch)
                  icon.addEventListener("touchstart", function (e) {
                    e.preventDefault(); // evita clique duplo no mobile
                    input.setAttribute("type", "text");
                    this.classList.remove("ri-eye-line");
                    this.classList.add("ri-eye-off-line");
                  });
          
                  icon.addEventListener("touchend", function () {
                    input.setAttribute("type", "password");
                    this.classList.remove("ri-eye-off-line");
                    this.classList.add("ri-eye-line");
                  });
                });
              </script> 
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Start Main Content Area --> 

<!-- Link Of JS File --> 

<!-- Scripts --> 
<script src="config/cep-autofill.js"></script> 
<script src="config/mascaras.js"></script> 
<script src="config/vrifica_campos_form.js"></script> 
<script src="config/feedback_campos_form.js"></script> 
<script src="assets/js/bootstrap.bundle.min.js"></script> 

<!-- Scripts para remover --> 
<script src="assets/js/sidebar-menu.js"></script> 
<script src="assets/js/dragdrop.js"></script> 
<script src="assets/js/rangeslider.min.js"></script> 
<script src="assets/js/quill.min.js"></script> 
<script src="assets/js/data-table.js"></script> 
<script src="assets/js/prism.js"></script> 
<script src="assets/js/clipboard.min.js"></script> 
<script src="assets/js/feather.min.js"></script> 
<script src="assets/js/feather.min.js"></script> 
<script src="assets/js/simplebar.min.js"></script> 
<script src="assets/js/apexcharts.min.js"></script> 
<script src="assets/js/echarts.min.js"></script> 
<script src="assets/js/swiper-bundle.min.js"></script> 
<script src="assets/js/fullcalendar.main.js"></script> 
<script src="assets/js/jsvectormap.min.js"></script> 
<script src="assets/js/world-merc.js"></script> 
<script src="assets/js/moment.min.js"></script> 
<script src="assets/js/lightpick.js"></script> 
<script src="assets/js/custom/apexcharts.js"></script> 
<script src="assets/js/custom/echarts.js"></script> 
<script src="assets/js/custom/custom.js"></script>
</body>
</html>