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

$erro = null;
$sucesso = null;

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

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

    if (!$nome || !$email || !$senha) {
        $erro = "Preencha todos os campos.";
    } else {

        // Verifica se email já existe
        $stmt = $pdo->prepare("SELECT id FROM usuarios WHERE email = ?");
        $stmt->execute([$email]);

        if ($stmt->fetch()) {
            $erro = "Este e-mail já está cadastrado.";
        } else {

            $hash = password_hash($senha, PASSWORD_DEFAULT);

            $stmt = $pdo->prepare("
                INSERT INTO usuarios (nome, email, senha, plano_id, ativo)
                VALUES (?, ?, ?, 1, 1)
            ");
            $stmt->execute([$nome, $email, $hash]);

            $sucesso = "Cadastro realizado com sucesso. Faça login.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Cadastro - 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">Criar Conta</h1>

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

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

    <form method="post" class="space-y-3">
        <input
            type="text"
            name="nome"
            placeholder="Nome completo"
            class="w-full border p-2 rounded"
            required
        >

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

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

        <button
            class="w-full bg-blue-600 text-white p-2 rounded hover:bg-blue-700"
        >
            Cadastrar
        </button>
    </form>

    <p class="text-center text-sm mt-4">
        Já tem conta?
        <a href="login.php" class="text-blue-600 hover:underline">
            Fazer login
        </a>
    </p>
</div>

</body>
</html>
