<?php
require_once '5_config/config.php';
iniciarSessao();

// Redirecionar se já logado
if (!empty($_SESSION['usuario_id'])) {
    header('Location: 2_backend/dashboard.php');
    exit;
}

$erro = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $senha = $_POST['senha'] ?? '';

    if ($email && $senha) {
        $db = getDB();
        $stmt = $db->prepare("SELECT id, nome, email, senha, perfil, ativo FROM usuarios WHERE email = ? LIMIT 1");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user && $user['ativo'] && password_verify($senha, $user['senha'])) {
            $_SESSION['usuario_id']    = $user['id'];
            $_SESSION['usuario_nome']  = $user['nome'];
            $_SESSION['usuario_email'] = $user['email'];
            $_SESSION['usuario_perfil']= $user['perfil'];

            // Atualizar último acesso
            $db->prepare("UPDATE usuarios SET ultimo_acesso = NOW() WHERE id = ?")->execute([$user['id']]);

            header('Location: 2_backend/dashboard.php');
            exit;
        } else {
            $erro = 'E-mail ou senha inválidos. Verifique suas credenciais.';
        }
    } else {
        $erro = 'Preencha todos os campos.';
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login | ERP - ActSafe</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      theme: { extend: { colors: {
        'actsafe-blue': '#0F4C81', 'actsafe-dark': '#0a3560',
        'actsafe-orange': '#F26419', 'actsafe-bg': '#F4F6F9'
      }}}
    }
  </script>
  <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
  <style>
    body { font-family: 'Inter', system-ui, sans-serif; }
    .login-bg { background: linear-gradient(135deg, #0F4C81 0%, #0a3560 60%, #1a1a2e 100%); }
    .input-field { width:100%; padding:10px 14px; border:1px solid #d1d5db; border-radius:8px; font-size:14px; outline:none; transition:border-color .15s; }
    .input-field:focus { border-color:#0F4C81; box-shadow:0 0 0 3px rgba(15,76,129,.1); }
  </style>
</head>
<body class="login-bg min-h-screen flex items-center justify-center p-4">
  <div class="w-full max-w-md">
    <!-- Card de Login -->
    <div class="bg-white rounded-2xl shadow-2xl overflow-hidden">
      <!-- Header -->
      <div class="bg-actsafe-blue px-8 py-8 text-center">
        <div class="w-16 h-16 rounded-2xl bg-white/20 flex items-center justify-center mx-auto mb-4">
          <i data-lucide="shield-check" class="w-9 h-9 text-white"></i>
        </div>
        <h1 class="text-2xl font-bold text-white">ERP - ActSafe</h1>
        <p class="text-blue-200 text-sm mt-1">Gestão de Conformidade Normativa</p>
        <p class="text-blue-300 text-xs mt-1">NR 10 · NR 12 · SPDA</p>
      </div>

      <!-- Formulário -->
      <div class="px-8 py-7">
        <h2 class="text-lg font-semibold text-gray-800 mb-5">Acesse sua conta</h2>

        <?php if ($erro): ?>
        <div class="bg-red-50 border border-red-200 text-red-700 rounded-lg px-4 py-3 mb-4 flex items-center gap-2 text-sm">
          <i data-lucide="alert-circle" class="w-4 h-4 flex-shrink-0"></i>
          <?= sanitizar($erro) ?>
        </div>
        <?php endif; ?>

        <form method="POST" action="index.php" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1.5">E-mail</label>
            <div class="relative">
              <i data-lucide="mail" class="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2"></i>
              <input type="email" name="email" class="input-field pl-9" placeholder="seu@email.com.br"
                     value="<?= sanitizar($_POST['email'] ?? '') ?>" required autofocus>
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1.5">Senha</label>
            <div class="relative">
              <i data-lucide="lock" class="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2"></i>
              <input type="password" name="senha" id="senha" class="input-field pl-9 pr-10" placeholder="••••••••" required>
              <button type="button" onclick="toggleSenha()" class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600">
                <i data-lucide="eye" class="w-4 h-4" id="eye-icon"></i>
              </button>
            </div>
          </div>
          <button type="submit" class="w-full bg-actsafe-blue hover:bg-actsafe-dark text-white font-semibold py-2.5 rounded-lg transition-colors flex items-center justify-center gap-2 mt-2">
            <i data-lucide="log-in" class="w-4 h-4"></i>
            Entrar no Sistema
          </button>
        </form>
      </div>
    </div>

    <!-- Rodapé -->
    <p class="text-center text-blue-200 text-xs mt-5">
      Desenvolvido por <strong class="text-white">Antônio da Luz</strong> · ERP - ActSafe v1.0
    </p>
  </div>

  <script>
    lucide.createIcons();
    function toggleSenha() {
      const input = document.getElementById('senha');
      const icon  = document.getElementById('eye-icon');
      if (input.type === 'password') {
        input.type = 'text';
        icon.setAttribute('data-lucide', 'eye-off');
      } else {
        input.type = 'password';
        icon.setAttribute('data-lucide', 'eye');
      }
      lucide.createIcons();
    }
  </script>
</body>
</html>
