<?php
session_start();
$page_title = "Minha Conta";
require 'includes/conexao.php';
include 'includes/header.php';

// Redireciona se não estiver logado
if (!isset($_SESSION['account_id'])) {
    header("Location: login.php");
    exit;
}

$account_id = $_SESSION['account_id'];
$msg = '';
$generated_key = false;

// --- 1. GERAR RECOVERY KEY ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['generate_rk'])) {
    // Verifica se já tem RK para não sobrescrever acidentalmente
    $chk = $pdo->prepare("SELECT recovery_key FROM accounts WHERE id = ?");
    $chk->execute([$account_id]);
    
    if (empty($chk->fetch()['recovery_key'])) {
        // Gera uma chave aleatória formato XXXX-XXXX-XXXX-XXXX
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $new_key = substr(str_shuffle($chars), 0, 4) . '-' . 
                   substr(str_shuffle($chars), 0, 4) . '-' . 
                   substr(str_shuffle($chars), 0, 4) . '-' . 
                   substr(str_shuffle($chars), 0, 4);
        
        $upd = $pdo->prepare("UPDATE accounts SET recovery_key = ? WHERE id = ?");
        if ($upd->execute([$new_key, $account_id])) {
            $generated_key = $new_key;
            $msg = '<div class="alert alert-success border-0 shadow-sm">
                        <h4 class="alert-heading fw-bold"><i class="fas fa-check-circle"></i> Sucesso!</h4>
                        <p>Sua Recovery Key foi gerada. <strong>ANOTE AGORA</strong>, ela não será mostrada novamente.</p>
                    </div>';
        }
    } else {
        $msg = '<div class="alert alert-danger">Você já possui uma Recovery Key gerada!</div>';
    }
}

// --- 2. BUSCAR DADOS DA CONTA ---
$stmt = $pdo->prepare("SELECT id, name, email, premdays, premium_points, creation, recovery_key FROM accounts WHERE id = ?");
$stmt->execute([$account_id]);
$account = $stmt->fetch();

// Buscar personagens
$stmtChars = $pdo->prepare("SELECT * FROM players WHERE account_id = ? ORDER BY name ASC");
$stmtChars->execute([$account_id]);
$characters = $stmtChars->fetchAll();

// Cálculos de Segurança e VIP
$hasRK = !empty($account['recovery_key']);
$vipPercent = ($account['premdays'] > 360) ? 100 : ($account['premdays'] / 360) * 100;
$securityScore = 50; // Começa com 50% (Senha)
if ($hasRK) $securityScore += 50; // +50% se tiver RK
?>

