<?php
// ==========================================================
// ARQUIVO: character.php
// VERSÃO: Avatar Letra + Dados Dinâmicos do BD
// ==========================================================

require 'includes/conexao.php';
include 'includes/header.php';

// --- CONFIGURAÇÃO DINÂMICA (Vem do Banco agora) ---
// Busca configurações criadas no Admin
try {
    // Tenta buscar, se as tabelas não existirem (ainda não rodou o SQL), retorna array vazio para não dar erro fatal
    $badgesConfig = $pdo->query("SELECT * FROM site_badges ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $badgesConfig = []; }

try {
    $questsConfig = $pdo->query("SELECT * FROM site_quests ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $questsConfig = []; }


// --- LÓGICA DO PLAYER ---
$name = isset($_GET['name']) ? urldecode(trim($_GET['name'])) : null;
$playerFound = false;

if ($name) {
    try {
        // 1. DADOS GERAIS DO JOGADOR
        $sql = "SELECT p.*, a.premdays, g.name as guild_name, gr.name as rank_name, 
                h.name as house_name, h.town_id as house_town
                FROM players p
                LEFT JOIN accounts a ON p.account_id = a.id
                LEFT JOIN guild_membership gm ON p.id = gm.player_id
                LEFT JOIN guilds g ON gm.guild_id = g.id
                LEFT JOIN guild_ranks gr ON gm.rank_id = gr.id
                LEFT JOIN houses h ON h.owner = p.id
                WHERE p.name = :name AND p.deleted = 0";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':name' => $name]);
        $player = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($player) {
            $playerFound = true;
            $pid = $player['id'];

            // Letra Inicial para o Avatar
            $initialLetter = strtoupper(substr($player['name'], 0, 1));

            // 2. SKILLS (Fishing)
            $sqlSkills = "SELECT skillid, value FROM player_skills WHERE player_id = ?";
            $stmtSkills = $pdo->prepare($sqlSkills);
            $stmtSkills->execute([$pid]);
            $skillsRaw = $stmtSkills->fetchAll(PDO::FETCH_KEY_PAIR);
            $fishingLevel = $skillsRaw[6] ?? 10; 

            // 3. STORAGES (Para Badges e Quests)
            $sqlStorage = "SELECT `key`, `value` FROM player_storage WHERE player_id = ?";
            $stmtStore = $pdo->prepare($sqlStorage);
            $stmtStore->execute([$pid]);
            $myStorages = $stmtStore->fetchAll(PDO::FETCH_KEY_PAIR);

            // 4. HISTÓRICO DE MORTES
            $sqlDeaths = "SELECT 
                            pd.date, pd.level, 
                            ek.name as monster_name, 
                            pl.name as player_killer_name,
                            pd.mostdamage_by, 
                            pd.monster
                          FROM player_deaths pd
                          LEFT JOIN killers k ON k.death_id = pd.id AND k.final_hit = 1
                          LEFT JOIN environment_killers ek ON ek.kill_id = k.id
                          LEFT JOIN player_killers pk ON pk.kill_id = k.id
                          LEFT JOIN players pl ON pl.id = pk.player_id
                          WHERE pd.player_id = ? 
                          ORDER BY pd.date DESC 
                          LIMIT 5";
            
            $stmtDeaths = $pdo->prepare($sqlDeaths);
            $stmtDeaths->execute([$pid]);
            $deaths = $stmtDeaths->fetchAll(PDO::FETCH_ASSOC);

            // Cálculos de Status
            $hpPercent = ($player['health'] / max($player['healthmax'], 1)) * 100;
            $manaPercent = ($player['mana'] / max($player['manamax'], 1)) * 100;
            $statusOnline = ($player['online'] == 1) ? '<span class="status-badge online">ONLINE</span>' : '<span class="status-badge offline">OFFLINE</span>';
            $isVip = ($player['premdays'] > 0);
        }
    } catch (Exception $e) {
        $error = "Erro ao buscar dados.";
    }
}
?>

<style>
    :root {
        --bg-dark: #0f172a;       
        --bg-card: #1e293b;       
        --bg-card-hover: #334155;
        --primary: #3b82f6;       
        --secondary: #64748b;
        --accent: #f59e0b;        
        --text-main: #ffffff;     
        --text-muted: #cbd5e1;    
        --success: #22c55e;
        --danger: #ef4444;
    }

    body {
        background-color: var(--bg-dark);
        color: var(--text-main);
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    /* BUSCA */
    .search-container { max-width: 600px; margin: 60px auto; text-align: center; }
    .custom-input {
        background: var(--bg-card); border: 1px solid #475569; color: white;
        padding: 15px 25px; border-radius: 50px; font-size: 1.1rem;
    }
    .custom-input:focus {
        background: var(--bg-card-hover); color: white; border-color: var(--primary);
        box-shadow: 0 0 20px rgba(59, 130, 246, 0.4); outline: none;
    }
    .custom-input::placeholder { color: #64748b; }

    /* CARD PRINCIPAL */
    .profile-card {
        background: rgba(30, 41, 59, 0.95);
        border: 1px solid rgba(255,255,255,0.08);
        border-radius: 16px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.6);
        overflow: hidden;
        margin-bottom: 30px;
    }

    .hero-section {
        background: linear-gradient(135deg, #0f172a 0%, #172554 100%);
        padding: 40px;
        position: relative;
    }
    .hero-section::after {
        content: ''; position: absolute; top: 0; right: 0; width: 300px; height: 100%;
        background: radial-gradient(circle, rgba(59, 130, 246, 0.1) 0%, transparent 70%);
        pointer-events: none;
    }

    /* AVATAR COM LETRA */
    .avatar-letter {
        width: 130px; height: 130px;
        background: linear-gradient(135deg, var(--primary), #1e40af);
        border-radius: 50%;
        border: 4px solid rgba(255,255,255,0.2);
        display: flex; align-items: center; justify-content: center;
        box-shadow: 0 0 30px rgba(59, 130, 246, 0.5);
        z-index: 2;
        color: white;
        font-size: 4rem;
        font-weight: 800;
        text-shadow: 0 4px 10px rgba(0,0,0,0.3);
        font-family: 'Rajdhani', sans-serif;
    }

    .player-name {
        font-size: 2.5rem; font-weight: 800; text-transform: uppercase;
        letter-spacing: 1px; text-shadow: 0 4px 10px rgba(0,0,0,0.5); margin: 0; color: white;
    }

    .status-badge {
        padding: 6px 15px; border-radius: 20px; font-size: 0.85rem;
        font-weight: bold; letter-spacing: 0.5px; text-transform: uppercase;
    }
    .status-badge.online { background: var(--success); color: white; box-shadow: 0 0 15px rgba(34, 197, 94, 0.4); }
    .status-badge.offline { background: var(--secondary); color: white; }

    /* STATUS BARS */
    .stat-box {
        background: rgba(15, 23, 42, 0.5); padding: 15px; border-radius: 12px;
        border: 1px solid rgba(255,255,255,0.05);
    }
    .progress { height: 10px; background-color: #334155; border-radius: 5px; overflow: hidden; }
    .bg-hp { background: linear-gradient(90deg, #ef4444, #f87171); }
    .bg-mana { background: linear-gradient(90deg, #3b82f6, #60a5fa); }

    /* SEÇÕES */
    .section-title {
        border-left: 4px solid var(--primary); padding-left: 15px;
        font-weight: 800; text-transform: uppercase; margin-bottom: 25px;
        color: var(--text-main); letter-spacing: 1px; font-size: 1.1rem;
    }

    /* BADGES */
    .badges-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(85px, 1fr)); gap: 15px; }
    .badge-item {
        background: var(--bg-card); border: 1px solid #334155;
        border-radius: 12px; padding: 15px; text-align: center; transition: all 0.3s ease;
    }
    .badge-item.locked { opacity: 0.3; filter: grayscale(100%); }
    .badge-item.unlocked { 
        border-color: var(--accent); background: rgba(245, 158, 11, 0.1);
        transform: translateY(-5px); box-shadow: 0 5px 20px rgba(245, 158, 11, 0.15);
    }
    .badge-item i { font-size: 2rem; margin-bottom: 8px; display: block; }
    .badge-name { font-size: 0.7rem; font-weight: bold; color: var(--text-muted); }

    /* QUESTS */
    .quest-item {
        display: flex; justify-content: space-between; align-items: center;
        padding: 15px; border-bottom: 1px solid #334155; transition: 0.2s;
    }
    .quest-item:last-child { border-bottom: none; }
    .quest-item:hover { background: rgba(255,255,255,0.03); }
    .quest-status.completed { color: var(--success); font-weight: bold; }
    .quest-status.pending { color: var(--danger); font-size: 0.9rem; opacity: 0.8; }

    /* SKILL & DEATHS */
    .skill-box {
        text-align: center; padding: 15px; background: rgba(0,0,0,0.2);
        border-radius: 12px; border: 1px solid rgba(59, 130, 246, 0.2); min-width: 100px;
    }
    .skill-box h5 { color: white; font-size: 1.5rem; }

    .death-row {
        background: rgba(239, 68, 68, 0.05); border-left: 3px solid var(--danger);
        padding: 12px 15px; margin-bottom: 10px; border-radius: 0 8px 8px 0;
        font-size: 0.95rem; transition: 0.2s;
    }
    .death-row:hover { background: rgba(239, 68, 68, 0.1); }
    .death-date { display: block; font-size: 0.75rem; color: #94a3b8; margin-bottom: 2px; }
    .killer-name { color: #fca5a5; font-weight: bold; text-decoration: underline; }
    .info-list li { padding: 10px 0; border-bottom: 1px solid #334155; color: var(--text-muted); }
    .info-list li:last-child { border-bottom: none; }
    .info-list strong { color: white; float: right; }

    @media (max-width: 768px) {
        .hero-section { text-align: center; padding: 30px 20px; }
        .hero-content { flex-direction: column; }
        .avatar-letter { margin: 0 auto 20px auto; }
        .skill-box { margin-top: 20px; width: 100%; }
        .player-name { font-size: 2rem; }
    }
</style>

<div class="container pb-5">

    <?php if (!$playerFound): ?>
        <div class="search-container">
            <div class="mb-5">
                <i class="fas fa-search fa-5x text-secondary mb-4 opacity-50"></i>
                <h2 class="fw-bold text-white">Procurar Treinador</h2>
                <p class="text-muted fs-5">Digite o nome para ver estatísticas, time e conquistas.</p>
            </div>
            <form action="" method="GET">
                <div class="input-group">
                    <input type="text" name="name" class="form-control custom-input" placeholder="Ex: Ash Ketchum" required>
                </div>
                <button class="btn btn-primary px-5 py-3 mt-4 rounded-pill fw-bold shadow-lg w-50" type="submit">
                    BUSCAR AGORA
                </button>
            </form>
            <?php if(isset($_GET['name'])): ?>
                <div class="alert alert-danger mt-5 bg-transparent border border-danger text-danger fw-bold rounded-3">
                    <i class="fas fa-exclamation-circle me-2"></i> Personagem não encontrado.
                </div>
            <?php endif; ?>
        </div>
    <?php else: ?>

        <div class="profile-card mt-5 fade-in">
            <div class="hero-section d-flex align-items-center gap-4 hero-content">
                
                <div class="avatar-letter">
                    <?php echo $initialLetter; ?>
                </div>

                <div class="flex-grow-1">
                    <h1 class="player-name"><?php echo htmlspecialchars($player['name']); ?></h1>
                    
                    <div class="d-flex align-items-center gap-2 mt-3 flex-wrap justify-content-center justify-content-md-start">
                        <?php echo $statusOnline; ?>
                        <span class="badge bg-dark border border-secondary py-2 px-3">Level <?php echo $player['level']; ?></span>
                        <span class="badge bg-dark border border-secondary py-2 px-3"><?php echo $player['vocation'] == 1 ? 'Treinador' : 'Novato'; ?></span>
                        <?php if($isVip): ?>
                            <span class="badge bg-warning text-dark py-2 px-3 fw-bold"><i class="fas fa-crown me-1"></i> VIP</span>
                        <?php endif; ?>
                    </div>

                    <?php if($player['guild_name']): ?>
                        <div class="mt-3 text-info fw-semibold">
                            <i class="fas fa-shield-alt me-1"></i> <?php echo $player['rank_name']; ?> da guild <strong><?php echo $player['guild_name']; ?></strong>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="skill-box d-none d-md-block">
                    <i class="fas fa-fish fa-2x text-primary mb-2"></i>
                    <h5 class="m-0 fw-bold"><?php echo $fishingLevel; ?></h5>
                    <small class="text-muted text-uppercase fw-bold" style="font-size: 0.7rem;">Fishing</small>
                </div>
            </div>

            <div class="px-4 pb-4 pt-2 bg-dark bg-opacity-25">
                <div class="row g-3">
                    <div class="col-md-6">
                        <div class="stat-box">
                            <div class="d-flex justify-content-between mb-2">
                                <span class="fw-bold text-white small"><i class="fas fa-heart text-danger me-1"></i> VIDA</span>
                                <span class="text-white small fw-bold"><?php echo $player['health']; ?> / <?php echo $player['healthmax']; ?></span>
                            </div>
                            <div class="progress">
                                <div class="progress-bar bg-hp" style="width: <?php echo $hpPercent; ?>%"></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="stat-box">
                            <div class="d-flex justify-content-between mb-2">
                                <span class="fw-bold text-white small"><i class="fas fa-bolt text-info me-1"></i> POKEMONS (MANA)</span>
                                <span class="text-white small fw-bold"><?php echo $player['mana']; ?> / <?php echo $player['manamax']; ?></span>
                            </div>
                            <div class="progress">
                                <div class="progress-bar bg-mana" style="width: <?php echo $manaPercent; ?>%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-4">
            <div class="col-lg-7">
                
                <div class="profile-card p-4 h-auto">
                    <h5 class="section-title"><i class="fas fa-medal me-2"></i> Insígnias de Kanto</h5>
                    <div class="badges-grid">
                        <?php if(empty($badgesConfig)): ?>
                            <div class="col-12 text-center text-muted small">Nenhuma insígnia configurada no painel.</div>
                        <?php else: ?>
                            <?php foreach($badgesConfig as $bData): 
                                $hasBadge = isset($myStorages[$bData['storage_id']]) && $myStorages[$bData['storage_id']] > 0;
                                $cssClass = $hasBadge ? 'unlocked' : 'locked';
                                $iconColor = $hasBadge ? $bData['color'] : '#64748b';
                            ?>
                            <div class="badge-item <?php echo $cssClass; ?>" title="<?php echo $bData['name']; ?>">
                                <i class="fas <?php echo $bData['icon']; ?>" style="color: <?php echo $iconColor; ?>"></i>
                                <span class="badge-name"><?php echo $bData['name']; ?></span>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="profile-card p-4 h-auto">
                    <h5 class="section-title"><i class="fas fa-scroll me-2"></i> Log de Missões</h5>
                    <div class="d-flex flex-column">
                        <?php if(empty($questsConfig)): ?>
                            <div class="text-center text-muted small">Nenhuma quest configurada no painel.</div>
                        <?php else: ?>
                            <?php foreach($questsConfig as $qData): 
                                $isDone = isset($myStorages[$qData['storage_id']]) && $myStorages[$qData['storage_id']] > 0;
                            ?>
                            <div class="quest-item">
                                <span class="text-white fw-semibold"><?php echo $qData['name']; ?></span>
                                <?php if($isDone): ?>
                                    <span class="quest-status completed"><i class="fas fa-check-circle me-1"></i> Completa</span>
                                <?php else: ?>
                                    <span class="quest-status pending"><i class="fas fa-clock me-1"></i> Pendente</span>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

            </div>

            <div class="col-lg-5">
                <div class="profile-card p-4">
                    <h5 class="section-title"><i class="fas fa-info-circle me-2"></i> Informações</h5>
                    <ul class="list-unstyled info-list mb-0">
                        <li>Residência <strong><?php echo $player['house_name'] ?: 'Sem casa'; ?></strong></li>
                        <li>Último Login <strong><?php echo $player['lastlogin'] > 0 ? date('d/m/Y H:i', $player['lastlogin']) : 'Nunca'; ?></strong></li>
                        <li>Criado em <strong><?php echo isset($player['created']) ? date('d/m/Y', $player['created']) : '-'; ?></strong></li>
                    </ul>
                </div>

                <div class="profile-card p-4">
                    <h5 class="section-title"><i class="fas fa-skull me-2"></i> Mortes Recentes</h5>
                    <?php if(count($deaths) > 0): ?>
                        <?php foreach($deaths as $d): 
                            $killer = 'Desconhecido';
                            if (!empty($d['monster_name'])) { $killer = $d['monster_name']; } 
                            elseif (!empty($d['player_killer_name'])) { $killer = $d['player_killer_name']; }
                            elseif (!empty($d['mostdamage_by']) && $d['mostdamage_by'] !== 'valor_padrao') { $killer = $d['mostdamage_by']; }
                            elseif (!empty($d['monster'])) { $killer = $d['monster']; }
                        ?>
                        <div class="death-row">
                            <span class="death-date"><?php echo date('d/m/Y H:i', $d['date']); ?></span>
                            <div>
                                Morreu no level <strong class="text-white"><?php echo $d['level']; ?></strong> para 
                                <span class="killer-name"><?php echo htmlspecialchars($killer); ?></span>.
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="text-center text-muted py-4 rounded border border-secondary border-opacity-25" style="border-style: dashed !important;">
                            <i class="fas fa-shield-alt fa-2x mb-2 opacity-50"></i><br>
                            Nenhuma morte registrada recentemente.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

    <?php endif; ?>
</div>

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