<?php

require '../conexao.php';
require '../config_seguranca.php'; // ADICIONADO: Segurança Central

// Desativar erros em produção (Segurança por obscuridade)
ini_set('display_errors', 0);
error_reporting(0); // Em produção, zero. Em dev, E_ALL.

if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

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

$_SESSION['msg'] = "";
$_SESSION['msg2'] = "";


$user_id = $_SESSION['user_name'];
$user_name = $_SESSION['user_name'];
$_SESSION['vendido'] = "0";

$user_wallet = $_SESSION['user_wallet'];


try {
    // --- BUSCA SALDO SEGURO NA TABELA DEDICADA ---
    $stmt = $pdo->prepare("SELECT saldo FROM carteiras_saldos WHERE wallet = :wallet");
    $stmt->execute([':wallet' => $user_wallet]);
    $saldo_db = $stmt->fetchColumn();

    if ($saldo_db === false) {
        $stmtInsert = $pdo->prepare("INSERT INTO carteiras_saldos (wallet, saldo) VALUES (:wallet, 0.00)");
        $stmtInsert->execute([':wallet' => $user_wallet]);
        $saldo_carteira = "0.00";
    } else {
        $saldo_carteira = $saldo_db;
    }

    // Formatação visual
    $cor_saldo_carteira = $saldo_carteira >= 0 ? '#039126' : '#ff2222';
    $saldo_carteira_formatado = number_format($saldo_carteira, 2, ',', '.'); 

} catch (PDOException $e) {
    $saldo_carteira_formatado = "Erro";
    $cor_saldo_carteira = '#ff2222';
    // Log interno do erro, nunca exibir $e->getMessage() para o usuário em produção
    error_log("Erro SQL Mercado: " . $e->getMessage());
}

$stmt = $pdo->prepare("SELECT COUNT(*) FROM fichaspersonagens WHERE jogador = ?");
$stmt->execute([$user_name]);
$totalFichas = $stmt->fetchColumn();

$vendendo = 'vendendo';
$sql = "SELECT * FROM personagens WHERE jogador = :user_name AND situacao != :vendendo";
$stmt = $pdo->prepare($sql);
$stmt->execute([':user_name' => $user_name, ':vendendo' => $vendendo]);
$personagens = $stmt->fetchAll(PDO::FETCH_ASSOC);

