<?php
// === ATIVA MODO DE DEBUG ===
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require 'conexao.php';

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

// --- CONFIGURAÇÕES ---
$itensPorPagina = 50; 
$paginaAtual = isset($_GET['pagina']) ? max(1, intval($_GET['pagina'])) : 1;
$busca = trim($_GET['busca'] ?? '');

// Filtros
$filtros_padrao = ['FINANCEIRO', 'VENDA', 'MOVIMENTO', 'EMISSAO', 'NASCIMENTO', 'TRANSFORMACAO', 'SISTEMA'];
$tipos_selecionados = isset($_GET['tipos']) ? $_GET['tipos'] : $filtros_padrao;

// --- ESTATÍSTICAS ---
try {
    $total_personagens = $pdo->query("SELECT COUNT(*) FROM personagens")->fetchColumn();
    $total_fichas = $pdo->query("SELECT COUNT(*) FROM fichaspersonagens")->fetchColumn();
    $total_txs = $pdo->query("SELECT COUNT(*) FROM mempool")->fetchColumn(); 
} catch (Exception $e) {
    $total_personagens = 0; $total_fichas = 0; $total_txs = 0;
}

// --- QUERY SQL ---
$sql_base = "
SELECT * FROM (

    SELECT 
        'FINANCEIRO' as tipo,
        m.id as id_reg,
        m.dataehora as data_evento,
        m.remetente as wallet_from, 
        m.destinatario as wallet_to, 
        m.valor as val_num,
        m.hash as tx_hash,
        NULL as item_nome,
        NULL as item_id,
        m.link as item_link,   
        m.referencia as info_extra,
        NULL as mediacao,
        'BRL' as asset_type
    FROM mempool m

    UNION ALL

    SELECT 
        'VENDA' as tipo,
        v.id as id_reg,
        v.dataehora as data_evento,
        u1.wallet as wallet_from,
        u2.wallet as wallet_to,
        v.preco as val_num,
        CONCAT('MKT-', v.id) as tx_hash,
        v.referencia as item_nome, 
        NULL as item_id,
        NULL as item_link,
        CONCAT('Ref Ordem: ', v.referencia) as info_extra,
        v.mediacao as mediacao,
        'NFT_SALE' as asset_type
    FROM vendas v
    LEFT JOIN usersblock u1 ON v.vendedor = u1.user
    LEFT JOIN usersblock u2 ON v.comprador = u2.user

    UNION ALL

    SELECT
        'MOVIMENTO' as tipo,
        m.id as id_reg,
        m.data as data_evento,
        u1.wallet as wallet_from,
        m.destino as wallet_to,
        0 as val_num,
        CONCAT('MOV-', m.id) as tx_hash,
        NULL as item_nome, 
        m.personagem as item_id,
        NULL as item_link,
        CONCAT('De: ', m.origem, ' Para: ', m.destino) as info_extra,
        NULL as mediacao,
        'CHAR_MOVE' as asset_type
    FROM movpersonagens m
    LEFT JOIN usersblock u1 ON m.jogador = u1.user

    UNION ALL

    SELECT
        'EMISSAO' as tipo,
        f.id as id_reg,
        f.data as data_evento,
        u_admin.wallet as wallet_from, 
        u_dest.wallet as wallet_to,    
        1 as val_num,
        f.hash as tx_hash,
        'Ficha Personagem' as item_nome,
        f.id as item_id,
        f.link as item_link,   
        f.descricao as info_extra,
        f.responsavel as mediacao, 
        'ASSET_MINT' as asset_type
    FROM fichaspersonagens f
    LEFT JOIN usersblock u_admin ON f.responsavel = u_admin.user
    LEFT JOIN usersblock u_dest ON f.jogador = u_dest.user

    UNION ALL

    SELECT
        'NASCIMENTO' as tipo,
        p.id as id_reg,
        p.datacriacao as data_evento,
        'GENESIS_BLOCK_SYSTEM' as wallet_from,
        p.personagem as wallet_to, 
        1 as val_num,
        CONCAT('CHAR-', p.id) as tx_hash,
        p.personagem as item_nome,
        p.id as item_id,
        NULL as item_link,
        CONCAT('Classe: ', p.cla) as info_extra,
        NULL as mediacao,
        'CHAR_MINT' as asset_type
    FROM personagens p

    UNION ALL

    SELECT 
        CASE 
            WHEN i.informacao LIKE '%Transformação%' THEN 'TRANSFORMACAO'
            WHEN i.informacao LIKE '%Transferencia%' THEN 'TRANSFERENCIA'
            ELSE 'SISTEMA'
        END as tipo,
        i.id as id_reg,
        i.dataehora as data_evento,
        COALESCE(u1.wallet, 'SYSTEM') as wallet_from,
        COALESCE(u2.wallet, i.p2) as wallet_to,
        0 as val_num,
        i.origem as tx_hash, 
        NULL as item_nome,
        NULL as item_id,
        NULL as item_link,
        i.informacao as info_extra,
        NULL as mediacao,
        'LOG_EVENT' as asset_type
    FROM infossistema i
    LEFT JOIN usersblock u1 ON i.p1 = u1.user
    LEFT JOIN usersblock u2 ON i.p2 = u2.user
    WHERE 
      -- FILTRAGEM AGRESSIVA PARA EVITAR DUPLICIDADE VISUAL
      i.informacao NOT LIKE '%ADMIN MINT:%' 
      AND i.informacao NOT LIKE '%Venda:%'        -- Remove Venda Padrão
      AND i.informacao NOT LIKE '%Venda Auto:%'   -- Remove Venda Automática (Log duplicado)
      AND i.informacao NOT LIKE '%Gerada sistema%'

) AS ledger WHERE 1=1
";

