<?php
// ==========================================================
// ARQUIVO: char_bazaar.php (Bazar de Personagens)
// ==========================================================
session_start();
$page_title = "Pokemon Relics - Bazar de Personagens";

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

// VERIFICAÇÃO DE LOGIN
if (!isset($_SESSION['account_id'])) {
 echo "
    <div class='container my-5 text-center' style='padding-top: 100px;'>
        <div class='card bg-dark text-white border-secondary p-5 shadow-lg'>
            <i class='fas fa-lock fa-4x text-warning mb-3'></i>
            <h2>Acesso Restrito</h2>
            <p class='text-white-50'>Você precisa estar logado para acessar o Bazar de Personagens.</p>
            <a href='login.php' class='btn btn-primary fw-bold mt-2'><i class='fas fa-sign-in-alt me-2'></i>Fazer Login</a>
        </div>
    </div>";
include 'includes/footer.php';
exit;
}

$accountID = $_SESSION['account_id'];

// --- CARREGAR DADOS ---

// 1. Pontos (PPS) do Usuário Logado
$stmt = $pdo->prepare("SELECT post_points FROM accounts WHERE id = ?");
$stmt->execute([$accountID]);
$myPoints = $stmt->fetchColumn();

// 2. Personagens do Usuário Logado (Disponíveis para Venda/Cancelamento)
// Seleciona personagens do usuário que NÃO estão listados no bazar
$myCharsStmt = $pdo->prepare("
    SELECT p.id, p.name, p.level 
    FROM players p
    LEFT JOIN char_bazaar cb ON p.id = cb.player_id AND cb.status = 'listed'
    WHERE p.account_id = ? AND cb.player_id IS NULL 
    ORDER BY p.level DESC
");
$myCharsStmt->execute([$accountID]);
$myAvailableChars = $myCharsStmt->fetchAll(PDO::FETCH_ASSOC);

// 3. Personagens Atualmente Listados (em Venda)
$listedCharsStmt = $pdo->prepare("
    SELECT cb.id as bazaar_id, p.id as player_id, p.name, p.level, cb.price_points, cb.account_id as seller_account_id
    FROM char_bazaar cb
    JOIN players p ON cb.player_id = p.id
    WHERE cb.status = 'listed'
    ORDER BY cb.listing_time DESC
");
$listedCharsStmt->execute();
$listedChars = $listedCharsStmt->fetchAll(PDO::FETCH_ASSOC);

// 4. Personagens que o usuário logado tem para venda
$myListedCharsStmt = $pdo->prepare("
    SELECT cb.id as bazaar_id, p.name, p.level, cb.price_points
    FROM char_bazaar cb
    JOIN players p ON cb.player_id = p.id
    WHERE cb.status = 'listed' AND cb.account_id = ?
    ORDER BY cb.listing_time DESC
");
$myListedCharsStmt->execute([$accountID]);
$myListedChars = $myListedCharsStmt->fetchAll(PDO::FETCH_ASSOC);

?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<style>
    /* Estilos Dark Theme Base */
    body { background-color: #0f172a; color: #f8fafc; }
    .bazaar-hero {
        background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
        padding: 50px 0;
        border-bottom: 1px solid rgba(255,255,255,0.05);
        margin-top: -20px;
        box-shadow: 0 10px 30px -10px rgba(0,0,0,0.5);
    }
    .bazaar-card {
        background: #1e293b;
        border: 1px solid rgba(255,255,255,0.1);
        border-radius: 16px;
        padding: 25px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        height: 100%;
    }
    /* Estilos de Item */
    .char-item {
        background: #0f172a;
        border: 2px solid #334155;
        border-radius: 12px;
        padding: 15px;
        transition: all 0.2s;
        cursor: pointer;
    }
    .char-item:hover {
        border-color: #3b82f6;
        transform: translateY(-2px);
        box-shadow: 0 5px 20px rgba(59, 130, 246, 0.2);
    }
    .char-price {
        font-size: 1.5rem;
        font-weight: 700;
        color: #f59e0b; /* Amarelo/Warning */
    }
    .btn-buy {
        background: linear-gradient(135deg, #10b981, #059669);
        border: none;
        color: white;
        font-weight: 700;
        transition: all 0.2s;
    }
    .btn-buy:hover {
        background: linear-gradient(135deg, #059669, #047857);
    }
    /* Modal Personalizado */
    .modal-dark .modal-content { 
        background-color: #0f172a; 
        color: #fff; 
        border: 1px solid #3b82f6; 
    }
    .modal-dark .modal-header { 
        border-bottom: 1px solid rgba(255,255,255,0.1); 
    }
    .modal-dark .modal-footer { 
        border-top: 1px solid rgba(255,255,255,0.1); 
    }
</style>

<div class="bazaar-hero text-center">
    <div class="container">
        <h1 class="display-4 fw-bold text-white mb-3" style="letter-spacing: 1px;">BAZAR DE PERSONAGENS</h1>
        <p class="text-white-50 fs-5 mb-5 max-w-600 mx-auto">Compre e venda personagens de jogadores usando seus Post Points (PPS).</p>
        
        <div class="d-inline-flex align-items-center gap-3 bg-dark bg-opacity-50 px-4 py-3 rounded-pill border border-primary border-opacity-25 shadow-sm">
            <div class="d-flex align-items-center me-3">
                <span class="text-white-50 me-2">Seus PPS:</span>
                <span class="text-warning fw-bold fs-4" id="displayPoints">
                    <i class="fas fa-coins me-1"></i><?php echo number_format($myPoints, 0, ',', '.'); ?>
                </span>
            </div>
            <button class="btn btn-primary rounded-pill fw-bold px-4 hover-lift shadow-sm" data-bs-toggle="modal" data-bs-target="#sellModal">
                <i class="fas fa-hand-holding-usd me-2"></i>Vender Personagem
            </button>
        </div>
    </div>
</div>

<div class="container my-5 pb-5">
    <div class="row g-5">
        
        <div class="col-lg-8">
            <h2 class="fw-bold text-white mb-4 border-bottom border-secondary pb-2">
                <i class="fas fa-store me-2 text-info"></i> Personagens à Venda
            </h2>

            <div id="listingArea" class="row g-3">
                <?php if (empty($listedChars)): ?>
                    <div class="col-12 text-center py-5">
                        <i class="fas fa-search-minus fa-5x text-white-50 mb-3"></i>
                        <h4 class="text-white-50">Nenhum personagem listado no momento.</h4>
                        <p class="text-white-50">Seja o primeiro a listar o seu!</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($listedChars as $char): ?>
                        <?php 
                            // Verifica se o personagem é do próprio usuário (não pode comprar o próprio)
                            $isMyChar = ($char['seller_account_id'] == $accountID);
                        ?>
                        <div class="col-md-6 col-lg-4">
                            <div class="char-item" 
                                data-char-id="<?php echo $char['player_id']; ?>" 
                                data-bazaar-id="<?php echo $char['bazaar_id']; ?>" 
                                data-name="<?php echo htmlspecialchars($char['name']); ?>" 
                                data-level="<?php echo $char['level']; ?>" 
                                data-price="<?php echo $char['price_points']; ?>" 
                                onclick="openBuyModal(this)">
                                
                                <h5 class="fw-bold text-truncate text-primary"><?php echo htmlspecialchars($char['name']); ?></h5>
                                <p class="text-white-50 mb-2">Level: <span class="fw-bold text-warning"><?php echo $char['level']; ?></span></p>
                                
                                <div class="text-center py-3">
                                    <i class="fas fa-user-circle fa-5x mb-2 text-secondary"></i>
                                </div>

                                <div class="d-flex justify-content-between align-items-center mt-3">
                                    <span class="char-price"><i class="fas fa-coins me-1"></i><?php echo number_format($char['price_points'], 0, ',', '.'); ?></span>
                                    
                                    <?php if ($isMyChar): ?>
                                        <button class="btn btn-sm btn-danger disabled" title="Seu Personagem" disabled>SEU</button>
                                    <?php else: ?>
                                        <button class="btn btn-sm btn-buy buy-btn">Comprar</button>
                                    <?php endif; ?>
                                </div>
                                
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="bazaar-card">
                <h4 class="fw-bold text-white border-bottom border-secondary pb-3 mb-4 d-flex align-items-center">
                    <i class="fas fa-tag text-success me-3 fa-lg"></i> Meus Personagens à Venda
                </h4>
                
                <?php if(empty($myListedChars)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-box-open fa-3x text-white-50 mb-3"></i>
                        <p class="text-white-50 fw-bold">Você não tem personagens listados.</p>
                        <button class="btn btn-sm btn-outline-primary mt-2" data-bs-toggle="modal" data-bs-target="#sellModal">Listar agora</button>
                    </div>
                <?php else: ?>
                    <div class="d-flex flex-column gap-3">
                        <?php foreach($myListedChars as $char): ?>
                            <div class="d-flex align-items-center p-3 rounded border border-info bg-dark shadow-sm">
                                <div class="flex-grow-1 overflow-hidden">
                                    <div class="text-white fw-bold text-truncate"><?php echo htmlspecialchars($char['name']); ?> (Lvl <?php echo $char['level']; ?>)</div>
                                    <div class="text-warning small"><i class="fas fa-coins me-1"></i><?php echo number_format($char['price_points'], 0, ',', '.'); ?> PPS</div>
                                </div>
                                <button class="btn btn-danger btn-sm ms-3" onclick="confirmCancel(<?php echo $char['bazaar_id']; ?>, '<?php echo htmlspecialchars($char['name']); ?>')">
                                    <i class="fas fa-times-circle me-1"></i> Cancelar
                                </button>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

    </div>
</div>

<div class="modal fade" id="sellModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-dark">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-white"><i class="fas fa-hand-holding-usd me-2"></i> Listar Personagem para Venda</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="sellForm">
                    <input type="hidden" name="action" value="list_char">
                    <div class="mb-3">
                        <label for="charToSell" class="form-label text-white-50">Selecione o Personagem:</label>
                        <?php if (empty($myAvailableChars)): ?>
                            <div class="alert alert-warning">Nenhum personagem disponível para venda.</div>
                            <select id="charToSell" class="form-select" disabled>
                                <option>Nenhum personagem disponível</option>
                            </select>
                        <?php else: ?>
                            <select id="charToSell" name="player_id" class="form-select bg-dark text-white border-secondary">
                                <?php foreach($myAvailableChars as $char): ?>
                                    <option value="<?php echo $char['id']; ?>"><?php echo htmlspecialchars($char['name']); ?> (Lvl <?php echo $char['level']; ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        <?php endif; ?>
                    </div>
                    <div class="mb-3">
                        <label for="pricePoints" class="form-label text-white-50">Preço em PPS:</label>
                        <input type="number" id="pricePoints" name="price_points" class="form-control bg-dark text-white border-secondary" min="10" required placeholder="Mínimo de 10 PPS">
                    </div>
                    <div id="sellMessage" class="mt-3"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button>
                <button type="submit" form="sellForm" class="btn btn-primary" id="listCharBtn" <?php echo empty($myAvailableChars) ? 'disabled' : ''; ?>><i class="fas fa-tag me-2"></i>Listar Personagem</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="buyModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-dark">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-white"><i class="fas fa-shopping-cart me-2"></i> Comprar Personagem</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-4">
                    <i class="fas fa-user-tag fa-4x text-info mb-3"></i>
                    <h4 class="text-white" id="buyCharName"></h4>
                    <p class="text-white-50">Nível: <span class="fw-bold" id="buyCharLevel"></span></p>
                </div>
                
                <div class="alert alert-info bg-info bg-opacity-10 border-info text-white text-center">
                    Custo total: <span class="char-price fs-3" id="buyCharPrice"></span>
                </div>
                
                <p class="text-white-50 small mt-3">Ao confirmar, os PPS serão deduzidos da sua conta e o personagem será transferido imediatamente.</p>
                
                <form id="buyForm">
                    <input type="hidden" name="action" value="buy_char">
                    <input type="hidden" name="bazaar_id" id="buyBazaarId">
                    <div id="buyMessage" class="mt-3"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="submit" form="buyForm" class="btn btn-buy" id="confirmBuyBtn"><i class="fas fa-check me-2"></i>Confirmar Compra</button>
            </div>
        </div>
    </div>
</div>

<script>
    // Armazena os pontos atuais do usuário (para checagem rápida no frontend)
    const MY_POINTS = <?php echo $myPoints; ?>;

    function openBuyModal(element) {
        const charName = element.dataset.name;
        const charLevel = element.dataset.level;
        const charPrice = parseInt(element.dataset.price);
        const bazaarId = element.dataset.bazaarId;

        document.getElementById('buyCharName').textContent = charName;
        document.getElementById('buyCharLevel').textContent = charLevel;
        document.getElementById('buyCharPrice').innerHTML = `<i class="fas fa-coins me-1"></i>${charPrice.toLocaleString('pt-BR')} PPS`;
        document.getElementById('buyBazaarId').value = bazaarId;
        document.getElementById('buyMessage').innerHTML = '';

        const confirmBuyBtn = document.getElementById('confirmBuyBtn');
        const pointsDisplay = document.getElementById('displayPoints').textContent.replace(/[^\d]/g, '');
        const currentPoints = parseInt(pointsDisplay);

        if (currentPoints < charPrice) {
            confirmBuyBtn.disabled = true;
            confirmBuyBtn.textContent = 'PPS Insuficientes';
            document.getElementById('buyMessage').innerHTML = `<div class="alert alert-danger">Seus ${currentPoints.toLocaleString('pt-BR')} PPS não são suficientes.</div>`;
        } else {
            confirmBuyBtn.disabled = false;
            confirmBuyBtn.textContent = 'Confirmar Compra';
        }

        const buyModal = new bootstrap.Modal(document.getElementById('buyModal'));
        buyModal.show();
    }

    function confirmCancel(bazaarId, charName) {
        if (confirm(`Tem certeza que deseja cancelar a venda do personagem ${charName}? O item será removido do bazar.`)) {
            processBazaarAction('cancel_char', { bazaar_id: bazaarId });
        }
    }

    // Função central para enviar formulários de venda, compra e cancelamento
    async function processBazaarAction(action, data) {
        let formBody = new FormData();
        formBody.append('action', action);
        for (const key in data) {
            formBody.append(key, data[key]);
        }

        let msgElement;
        let buttonElement;

        if (action === 'list_char') {
            msgElement = document.getElementById('sellMessage');
            buttonElement = document.getElementById('listCharBtn');
        } else if (action === 'buy_char') {
            msgElement = document.getElementById('buyMessage');
            buttonElement = document.getElementById('confirmBuyBtn');
        } else if (action === 'cancel_char') {
            msgElement = document.getElementById('msgArea') || document.createElement('div');
            // Não há botão específico, apenas um feedback geral
        }
        
        if(buttonElement) {
             buttonElement.disabled = true;
             buttonElement.innerHTML = '<i class="fas fa-sync fa-spin me-2"></i>Processando...';
        }

        msgElement.innerHTML = ''; // Limpa mensagens anteriores

        try {
            const response = await fetch('api/bazaar_action.php', {
                method: 'POST',
                body: formBody // Usando FormData para simular POST tradicional
            });

            const result = await response.json();

            if (result.success) {
                // Sucesso na transação
                msgElement.innerHTML = `<div class="alert alert-success">${result.message}</div>`;
                
                // Atualiza pontos e recarrega a página após um breve delay
                setTimeout(() => { window.location.reload(); }, 1500);

            } else {
                // Falha na transação
                msgElement.innerHTML = `<div class="alert alert-danger">${result.error}</div>`;
            }

        } catch (error) {
            console.error('Erro de Fetch:', error);
            msgElement.innerHTML = `<div class="alert alert-danger">Erro de comunicação com o servidor. Tente novamente.</div>`;
        } finally {
             if(buttonElement && action !== 'cancel_char') {
                buttonElement.disabled = false;
                // Restaura o texto original do botão (simplificado, recarregar é melhor)
                if (action === 'list_char') buttonElement.innerHTML = '<i class="fas fa-tag me-2"></i>Listar Personagem';
                if (action === 'buy_char') buttonElement.innerHTML = '<i class="fas fa-check me-2"></i>Confirmar Compra';
            }
        }
    }

    // Listener para o formulário de Venda
    document.getElementById('sellForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const charId = document.getElementById('charToSell').value;
        const price = document.getElementById('pricePoints').value;
        if (charId && price >= 10) {
            processBazaarAction('list_char', { 
                player_id: charId, 
                price_points: price 
            });
        }
    });

    // Listener para o formulário de Compra
    document.getElementById('buyForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const bazaarId = document.getElementById('buyBazaarId').value;
        if (bazaarId) {
            processBazaarAction('buy_char', { bazaar_id: bazaarId });
        }
    });

    // Inicializa Tooltips (se necessário, mas não usados neste layout final)
    // document.addEventListener('DOMContentLoaded', function () {
    //     const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    //     [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
    // });
</script>

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