$csrf_token = $_SESSION['csrf_token'];
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mercado - Mavilla</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/dashboard.css">
    
    <style>
        /* === FUNDO E ESTRUTURA === */
        html { background: none !important; background-color: transparent !important; }

        body {
            font-family: 'Roboto', sans-serif;
            background: url('../rpg-login-background.jpg') no-repeat center center fixed !important;
            background-size: cover !important;
            background-color: transparent !important; 
            margin: 0;
            padding: 20px;
            min-height: 100vh;
            color: white;
        }

        .container, .market-stack { background: none !important; background-color: transparent !important; }

        .market-stack {
            display: flex;
            flex-direction: column;
            gap: 30px;
            max-width: 700px;
            margin: 0 auto;
            padding: 20px;
        }

        /* === CARDS VIDRO === */
        .neon-card {
            background-color: rgba(0, 5, 30, 0.85); 
            border: 2px solid var(--primary);
            box-shadow: 0 0 15px rgba(0, 0, 255, 0.4), inset 0 0 20px rgba(0,0,255,0.1);
            border-radius: 15px;
            padding: 30px;
            text-align: center;
            backdrop-filter: blur(4px);
        }

        h1, h3 {
            color: var(--neon-bright);
            text-transform: uppercase;
            text-shadow: 0 0 10px var(--primary);
            font-family: 'Times New Roman', serif;
            border-bottom: 1px solid var(--primary);
            padding-bottom: 15px;
            margin-bottom: 25px;
        }

        /* Inputs Neon */
        input[type="text"], input[type="number"], input[type="password"], select {
            background-color: rgba(0, 0, 0, 0.7) !important;
            border: 2px solid var(--primary) !important;
            color: #fff !important;
            padding: 12px;
            border-radius: 6px;
            width: 100%;
            max-width: 400px;
            margin-bottom: 15px;
            text-align: center;
            font-size: 1rem;
            outline: none;
        }
        input:focus, select:focus {
            box-shadow: 0 0 15px var(--neon-bright) !important;
            border-color: #fff !important;
        }

        /* Botões Padrão (Azul) */
        button {
            background-color: #000 !important;
            color: #fff !important;
            border: 2px solid var(--primary) !important;
            padding: 12px 25px !important;
            border-radius: 8px !important;
            cursor: pointer !important;
            font-weight: bold !important;
            text-transform: uppercase !important;
            width: 100%;
            max-width: 400px;
            transition: all 0.3s ease !important;
            box-shadow: 0 0 5px var(--primary);
        }
        button:hover {
            background-color: var(--primary) !important;
            color: #000 !important;
            box-shadow: 0 0 20px var(--neon-bright) !important;
            border-color: #fff !important;
        }

        /* === BOTÃO DE DINHEIRO (VERDE ESPECÍFICO #039126) === */
        .btn-money {
            border-color: #039126 !important;
            color: #039126 !important; /* Texto verde no fundo preto */
            background-color: #000 !important; /* Fundo preto padrão */
            box-shadow: 0 0 8px rgba(3, 145, 38, 0.4) !important;
        }
        
        /* HOVER: Fundo Verde, Texto Branco */
        .btn-money:hover {
            background-color: #039126 !important;
            color: #fff !important;
            box-shadow: 0 0 20px #039126 !important;
            border-color: #fff !important;
        }

        /* Saldo */
        .wallet-box {
            border: 1px dashed #555;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            background: rgba(255,255,255,0.05);
            max-width: 400px;
            margin-left: auto; margin-right: auto;
        }
        .wallet-val { font-size: 1.8rem; font-weight: bold; text-shadow: 0 0 5px; }
        
        label { display: block; color: #ccc; margin-bottom: 8px; font-size: 0.9rem; font-weight: bold; }
        .btn-group-center { display: flex; flex-direction: column; gap: 10px; max-width: 400px; margin: 20px auto 0 auto; }
        
        .footer-market {
             text-align:center; margin-top: 50px; color: #888; border-top: 1px solid var(--primary); padding-top: 20px; font-size: 0.8rem;
             background: rgba(0,0,20,0.8);
             padding-bottom: 20px;
             border-radius: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        
        <div class="listing-header-centered" style="margin-bottom:40px; text-align: center; margin-top: 30px;">
            <h1 style="font-size: 3rem; color:var(--primary); text-shadow:0 0 15px var(--primary); margin-bottom: 20px; border: none;">
                MERCADO MAVILLA
            </h1>
            <a href="../dashboard.php">
                <button style="width: auto; padding: 10px 40px !important;">Menu Principal</button>
            </a>
        </div>

        <?php if (isset($_SESSION['mensagem']) && !empty($_SESSION['mensagem'])): 
            $msg = $_SESSION['mensagem'];
            $borderColor = '#ffd700'; $textColor = '#ffd700';
            if (stripos($msg, 'erro') !== false || stripos($msg, 'inválido') !== false || stripos($msg, 'não') !== false) {
                $borderColor = '#ff2222'; $textColor = '#ff2222';
            } 
            elseif (stripos($msg, 'sucesso') !== false || stripos($msg, 'enviado') !== false || stripos($msg, 'realizada') !== false) {
                $borderColor = '#039126'; $textColor = '#039126';
            }
        ?>
            <div class="neon-card" style="border-color: <?= $borderColor ?>; color: <?= $textColor ?>; padding: 15px; margin-bottom: 20px; box-shadow: 0 0 10px <?= $borderColor ?>;">
                <?= $msg ?>
            </div>
            <?php unset($_SESSION['mensagem']); ?>
        <?php endif; ?>

        <div class="market-stack">

            <div class="neon-card">
                <h3>Gráfico de Preços (NFT)</h3>
                <div style="padding: 10px; background: rgba(0,0,0,0.5); border-radius: 8px;">
                    <?php include('../grafico.php'); ?>
                </div>
                <a href="../graficow.php"><button style="margin-top:20px;">Analisar Gráfico Detalhado</button></a>
            </div>
            
            <div class="neon-card">
                <h3>Minha Carteira</h3>
                
                <div class="wallet-box">
                    <p style="color:#aaa; margin:0; text-transform: uppercase; font-size: 0.8rem;">Saldo em Dinheiro</p>
                    <div class="wallet-val" style="color: <?= $cor_saldo_carteira ?>">R$ <?= $saldo_carteira ?></div>
                </div>

                <div class="wallet-box">
                    <p style="color:#aaa; margin:0; text-transform: uppercase; font-size: 0.8rem;">Total de Fichas</p>
                    <div class="wallet-val" style="color: #00f3ff"><?= $totalFichas ?></div>
                </div>

                <h4 style="margin-top: 30px; color: var(--primary); text-transform: uppercase; border-bottom: 1px dashed var(--primary); padding-bottom: 10px; display: inline-block;">Enviar Dinheiro</h4>
                <form action="envio.php" method="post" style="margin-top: 20px;">
                    <input type="text" name="destinatario" placeholder="Destinatário" required>
                    <input type="text" id="moneyInput" name="valor" placeholder="Valor (R$)" required>
                    <input type="password" name="pin" placeholder="PIN (4 dígitos)" maxlength="4" required>
                    <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                    
                    <button type="submit" class="btn-money" style="margin-top: 10px;">Enviar Pagamento</button>
                </form>
                <a href="../recibos.php"><button type="button" style="background: transparent !important; border: 1px solid #555 !important; margin-top:15px; color:#aaa !important;">Ver Histórico de Recibos</button></a>
            </div>

            <div class="neon-card">
                <h3>Vender Personagem</h3>
                
                <?php if (count($personagens) === 0): ?>
                    <div style="padding:20px; color:#ccc; font-style: italic;">
                        Você não possui personagens disponíveis para venda no momento.
                    </div>
                <?php else: ?>
                    <form action="venderpersonagem.php" method="POST">
                        <label>Selecione o Personagem:</label>
                        <select name="personagem" required style="cursor:pointer;">
                            <option value="" disabled selected>Selecione...</option>
                            <?php foreach ($personagens as $p): ?>
                                <option value="<?= intval($p['id']) ?>"><?= htmlspecialchars($p['personagem']) ?></option>
                            <?php endforeach; ?>
                        </select>

                        <label>Valor de Venda (R$):</label>
                        <input type="text" id="moneyInput2" name="valor" placeholder="0.00" required>

                        <label>PIN de Segurança:</label>
                        <input type="password" placeholder="****" name="pin" maxlength="4" required>

                        <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                        
                        <button type="submit" name="vender" class="btn-money" onclick="return confirm('Confirmar venda?')" style="margin-top: 15px;">💲 COLOCAR À VENDA 💲</button>
                    </form>
                <?php endif; ?>
                <a href="ordens_venda.php"><button type="button" style="margin-top:15px;">Ver Personagens à Venda</button></a>
            </div>

            <div class="neon-card">
                <h3>Criar Ordem de Compra</h3>
                <p style="color:#ccc; font-size:0.9rem; margin-bottom:20px;">Deseja comprar NFT/s? Crie uma ordem de compra.</p>
                
                <form action="criarordemcompra.php" method="POST">
                    <label>Quantidade de NFT's:</label>
                    <input type="number" name="quantidade" placeholder="Quantidade" id="quantidade" required>
                    
                    <label>Valor Unitário Oferecido (R$):</label>
                    <input type="text" id="moneyInput3" name="valor" placeholder="0.00" required>
                    
                    <label>PIN:</label>
                    <input type="password" placeholder="****" name="pin" maxlength="4" required>

                    <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                    <input type="hidden" name="userwallet" value="<?= $wallet ?>">
                    <input type="hidden" name="user_id" value="<?= $user_id ?>">
                    <input type="hidden" name="dataehora" value="<?= date('Y-m-d H:i:s') ?>">
                    
                    <button type="submit" name="criarOrdem" class="btn-money" style="margin-top: 15px;">💲 CRIAR ORDEM DE COMPRA 💲</button>
                </form>
                <a href="ordenscompra.php"><button type="button" style="margin-top:15px;">Ver Ordens Existentes</button></a>
            </div>

            <div class="neon-card">
                <h3>Gerenciar Fichas</h3>
                
                <a href="../fichas/vender_fichas.php"><button class="btn-money" style="margin-bottom:15px;">💲 VENDER FICHAS 💲</button></a>
                
                <a href="../fichas/listavendadefichas.php"><button>Ver Lista de Vendas</button></a>
            </div>

        </div>

        <div class="footer-market">
            ⚔️ RPG ERA MEDIEVAL: FERRO & FOGO ⚔️<br>
            &copy; <?php echo date("Y"); ?> Todos os direitos reservados.
        </div>

    </div>

    <script>
        function setupFormatter(id) {
            const input = document.getElementById(id);
            if(input) {
                input.addEventListener('input', function() {
                    let rawValue = this.value.replace(/\D/g, '');
                    if(rawValue === "") { this.value = ""; return; }
                    let formatted = (Number(rawValue) / 100).toFixed(2);
                    this.value = formatted;
                });
            }
        }
        setupFormatter('moneyInput');
        setupFormatter('moneyInput2');
        setupFormatter('moneyInput3');
    </script>

</body>
</html>