$params = [];

if (!empty($busca)) {
    $sql_base .= " AND (wallet_from LIKE :busca OR wallet_to LIKE :busca OR tx_hash LIKE :busca OR info_extra LIKE :busca)";
    $params[':busca'] = "%$busca%";
}

if (!empty($tipos_selecionados)) {
    $placeholders = [];
    foreach ($tipos_selecionados as $k => $t) {
        $ph = ":tipo_$k";
        $placeholders[] = $ph;
        $params[$ph] = $t;
    }
    $sql_base .= " AND tipo IN (" . implode(',', $placeholders) . ")";
} else {
    $sql_base .= " AND 1=0"; 
}

// Executa Query
try {
    $sql_count = "SELECT COUNT(*) FROM ($sql_base) AS total";
    $stmtCount = $pdo->prepare($sql_count);
    $stmtCount->execute($params);
    $totalRegistros = $stmtCount->fetchColumn();
    $totalPaginas = ceil($totalRegistros / $itensPorPagina);
    $offset = ($paginaAtual - 1) * $itensPorPagina;

    $sql_final = $sql_base . " ORDER BY data_evento DESC LIMIT :limit OFFSET :offset";
    $stmt = $pdo->prepare($sql_final);
    foreach ($params as $k => $v) { $stmt->bindValue($k, $v); }
    $stmt->bindValue(':limit', $itensPorPagina, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $registros_brutos = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch(PDOException $e) {
    die("<div style='color:red;'>ERRO SQL: " . $e->getMessage() . "</div>");
}

// === PÓS-PROCESSAMENTO (AGRUPAMENTO E CORREÇÃO DE TIPO) ===
$registros_finais = [];
$referencias_processadas = [];

foreach ($registros_brutos as $row) {
    
    // CORREÇÃO VISUAL:
    // Se for FINANCEIRO mas a descrição diz "Venda", transforme visualmente em VENDA.
    // Isso resolve o problema da linha verde que deveria ser amarela.
    if ($row['tipo'] == 'FINANCEIRO' && (stripos($row['info_extra'], 'Venda') !== false)) {
        $row['tipo'] = 'VENDA (AUTO)'; // Novo Título
        $row['asset_type'] = 'INSTANT_SALE';
        // Opcional: extrair o nome do item da string se necessário, mas a descrição já ajuda
    }

    // LÓGICA DE AGRUPAMENTO (Mantida para outros casos)
    $ref_code = null;
    if (preg_match('/(AUTO-\d+|ORD-\d+)/', $row['info_extra'], $matches)) {
        $ref_code = $matches[1];
    }

    if ($ref_code && isset($referencias_processadas[$ref_code])) {
        $index = $referencias_processadas[$ref_code];
        
        // Fusão de dados
        if (strpos($row['tipo'], 'VENDA') !== false && $registros_finais[$index]['tipo'] == 'FINANCEIRO') {
            $registros_finais[$index]['tipo'] = $row['tipo']; 
            $registros_finais[$index]['asset_type'] = 'NFT_SALE_COMPLETE';
            $registros_finais[$index]['item_nome'] = $row['item_nome'];
            $registros_finais[$index]['mediacao'] = $row['mediacao'];
            $registros_finais[$index]['tx_hash_secundario'] = $row['tx_hash'];
        }
        elseif ($row['tipo'] == 'FINANCEIRO' && strpos($registros_finais[$index]['tipo'], 'VENDA') !== false) {
            $registros_finais[$index]['item_link'] = $row['item_link']; 
            $registros_finais[$index]['tx_hash_financeiro'] = $row['tx_hash'];
            $registros_finais[$index]['asset_type'] = 'NFT_SALE_COMPLETE';
        }
        continue;
    }

    $registros_finais[] = $row;
    if ($ref_code) {
        $referencias_processadas[$ref_code] = array_key_last($registros_finais);
    }
}

// --- FUNÇÕES AUXILIARES ---
function linkPagina($pag) {
    $q = $_GET; $q['pagina'] = $pag;
    return '?' . http_build_query($q);
}

function isChecked($val, $arr) {
    if(!is_array($arr)) return '';
    return in_array($val, $arr) ? 'checked' : '';
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Mavilla Ledger - Auditoria</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@300;400;600&family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <style>
        :root { --bg: #050505; --panel: #0e0e0e; --border: #222; --accent: #00f3ff; --text: #ddd; }
        * { box-sizing: border-box; }
        body { background: var(--bg); color: var(--text); font-family: 'Inter', sans-serif; margin: 0; font-size: 12px; }
        a { text-decoration: none; color: inherit; }

        .header { background: #000; border-bottom: 1px solid var(--border); padding: 15px 20px; display: flex; justify-content: space-between; align-items: center; }
        .logo { font-family: 'Fira Code', monospace; font-weight: 700; color: #fff; font-size: 1.1rem; }
        .logo span { color: var(--accent); }
        .stats { display: flex; gap: 15px; font-family: 'Fira Code', monospace; color: #666; }
        .stats b { color: #fff; }

        .filters { background: var(--panel); padding: 15px; margin: 20px; border: 1px solid var(--border); border-radius: 6px; }
        .search-box { width: 100%; background: #000; border: 1px solid #333; color: #fff; padding: 10px; font-family: 'Fira Code', monospace; margin-bottom: 10px; }
        .search-box:focus { border-color: var(--accent); outline: none; }
        .checks { display: flex; gap: 15px; flex-wrap: wrap; margin-top: 10px; border-top: 1px solid #222; padding-top: 10px; }
        .chk-lbl { display: flex; align-items: center; gap: 5px; color: #888; cursor: pointer; text-transform: uppercase; font-weight: bold; font-size: 0.7rem; }
        .chk-lbl:hover { color: #fff; }
        .btn-go { background: var(--accent); color: #000; border: none; padding: 0 20px; font-weight: bold; cursor: pointer; margin-left: auto; display: block; height: 38px; }

        .table-wrap { overflow-x: auto; margin: 0 20px 50px 20px; border: 1px solid var(--border); background: #080808; }
        table { width: 100%; border-collapse: collapse; min-width: 1000px; }
        th { background: #111; color: #555; text-align: left; padding: 12px; font-size: 0.7rem; text-transform: uppercase; border-bottom: 2px solid #222; }
        td { padding: 12px; border-bottom: 1px solid #1a1a1a; vertical-align: top; color: #ccc; }
        tr:hover td { background: #111; }

        .c-type { width: 100px; }
        .c-date { width: 130px; font-family: 'Fira Code', monospace; color: #666; font-size: 0.7rem; }
        .c-wallets { width: 250px; font-family: 'Fira Code', monospace; font-size: 0.75rem; }
        .c-hash { width: 150px; font-family: 'Fira Code', monospace; font-size: 0.7rem; color: #00f3ff; word-break: break-all; }
        
        .payload-box {
            background: #000; border: 1px solid #222; padding: 8px; border-radius: 4px;
            font-family: 'Fira Code', monospace; font-size: 0.7rem; color: #aaa;
            white-space: pre-wrap; word-break: break-all;
        }
        .key { color: #555; font-weight: bold; }
        .val { color: #ddd; }
        .lnk { color: var(--accent); text-decoration: underline; cursor: pointer;}
        .hash-tag { color: #28a745; font-size: 0.65rem; display:block; margin-top:3px; word-break:break-all;}

        .badge { padding: 3px 6px; border-radius: 3px; font-size: 0.6rem; font-weight: 800; text-transform: uppercase; display: inline-block; width: 100%; text-align: center; }
        .b-fin { border: 1px solid #28a745; color: #28a745; }
        .b-ven { border: 1px solid #ffc107; color: #ffc107; }
        .b-min { border: 1px solid #00f3ff; color: #00f3ff; }
        .b-mov { border: 1px solid #6f42c1; color: #6f42c1; }
        .b-tra { border: 1px solid #e83e8c; color: #e83e8c; }
        .b-sys { border: 1px solid #fff; color: #fff; }

        .pagination { display: flex; justify-content: center; gap: 5px; margin-bottom: 50px; }
        .pg { padding: 5px 10px; border: 1px solid #333; color: #666; }
        .pg.active { background: var(--accent); color: #000; border-color: var(--accent); }
    </style>
</head>
<body>

    <div class="header">
        <div class="logo">MAVILLA <span>AUDIT</span></div>
        <div class="stats">
            <span>Chars: <b><?= $total_personagens ?></b></span>
            <span>Assets: <b><?= $total_fichas ?></b></span>
            <span>Txs: <b><?= $total_txs ?></b></span>
        </div>
        <a href="dashboard.php" style="color:#fff; border:1px solid #333; padding:5px 10px;">VOLTAR</a>
    </div>

    <form class="filters">
        <div style="display:flex; gap:10px;">
            <input name="busca" class="search-box" placeholder="Pesquisar HASH, WALLET, ID, NOME, LINK..." value="<?= htmlspecialchars($busca) ?>">
            <button class="btn-go">FILTRAR</button>
        </div>
        <div class="checks">
            <label class="chk-lbl"><input type="checkbox" name="tipos[]" value="FINANCEIRO" <?= isChecked('FINANCEIRO', $tipos_selecionados) ?>> Financeiro</label>
            <label class="chk-lbl"><input type="checkbox" name="tipos[]" value="VENDA" <?= isChecked('VENDA', $tipos_selecionados) ?>> Vendas</label>
            <label class="chk-lbl"><input type="checkbox" name="tipos[]" value="EMISSAO" <?= isChecked('EMISSAO', $tipos_selecionados) ?>> Emissões</label>
            <label class="chk-lbl"><input type="checkbox" name="tipos[]" value="MOVIMENTO" <?= isChecked('MOVIMENTO', $tipos_selecionados) ?>> Movimento</label>
            <label class="chk-lbl"><input type="checkbox" name="tipos[]" value="TRANSFORMACAO" <?= isChecked('TRANSFORMACAO', $tipos_selecionados) ?>> Transformações</label>
            <label class="chk-lbl"><input type="checkbox" name="tipos[]" value="NASCIMENTO" <?= isChecked('NASCIMENTO', $tipos_selecionados) ?>> Nascimentos</label>
            <label class="chk-lbl"><input type="checkbox" name="tipos[]" value="SISTEMA" <?= isChecked('SISTEMA', $tipos_selecionados) ?>> Logs</label>
        </div>
    </form>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th class="c-type">EVENTO</th>
                    <th class="c-date">DATA (UTC)</th>
                    <th class="c-wallets">ORIGEM &rarr; DESTINO</th>
                    <th>DETALHES DA TRANSAÇÃO (PAYLOAD)</th>
                    <th width="80" style="text-align:right">VALOR</th>
                    <th class="c-hash">TX HASH / REF</th>
                </tr>
            </thead>
            <tbody>
                <?php if(empty($registros_finais)): ?>
                    <tr><td colspan="6" style="text-align:center; padding:40px;">Nada encontrado.</td></tr>
                <?php else: ?>
                    <?php foreach($registros_finais as $row): 
                        $t = $row['tipo'];
                        $badge = 'b-sys';
                        if($t=='FINANCEIRO') $badge='b-fin';
                        
                        // SE CONTIVER 'VENDA', MUDA A COR PARA AMARELO (VENDA)
                        if(strpos($t, 'VENDA') !== false) $badge='b-ven';
                        
                        if($t=='EMISSAO') $badge='b-min';
                        if($t=='MOVIMENTO') $badge='b-mov';
                        if($t=='TRANSFORMACAO') $badge='b-tra';
                    ?>
                    <tr>
                        <td><span class="badge <?= $badge ?>"><?= $t ?></span></td>
                        
                        <td class="c-date">
                            <?= date('Y-m-d', strtotime($row['data_evento'])) ?><br>
                            <?= date('H:i:s', strtotime($row['data_evento'])) ?>
                        </td>

                        <td class="c-wallets">
                            <div style="margin-bottom:5px;">
                                <span style="color:#555;">FROM:</span><br>
                                <span style="color:#aaa;"><?= $row['wallet_from'] ?: 'GENESIS/NULL' ?></span>
                            </div>
                            <div>
                                <span style="color:#555;">TO:</span><br>
                                <span style="color:#fff;"><?= $row['wallet_to'] ?: 'BURN/NULL' ?></span>
                            </div>
                        </td>

                        <td>
                            <div class="payload-box">
                                <?php 
                                echo "<span class='key'>DB_ID:</span> <span class='val'>{$row['id_reg']}</span>\n";
                                echo "<span class='key'>ASSET_TYPE:</span> <span class='val'>{$row['asset_type']}</span>\n";

                                if($row['item_nome']) echo "<span class='key'>ITEM:</span> <span class='val'>".htmlspecialchars($row['item_nome'])."</span>\n";
                                if($row['item_id'])   echo "<span class='key'>ITEM_ID:</span> <span class='val'>{$row['item_id']}</span>\n";
                                
                                if($row['info_extra']) echo "<span class='key'>INFO:</span> <span class='val'>".htmlspecialchars($row['info_extra'])."</span>\n";
                                if($row['mediacao'])   echo "<span class='key'>MEDIAÇÃO:</span> <span class='val'>{$row['mediacao']}</span>\n";
                                
                                // Link Principal
                                if($row['item_link']) {
                                    echo "<span class='key'>LINK DATA:</span> <a href='{$row['item_link']}' target='_blank' class='lnk'>".htmlspecialchars($row['item_link'])."</a>\n";
                                }
                                
                                // HASH FINANCEIRO SECUNDARIO
                                if(isset($row['tx_hash_financeiro'])) {
                                    echo "\n<span class='key' style='color:#28a745'>TX PAGAMENTO:</span> <span class='val'>{$row['tx_hash_financeiro']}</span>";
                                }
                                ?>
                            </div>
                        </td>

                        <td style="text-align:right; font-weight:bold; color:#fff;">
                            <?= ($row['val_num'] > 0) ? number_format($row['val_num'], 2) : '-' ?>
                        </td>

                        <td class="c-hash">
                            <?= $row['tx_hash'] ?: '-' ?>
                            
                            <?php if(isset($row['tx_hash_secundario'])): ?>
                                <br><span class="hash-tag">Ref: <?= $row['tx_hash_secundario'] ?></span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPaginas > 1): ?>
        <div class="pagination">
            <a href="<?= linkPagina(1) ?>" class="pg">&laquo;</a>
            <span class="pg active"><?= $paginaAtual ?></span>
            <a href="<?= linkPagina($totalPaginas) ?>" class="pg">&raquo;</a>
        </div>
    <?php endif; ?>

</body>
</html>