<?php
require_once 'db_config.php';
session_start();

// Se já está logado, redireciona para dashboard
if (isset($_SESSION['usuario_id'])) {
    header("Location: dashboard.php");
    exit;
}

$erro = '';
$sucesso = '';

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

    if (empty($email) || empty($senha)) {
        $erro = 'Email e senha são obrigatórios.';
    } else {
        try {
            $stmt = $pdo->prepare("SELECT id, nome, email, senha_hash FROM usuarios WHERE email = ?");
            $stmt->execute([$email]);
            $usuario = $stmt->fetch();

            // Verificar senha (texto plano ou bcrypt)
            $senha_valida = ($usuario['senha_hash'] === $senha) || password_verify($senha, $usuario['senha_hash']);
            
            if ($usuario && $senha_valida) {
                // Login bem-sucedido
                $_SESSION['usuario_id'] = $usuario['id'];
                $_SESSION['usuario_nome'] = $usuario['nome'];
                $_SESSION['usuario_email'] = $usuario['email'];
                
                // Atualizar último login
                $stmtUpdate = $pdo->prepare("UPDATE usuarios SET ultimo_login = NOW() WHERE id = ?");
                $stmtUpdate->execute([$usuario['id']]);

                header("Location: dashboard.php");
                exit;
            } else {
                $erro = 'Email ou senha incorretos.';
            }
        } catch (PDOException $e) {
            $erro = 'Erro ao conectar com o banco de dados.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Carteira PRO</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="../css/global.css">
    <style>
        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes pulse {
            0%, 100% {
                opacity: 1;
            }
            50% {
                opacity: 0.7;
            }
        }

        .animate-slide-up {
            animation: slideUp 0.8s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
        }

        .animate-pulse-custom {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }

        .logo-box {
            background: linear-gradient(135deg, #3B82F6 0%, #60A5FA 100%);
            box-shadow: 0 10px 30px rgba(59, 130, 246, 0.3);
        }

        .input-focus {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .input-focus:focus {
            transform: translateY(-2px);
            box-shadow: 0 0 0 4px rgba(96, 165, 250, 0.2);
        }

        .btn-login {
            background: linear-gradient(135deg, #3B82F6 0%, #2563EB 100%);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
        }

        .btn-login:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
        }

        .btn-login:active {
            transform: translateY(-1px);
        }

        .card-login {
            border-top: 6px solid #60A5FA;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        }
    </style>
</head>
<body class="bg-gradient-to-br from-blue-100 via-blue-50 to-blue-200 min-h-screen flex items-center justify-center p-4">
    <!-- Background decorativo -->
    <div class="absolute inset-0 overflow-hidden pointer-events-none">
        <div class="absolute -top-40 -right-40 w-80 h-80 bg-blue-200 rounded-full opacity-20 animate-pulse-custom"></div>
        <div class="absolute -bottom-40 -left-40 w-80 h-80 bg-blue-300 rounded-full opacity-20 animate-pulse-custom" style="animation-delay: 1s;"></div>
    </div>

    <!-- Container Principal -->
    <div class="relative z-10 w-full max-w-md">
        <!-- Card de Login -->
        <div class="bg-white rounded-3xl p-10 card-login animate-slide-up">
            <!-- Logo e Título -->
            <div class="text-center mb-8">
                <div class="logo-box w-16 h-16 rounded-2xl flex items-center justify-center mx-auto mb-4 animate-pulse-custom">
                    <span class="text-white text-3xl font-bold">💼</span>
                </div>
                <h1 class="text-3xl font-bold text-gray-800 mb-2">Carteira PRO</h1>
                <p class="text-gray-500 text-sm">Controle profissional de seus ativos</p>
            </div>

            <!-- Mensagens de Erro/Sucesso -->
            <?php if ($erro): ?>
                <div class="mb-6 p-4 bg-red-100 border-l-4 border-red-500 rounded-lg animate-slide-up">
                    <p class="text-red-800 font-medium text-sm">❌ <?php echo htmlspecialchars($erro); ?></p>
                </div>
            <?php endif; ?>

            <?php if ($sucesso): ?>
                <div class="mb-6 p-4 bg-green-100 border-l-4 border-green-500 rounded-lg animate-slide-up">
                    <p class="text-green-800 font-medium text-sm">✓ <?php echo htmlspecialchars($sucesso); ?></p>
                </div>
            <?php endif; ?>

            <!-- Formulário de Login -->
            <form method="POST" class="space-y-5">
                <!-- Email -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">📧 Email</label>
                    <input 
                        type="email" 
                        name="email" 
                        placeholder="seu@email.com"
                        class="w-full px-4 py-3 rounded-xl border-2 border-gray-200 bg-gray-50 text-gray-800 placeholder-gray-400 input-focus"
                        required
                        autofocus
                    >
                </div>

                <!-- Senha -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">🔐 Senha</label>
                    <input 
                        type="password" 
                        name="senha" 
                        placeholder="••••••••"
                        class="w-full px-4 py-3 rounded-xl border-2 border-gray-200 bg-gray-50 text-gray-800 placeholder-gray-400 input-focus"
                        required
                    >
                </div>

                <!-- Lembrar-me -->
                <div class="flex items-center">
                    <input 
                        type="checkbox" 
                        id="lembrar" 
                        name="lembrar"
                        class="w-4 h-4 rounded border-gray-300 text-blue-500 cursor-pointer"
                    >
                    <label for="lembrar" class="ml-2 text-sm text-gray-600 cursor-pointer">Lembrar-me neste dispositivo</label>
                </div>

                <!-- Botão de Login -->
                <button 
                    type="submit" 
                    class="w-full py-3 px-4 rounded-xl text-white font-bold text-lg btn-login mt-6 flex items-center justify-center gap-2"
                >
                    ✓ Entrar
                </button>
            </form>

            <!-- Informações de Teste -->
            <div class="mt-8 p-4 bg-blue-50 rounded-xl border border-blue-200">
                <p class="text-xs text-gray-600 font-semibold mb-2">🧪 Dados de Teste:</p>
                <p class="text-xs text-gray-700"><span class="font-mono bg-white px-2 py-1 rounded">admin@teste.com</span></p>
                <p class="text-xs text-gray-700"><span class="font-mono bg-white px-2 py-1 rounded">123456</span></p>
            </div>

            <!-- Rodapé -->
            <div class="mt-6 text-center text-xs text-gray-500">
                <p>Sistema de Controle de Carteira de Ativos</p>
                <p class="mt-1">Desenvolvido com ❤️ em PHP + JavaScript</p>
            </div>
        </div>

        <!-- Informações Adicionais -->
        <div class="mt-8 text-center text-gray-600 text-sm">
            <p>🔒 Seus dados estão 100% seguros e criptografados</p>
        </div>
    </div>

    <!-- Script para melhorias de UX -->
    <script>
        // Remover mensagens de erro/sucesso após 5 segundos
        document.addEventListener('DOMContentLoaded', () => {
            const alertas = document.querySelectorAll('[class*="bg-red-100"], [class*="bg-green-100"]');
            alertas.forEach(alerta => {
                setTimeout(() => {
                    alerta.style.animation = 'slideUp 0.6s ease-out reverse';
                    setTimeout(() => alerta.remove(), 600);
                }, 5000);
            });

            // Focus no primeiro input
            const emailInput = document.querySelector('input[name="email"]');
            if (emailInput) emailInput.focus();
        });

        // Enter para enviar formulário
        document.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                document.querySelector('form').submit();
            }
        });
    </script>
</body>
</html>