<style>
    /* Estilos Exclusivos do Painel */
    .acc-header {
        background: linear-gradient(135deg, #2c3e50 0%, #4ca1af 100%);
        color: white; padding: 40px; border-radius: 15px; margin-bottom: 30px;
        position: relative; overflow: hidden;
    }
    .acc-header::after {
        content: ''; position: absolute; top: 0; right: 0; bottom: 0; left: 0;
        background: url('images/pattern.png'); opacity: 0.1;
    }
    .vip-badge {
        position: absolute; top: 20px; right: 20px;
        background: #ffcb05; color: #2c3e50; padding: 5px 15px;
        border-radius: 20px; font-weight: 800; text-transform: uppercase;
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
    }
    .char-card {
        transition: transform 0.2s; border: 1px solid #eee;
    }
    .char-card:hover {
        transform: translateY(-5px); border-color: #ffcb05;
        box-shadow: 0 10px 20px rgba(0,0,0,0.05);
    }
    .rk-display {
        font-family: 'Courier New', monospace; font-size: 2rem; letter-spacing: 5px;
        background: #333; color: #0f0; padding: 20px; border-radius: 10px;
        text-align: center; border: 2px dashed #555; margin: 20px 0;
    }
</style>

<div class="container my-5">

    <div class="acc-header shadow-lg">
        <div class="vip-badge">
            <?php echo ($account['premdays'] > 0) ? "VIP ACCOUNT" : "FREE ACCOUNT"; ?>
        </div>
        
        <div class="row align-items-center position-relative" style="z-index: 2;">
            <div class="col-md-2 text-center mb-3 mb-md-0">
                <div class="bg-white text-dark rounded-circle d-flex align-items-center justify-content-center mx-auto" style="width: 80px; height: 80px; font-size: 2rem; font-weight: bold;">
                    <?php echo substr($account['name'], 0, 1); ?>
                </div>
            </div>
            <div class="col-md-6">
                <h2 class="fw-bold mb-0">Olá, <?php echo htmlspecialchars($account['name']); ?></h2>
                <p class="opacity-75 mb-2"><?php echo $account['email']; ?></p>
                <div class="d-flex align-items-center gap-3">
                    <span class="badge bg-dark bg-opacity-50 border border-light">
                        <i class="far fa-calendar-alt"></i> Membro desde <?php echo date('Y', $account['creation']); ?>
                    </span>
                    <span class="badge <?php echo ($securityScore == 100) ? 'bg-success' : 'bg-warning text-dark'; ?>">
                        <i class="fas fa-shield-alt"></i> Segurança: <?php echo $securityScore; ?>%
                    </span>
                </div>
            </div>
            <div class="col-md-4 text-center text-md-end mt-3 mt-md-0">
                <small class="text-uppercase fw-bold opacity-75">Saldo de Pontos</small>
                <h1 class="fw-bold text-warning mb-0"><?php echo number_format($account['premium_points'], 0, ',', '.'); ?> <small class="fs-6">Pts</small></h1>
                <a href="shop.php" class="btn btn-sm btn-outline-light rounded-pill mt-2">Usar na Loja</a>
            </div>
        </div>
    </div>

    <div class="row">
        
        <div class="col-lg-3 mb-4">
            <div class="list-group shadow-sm">
                <a href="account.php" class="list-group-item list-group-item-action active fw-bold border-0" style="background-color: <?php echo $siteConfig['color_header']; ?>;">
                    <i class="fas fa-users me-2"></i> Personagens
                </a>
                <a href="shop.php" class="list-group-item list-group-item-action border-0">
                    <i class="fas fa-shopping-cart me-2"></i> Comprar Pontos
                </a>
                <a href="#" class="list-group-item list-group-item-action border-0" data-bs-toggle="modal" data-bs-target="#changePassModal">
                    <i class="fas fa-key me-2"></i> Mudar Senha
                </a>
                <a href="logout.php" class="list-group-item list-group-item-action text-danger fw-bold border-0">
                    <i class="fas fa-sign-out-alt me-2"></i> Sair
                </a>
            </div>

            <div class="card border-0 shadow-sm mt-4 bg-white">
                <div class="card-body">
                    <h6 class="fw-bold text-muted text-uppercase mb-3">Status VIP</h6>
                    <div class="d-flex justify-content-between align-items-end mb-2">
                        <span class="display-6 fw-bold text-primary"><?php echo $account['premdays']; ?></span>
                        <span class="text-muted small mb-2">Dias Restantes</span>
                    </div>
                    <div class="progress" style="height: 8px;">
                        <div class="progress-bar bg-warning" role="progressbar" style="width: <?php echo $vipPercent; ?>%"></div>
                    </div>
                    <a href="shop.php" class="btn btn-outline-primary btn-sm w-100 mt-3 fw-bold">Renovar VIP</a>
                </div>
            </div>
        </div>

        <div class="col-lg-9">
            <?php echo $msg; ?>

            <?php if ($generated_key): ?>
                <div class="card border-success shadow-lg mb-4">
                    <div class="card-header bg-success text-white fw-bold">
                        <i class="fas fa-lock"></i> NOVA RECOVERY KEY GERADA
                    </div>
                    <div class="card-body text-center">
                        <p class="card-text text-danger fw-bold">ATENÇÃO: Salve este código agora. Se você perder sua conta, esta é a única forma de recuperar!</p>
                        <div class="rk-display"><?php echo $generated_key; ?></div>
                        <button class="btn btn-secondary btn-sm" onclick="window.print()"><i class="fas fa-print"></i> Imprimir</button>
                    </div>
                </div>
            <?php elseif (!$hasRK): ?>
                <div class="alert alert-warning shadow-sm d-flex align-items-center justify-content-between">
                    <div>
                        <h5 class="alert-heading fw-bold"><i class="fas fa-exclamation-triangle"></i> Conta em Risco!</h5>
                        <p class="mb-0 small">Você ainda não gerou sua Recovery Key. Se perder a senha, perderá a conta.</p>
                    </div>
                    <form method="POST">
                        <button type="submit" name="generate_rk" class="btn btn-warning fw-bold text-dark shadow-sm" onclick="return confirm('Tem certeza? A chave será mostrada apenas UMA vez.');">
                            <i class="fas fa-key"></i> GERAR KEY
                        </button>
                    </form>
                </div>
            <?php endif; ?>

            <div class="d-flex justify-content-between align-items-center mb-3">
                <h4 class="fw-bold text-dark m-0"><i class="fas fa-user-friends text-primary"></i> Meus Personagens</h4>
                <a href="create_character.php" class="btn btn-success fw-bold rounded-pill shadow-sm">
                    <i class="fas fa-plus"></i> Novo Char
                </a>
            </div>

            <?php if (count($characters) > 0): ?>
                <div class="row">
                    <?php foreach($characters as $char): 
                        // Imagem da Outfit
                        $outfit = "https://outfit-images.ots.me/1285_walk_animation/animoutfit.php?id={$char['looktype']}&head={$char['lookhead']}&body={$char['lookbody']}&legs={$char['looklegs']}&feet={$char['lookfeet']}";
                        
                        // Vocação Nome
                        $vocName = ($char['vocation'] == 1) ? 'Treinador' : 'Novato';
                    ?>
                    <div class="col-md-6 mb-3">
                        <div class="card char-card h-100 bg-white">
                            <div class="card-body d-flex align-items-center">
                                <div class="me-3 position-relative">
                                    <img src="<?php echo $outfit; ?>" style="width: 64px; height: 64px; object-fit: contain;">
                                    <span class="position-absolute bottom-0 end-0 badge bg-secondary rounded-pill" style="font-size: 0.6rem;"><?php echo $char['level']; ?></span>
                                </div>
                                <div class="flex-grow-1">
                                    <h5 class="fw-bold mb-0 text-primary">
                                        <a href="character.php?name=<?php echo urlencode($char['name']); ?>" class="text-decoration-none"><?php echo htmlspecialchars($char['name']); ?></a>
                                    </h5>
                                    <small class="text-muted d-block text-uppercase" style="font-size: 0.7rem; letter-spacing: 1px;"><?php echo $vocName; ?></small>
                                    <small class="text-muted"><i class="fas fa-map-marker-alt"></i> <?php echo ($char['town_id'] == 1) ? 'Saffron' : 'Cidade '.$char['town_id']; ?></small>
                                </div>
                                <div class="dropdown">
                                    <button class="btn btn-light btn-sm rounded-circle" type="button" data-bs-toggle="dropdown">
                                        <i class="fas fa-ellipsis-v text-muted"></i>
                                    </button>
                                    <ul class="dropdown-menu dropdown-menu-end border-0 shadow">
                                        <li><a class="dropdown-item" href="character.php?name=<?php echo urlencode($char['name']); ?>">Ver Perfil</a></li>
                                        <li><a class="dropdown-item disabled" href="#">Esconder (VIP)</a></li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li><a class="dropdown-item text-danger" href="#" onclick="alert('Para deletar, use o cliente do jogo por segurança.');">Deletar</a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="text-center py-5 bg-white rounded shadow-sm border">
                    <i class="fas fa-user-slash fa-3x text-muted mb-3 opacity-25"></i>
                    <h5 class="text-muted">Você não tem personagens.</h5>
                    <a href="create_character.php" class="btn btn-primary mt-2">Crie seu primeiro agora!</a>
                </div>
            <?php endif; ?>

        </div>
    </div>
</div>

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