<?php
session_start();
require 'includes/conexao.php';

// --- 1. LÓGICA (ANTES DO HTML) ---

// Se já estiver logado, redireciona IMEDIATAMENTE (antes de carregar o site)
if (isset($_SESSION['account_id'])) {
    header("Location: account.php");
    exit;
}

$msg = '';

// Processar o formulário de login
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $account = trim($_POST['account']);
    $password = trim($_POST['password']);

    if (empty($account) || empty($password)) {
        $msg = '<div class="alert alert-warning text-center shadow-sm">Preencha todos os campos!</div>';
    } else {
        // Criptografia SHA1 (Padrão Poketibia)
        $passwordHash = sha1($password);

        try {
            $stmt = $pdo->prepare("SELECT id, name, password FROM accounts WHERE name = ?");
            $stmt->execute([$account]);
            $user = $stmt->fetch();

            if ($user && $user['password'] === $passwordHash) {
                $_SESSION['account_id'] = $user['id'];
                $_SESSION['account_name'] = $user['name'];
                
                // Redireciona com sucesso (agora funciona porque não tem HTML antes)
                header("Location: account.php");
                exit;
            } else {
                $msg = '<div class="alert alert-danger text-center shadow-sm">Conta ou senha incorretos!</div>';
            }
        } catch (Exception $e) {
            $msg = '<div class="alert alert-danger text-center">Erro de conexão.</div>';
        }
    }
}

// --- 2. VISUAL (HTML COMEÇA AQUI) ---
$page_title = "Acessar Conta";
include 'includes/header.php';
?>

<style>
    .login-container {
        max-width: 450px;
        margin: 50px auto;
    }
    .login-card {
        border: none;
        border-radius: 20px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        overflow: hidden;
    }
    .login-header {
        background: linear-gradient(135deg, <?php echo $siteConfig['color_hero_start']; ?>, <?php echo $siteConfig['color_hero_end']; ?>);
        color: white;
        padding: 40px 20px;
        text-align: center;
        position: relative;
    }
    .login-header::after {
        content: '';
        position: absolute;
        bottom: -10px; left: 0; right: 0;
        height: 20px;
        background: white;
        border-radius: 20px 20px 0 0;
    }
    .form-floating > .form-control:focus ~ label {
        color: #e3350d;
    }
    .form-control:focus {
        border-color: #e3350d;
        box-shadow: 0 0 0 0.25rem rgba(227, 53, 13, 0.25);
    }
    .btn-login {
        background-color: #2c3e50;
        border: none;
        padding: 12px;
        font-size: 1.1rem;
        letter-spacing: 1px;
        transition: transform 0.2s;
    }
    .btn-login:hover {
        background-color: #1a252f;
        transform: translateY(-2px);
    }
</style>

<div class="container">
    <div class="login-container">
        
        <?php echo $msg; ?>

        <div class="card login-card">
            <div class="login-header">
                <i class="fas fa-user-circle fa-4x mb-3 opacity-75"></i>
                <h3 class="fw-bold m-0">Bem-vindo de volta!</h3>
                <p class="opacity-75 small">Acesse sua conta para gerenciar seus personagens.</p>
            </div>
            
            <div class="card-body p-4 pt-2">
                <form method="POST" autocomplete="off">
                    
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" id="floatingInput" name="account" placeholder="Nome da Conta" required>
                        <label for="floatingInput"><i class="fas fa-user me-2"></i> Account Name</label>
                    </div>
                    
                    <div class="form-floating mb-4">
                        <input type="password" class="form-control" id="floatingPassword" name="password" placeholder="Senha" required>
                        <label for="floatingPassword"><i class="fas fa-lock me-2"></i> Password</label>
                    </div>

                    <div class="d-grid mb-4">
                        <button type="submit" class="btn btn-primary btn-login fw-bold rounded-pill shadow-sm">
                            ENTRAR AGORA <i class="fas fa-arrow-right ms-2"></i>
                        </button>
                    </div>

                    <div class="d-flex justify-content-between align-items-center">
                        <a href="recovery.php" class="text-decoration-none text-muted small">
                            <i class="fas fa-key"></i> Esqueceu a senha?
                        </a>
                        <a href="register.php" class="text-decoration-none fw-bold text-success small">
                            Criar Conta <i class="fas fa-user-plus"></i>
                        </a>
                    </div>

                </form>
            </div>
        </div>
        
        <div class="text-center mt-4">
            <a href="index.php" class="text-muted text-decoration-none small">
                <i class="fas fa-arrow-left"></i> Voltar ao Início
            </a>
        </div>

    </div>
</div>

<?php include 'includes/footer.php'; ?>