<?php
require '../config/config.php';
require '../config/database.php';

// Se já estiver logado, vai direto pro dashboard
if (isset($_SESSION['user_id'])) {
    header('Location: dashboard.php');
    exit;
}

$erro = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $email = trim($_POST['email']);
    $senha = $_POST['senha'];

    if (!$email || !$senha) {
        $erro = "Informe e-mail e senha.";
    } else {

        $stmt = $pdo->prepare("
            SELECT id, senha, ativo 
            FROM usuarios 
            WHERE email = ?
            LIMIT 1
        ");
        $stmt->execute([$email]);
        $usuario = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$usuario || !password_verify($senha, $usuario['senha'])) {
            $erro = "E-mail ou senha inválidos.";
        } elseif ((int)$usuario['ativo'] !== 1) {
            $erro = "Usuário desativado. Entre em contato com o suporte.";
        } else {
            // Login OK
            $_SESSION['user_id'] = $usuario['id'];
            header('Location: dashboard.php');
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Login - XML SEFAZ</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">

<div class="bg-white p-6 rounded shadow w-full max-w-md">

    <h1 class="text-2xl font-bold mb-4 text-center">
        Acessar Sistema
    </h1>

    <?php if ($erro): ?>
        <div class="bg-red-100 text-red-700 p-3 rounded mb-4">
            <?= htmlspecialchars($erro) ?>
        </div>
    <?php endif; ?>

    <form method="post" class="space-y-3">

        <input
            type="email"
            name="email"
            placeholder="E-mail"
            class="w-full border p-2 rounded focus:outline-none focus:ring"
            required
        >

        <input
            type="password"
            name="senha"
            placeholder="Senha"
            class="w-full border p-2 rounded focus:outline-none focus:ring"
            required
        >

        <button
            type="submit"
            class="w-full bg-blue-600 text-white p-2 rounded hover:bg-blue-700 transition"
        >
            Entrar
        </button>

    </form>

    <div class="text-center text-sm mt-4 space-y-1">
        <p>
            Não tem conta?
            <a href="cadastro.php" class="text-blue-600 hover:underline">
                Criar conta
            </a>
        </p>
    </div>

</div>

</body>
</html>
