<?php
session_start();

// 1. CONEXÃO
if (file_exists('config.php')) {
    require_once 'config.php';
} else {
    // Fallback de conexão se config.php não existir (Use seus dados reais aqui se der erro)
    $host = 'localhost';
    $db   = 'pataibac_TikTokShop'; // Seu banco
    $user = 'pataibac_Leone'; // Seu usuário
    $pass = 's_!0crm}%uR%';      // Sua senha
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("Erro de conexão: Crie o arquivo config.php ou ajuste este arquivo.");
    }
}

$erro = '';

// 2. PROCESSAMENTO DO LOGIN
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $senha = $_POST['senha'];

    if ($email && $senha) {
        // Busca usuário
        $stmt = $pdo->prepare("SELECT * FROM usuarios WHERE email = ? LIMIT 1");
        $stmt->execute([$email]);
        $usuario = $stmt->fetch(PDO::FETCH_ASSOC);

        // Verifica senha (compatível com o cadastro automático do Webhook)
        if ($usuario && password_verify($senha, $usuario['senha'])) {
            // Sucesso: Cria sessão
            $_SESSION['usuario_id'] = $usuario['id'];
            $_SESSION['email'] = $usuario['email'];
            $_SESSION['nome'] = $usuario['nome'];
            
            // Redireciona para o Painel
            header("Location: index.php");
            exit;
        } else {
            $erro = "E-mail ou senha incorretos.";
        }
    } 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, maximum-scale=1.0, user-scalable=no">
    <title>Entrar - App Parceiros</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .btn-primary { background: linear-gradient(to right, #ff0050, #00f2ea); }
    </style>
</head>
<body class="bg-gray-50 flex items-center justify-center min-h-screen px-4">

    <div class="w-full max-w-sm bg-white rounded-2xl shadow-xl overflow-hidden p-8 relative">
        
        <!-- Logo / Cabeçalho -->
        <div class="text-center mb-8">
            <div class="w-16 h-16 bg-black rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-pink-500/20">
                <i class="fas fa-bolt text-2xl text-white"></i>
            </div>
            <h1 class="text-2xl font-bold text-gray-800">Bem-vindo(a)!</h1>
            <p class="text-sm text-gray-500">Acesse sua conta para gerenciar ganhos.</p>
        </div>

        <!-- Mensagem de Erro -->
        <?php if($erro): ?>
            <div class="bg-red-50 text-red-500 text-xs font-bold p-3 rounded-lg mb-4 text-center border border-red-100">
                <i class="fas fa-exclamation-circle mr-1"></i> <?php echo $erro; ?>
            </div>
        <?php endif; ?>

        <!-- Formulário -->
        <form method="POST" action="">
            <div class="mb-4">
                <label class="block text-xs font-bold text-gray-600 mb-1 ml-1">E-MAIL</label>
                <div class="relative">
                    <i class="fas fa-envelope absolute left-3 top-3.5 text-gray-400"></i>
                    <input type="email" name="email" required placeholder="seu@email.com" 
                           class="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-pink-500 focus:ring-1 focus:ring-pink-500 transition">
                </div>
            </div>

            <div class="mb-6">
                <label class="block text-xs font-bold text-gray-600 mb-1 ml-1">SENHA</label>
                <div class="relative">
                    <i class="fas fa-lock absolute left-3 top-3.5 text-gray-400"></i>
                    <input type="password" name="senha" required placeholder="Sua senha" 
                           class="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-pink-500 focus:ring-1 focus:ring-pink-500 transition">
                </div>
                <div class="text-right mt-2">
                    <a href="#" class="text-xs text-pink-600 font-semibold hover:underline">Esqueceu a senha?</a>
                </div>
            </div>

            <button type="submit" class="w-full btn-primary text-white font-bold py-3.5 rounded-xl shadow-lg shadow-pink-500/30 transform transition active:scale-95 hover:opacity-90">
                ENTRAR AGORA
            </button>
        </form>

        <div class="mt-8 text-center border-t border-gray-100 pt-6">
            <p class="text-xs text-gray-500">Ainda não tem conta?</p>
            <a href="#" onclick="alert('O cadastro é feito automaticamente ao comprar um produto!')" class="text-sm font-bold text-gray-800 hover:text-pink-600 transition">Criar conta nova</a>
        </div>
    </div>

</body>
</html>