<?php
session_start();
require '../conexao.php'; // Se estiver em subpasta, use '../conexao.php'

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Inicializa valores padrão (Caso o banco falhe ou seja novo)
$body = 'body_human.png';
$eyes = 'eyes_blue.png';
$hair = 'hair_short.png';
$armor = 'cloth_peasant.png';

try {
    // Tenta recuperar avatar atual
    // Se as colunas não existirem, vai cair no 'catch' e usar o padrão
    $stmt = $pdo->prepare("SELECT avatar_body, avatar_eyes, avatar_hair, avatar_armor FROM personagens WHERE id = :id");
    $stmt->execute([':id' => $_SESSION['personagem']]);
    $avatar = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($avatar) {
        $body = $avatar['avatar_body'] ?? $body;
        $eyes = $avatar['avatar_eyes'] ?? $eyes;
        $hair = $avatar['avatar_hair'] ?? $hair;
        $armor = $avatar['avatar_armor'] ?? $armor;
    }
} catch (Exception $e) {
    // Se der erro (ex: coluna não existe), ignora e usa o padrão.
    // Em produção, você pode logar o erro: error_log($e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Criador de Avatar - Mavilla</title>
    <link rel="stylesheet" href="css/dashboard.css">
    <style>
        body {
            background: url('rpg-login-background.jpg') no-repeat center center fixed;
            background-size: cover;
            display: flex; align-items: center; justify-content: center; min-height: 100vh;
            font-family: 'Segoe UI', sans-serif;
            margin: 0; padding: 20px;
        }

        /* Container Principal */
        .studio-container {
            display: flex;
            gap: 40px;
            background-color: rgba(0, 5, 20, 0.95);
            border: 2px solid #0000FF;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 0 30px rgba(0,0,255,0.3);
            flex-wrap: wrap;
            justify-content: center;
            backdrop-filter: blur(5px);
        }

        /* Área do Personagem (Preview) */
        .preview-box {
            width: 250px;
            height: 250px;
            background: radial-gradient(circle, #333, #000);
            border: 4px solid #00f3ff;
            border-radius: 10px;
            position: relative;
            box-shadow: inset 0 0 20px #000;
            overflow: hidden;
        }

        /* As Camadas (Layers) - O Segredo */
        .layer {
            position: absolute;
            top: 0; left: 0;
            width: 100%; height: 100%;
            image-rendering: pixelated; /* Importante para pixel art ficar nítido */
            transition: 0.2s;
        }

        /* Controles */
        .controls-box {
            width: 300px;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        h2 { color: #00f3ff; margin-top: 0; text-transform: uppercase; text-shadow: 0 0 10px #0000FF; text-align: center; }

        label { color: #aaa; font-size: 0.9rem; font-weight: bold; margin-bottom: 5px; display: block; }

        select {
            width: 100%;
            background: #000;
            color: #fff;
            border: 1px solid #0000FF;
            padding: 10px;
            border-radius: 5px;
            outline: none;
            cursor: pointer;
        }
        select:focus { box-shadow: 0 0 10px #00f3ff; }

        .btn-save {
            background: #28a745; color: #fff; border: none; padding: 12px; 
            border-radius: 5px; font-weight: bold; font-size: 1.1rem; 
            cursor: pointer; margin-top: 20px; transition: 0.3s;
            text-transform: uppercase;
            box-shadow: 0 0 10px #28a745;
        }
        .btn-save:hover { box-shadow: 0 0 20px #28a745; background: #218838; }
        
        .btn-back {
            background: transparent; border: 1px solid #555; color: #ccc; padding: 10px;
            border-radius: 5px; cursor: pointer; margin-top: 5px; width: 100%;
            text-transform: uppercase; font-weight: bold;
        }
        .btn-back:hover { border-color: #fff; color: #fff; }

        /* SVG PLACEHOLDERS (Para teste - Substitua por imagens reais depois) */
        /* Essas classes simulam as imagens para você ver funcionando */
        .sim-body { fill: #ffccaa; } /* Pele */
        .sim-orc { fill: #55aa55; }   /* Orc */
        
        .sim-hair-black { fill: #000; }
        .sim-hair-red { fill: #aa0000; }
        
        .sim-armor-iron { fill: #ccc; stroke: #555; stroke-width:2; }
        .sim-armor-gold { fill: #ffcc00; stroke: #996600; stroke-width:2; }
    </style>
</head>
<body>

    <div class="studio-container">
        
        <div style="text-align:center;">
            <div class="preview-box" id="avatarStage">
                <img id="img_body" class="layer" src="" style="z-index: 1;">
                <img id="img_eyes" class="layer" src="" style="z-index: 2;">
                <img id="img_hair" class="layer" src="" style="z-index: 3;">
                <img id="img_armor" class="layer" src="" style="z-index: 4;">
            </div>
            <p style="color:#00f3ff; margin-top:10px; font-size:0.8rem; text-transform: uppercase; font-weight: bold;">Visualização</p>
        </div>

        <div class="controls-box">
            <h2>Customizar</h2>

            <div>
                <label>Raça / Pele</label>
                <select id="sel_body" onchange="updateAvatar()">
                    <option value="body_human" <?= $body == 'body_human' ? 'selected' : '' ?>>Humano</option>
                    <option value="body_orc" <?= $body == 'body_orc' ? 'selected' : '' ?>>Orc</option>
                    <option value="body_elf" <?= $body == 'body_elf' ? 'selected' : '' ?>>Elfo Escuro</option>
                </select>
            </div>

            <div>
                <label>Cor dos Olhos</label>
                <select id="sel_eyes" onchange="updateAvatar()">
                    <option value="eyes_blue" <?= $eyes == 'eyes_blue' ? 'selected' : '' ?>>Azul</option>
                    <option value="eyes_red" <?= $eyes == 'eyes_red' ? 'selected' : '' ?>>Vermelho</option>
                    <option value="eyes_green" <?= $eyes == 'eyes_green' ? 'selected' : '' ?>>Verde</option>
                </select>
            </div>

            <div>
                <label>Cabelo</label>
                <select id="sel_hair" onchange="updateAvatar()">
                    <option value="hair_messy_black" <?= $hair == 'hair_messy_black' ? 'selected' : '' ?>>Curto Preto</option>
                    <option value="hair_long_blonde" <?= $hair == 'hair_long_blonde' ? 'selected' : '' ?>>Longo Loiro</option>
                    <option value="hair_punk_red" <?= $hair == 'hair_punk_red' ? 'selected' : '' ?>>Moicano Vermelho</option>
                    <option value="none" <?= $hair == 'none' ? 'selected' : '' ?>>Careca</option>
                </select>
            </div>

            <div>
                <label>Vestimenta</label>
                <select id="sel_armor" onchange="updateAvatar()">
                    <option value="armor_rag" <?= $armor == 'armor_rag' ? 'selected' : '' ?>>Trapos</option>
                    <option value="armor_iron" <?= $armor == 'armor_iron' ? 'selected' : '' ?>>Armadura de Ferro</option>
                    <option value="armor_gold" <?= $armor == 'armor_gold' ? 'selected' : '' ?>>Armadura Real</option>
                </select>
            </div>

            <button class="btn-save" onclick="salvarAlteracoes()">SALVAR AVATAR</button>
            <button class="btn-back" onclick="window.location.href='dashboardmed.php'">Voltar ao Jogo</button>
        </div>
    </div>

    <script>
        // --- SISTEMA DE PLACEHOLDER (Gera imagens falsas para testar) ---
        // IMPORTANTE: Quando tiver as imagens reais, delete esta função e mude o updateAvatar
        function getPlaceholder(type, val) {
            if(val === 'none') return 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; // Transparente

            let color = '#fff';
            let shape = '';

            if(type === 'body') {
                if(val === 'body_human') color = '#ffccaa';
                if(val === 'body_orc') color = '#55aa55';
                if(val === 'body_elf') color = '#5533aa';
                shape = '<circle cx="125" cy="100" r="50" fill="'+color+'"/><rect x="75" y="150" width="100" height="100" fill="'+color+'"/>';
            }
            if(type === 'eyes') {
                if(val === 'eyes_blue') color = '#00f3ff';
                if(val === 'eyes_red') color = '#ff0000';
                if(val === 'eyes_green') color = '#00ff00';
                shape = '<circle cx="110" cy="100" r="5" fill="'+color+'"/><circle cx="140" cy="100" r="5" fill="'+color+'"/>';
            }
            if(type === 'hair') {
                if(val.includes('black')) color = '#000';
                if(val.includes('blonde')) color = '#ffcc00';
                if(val.includes('red')) color = '#aa0000';
                shape = '<path d="M75,100 Q125,20 175,100" fill="'+color+'" />';
            }
            if(type === 'armor') {
                if(val === 'armor_iron') { color = '#888'; shape = '<rect x="80" y="155" width="90" height="90" fill="'+color+'" stroke="white" stroke-width="2"/>'; }
                else if(val === 'armor_gold') { color = '#ffaa00'; shape = '<rect x="80" y="155" width="90" height="90" fill="'+color+'" stroke="yellow" stroke-width="2"/>'; }
                else { color = '#654321'; shape = '<rect x="85" y="160" width="80" height="80" fill="'+color+'"/>'; }
            }

            const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="250" height="250" viewBox="0 0 250 250">${shape}</svg>`;
            return 'data:image/svg+xml;base64,' + btoa(svg);
        }

        // --- ATUALIZAÇÃO VISUAL ---
        function updateAvatar() {
            const bodyVal = document.getElementById('sel_body').value;
            const eyesVal = document.getElementById('sel_eyes').value;
            const hairVal = document.getElementById('sel_hair').value;
            const armorVal = document.getElementById('sel_armor').value;

            // ATENÇÃO: Estamos usando o gerador de SVG. 
            // Quando tiver PNGs reais, use: document.getElementById('img_body').src = 'assets/body/' + bodyVal + '.png';
            document.getElementById('img_body').src = getPlaceholder('body', bodyVal);
            document.getElementById('img_eyes').src = getPlaceholder('eyes', eyesVal);
            document.getElementById('img_hair').src = getPlaceholder('hair', hairVal);
            document.getElementById('img_armor').src = getPlaceholder('armor', armorVal);
        }

        // --- SALVAR NO BANCO ---
        function salvarAlteracoes() {
            const dados = new FormData();
            dados.append('body', document.getElementById('sel_body').value);
            dados.append('eyes', document.getElementById('sel_eyes').value);
            dados.append('hair', document.getElementById('sel_hair').value);
            dados.append('armor', document.getElementById('sel_armor').value);

            fetch('salvar_avatar_db.php', {
                method: 'POST',
                body: dados
            })
            .then(response => response.text())
            .then(res => {
                alert('Avatar Salvo com Sucesso!');
            })
            .catch(err => alert('Erro de conexão.'));
        }

        // Inicia o avatar com o estado atual
        updateAvatar();
    </script>
</body>
</html>