<?php
session_start();
require 'conexao.php';

// Verificação de Login
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$my_wallet = $_SESSION['user_wallet'];
$my_user = $_SESSION['user_name'];

// --- INICIALIZAÇÃO DOS FILTROS E PAGINAÇÃO ---
$filtro_tipo = $_GET['tipo'] ?? 'todos';
$filtro_busca = trim($_GET['busca'] ?? '');
$data_inicio = $_GET['data_inicio'] ?? '';
$data_fim = $_GET['data_fim'] ?? '';
$ordem = $_GET['ordem'] ?? 'desc'; 
$pagina_atual = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
if ($pagina_atual < 1) $pagina_atual = 1;

$itens_por_pagina = 20;
$offset = ($pagina_atual - 1) * $itens_por_pagina;

// --- CONSULTA SQL ---
$where_clause = " WHERE 1=1 ";
$params = [];

// 1. Filtro de Tipo
if ($filtro_tipo == 'recebidos') {
    $where_clause .= " AND m.destinatario = :my_wallet";
    $params[':my_wallet'] = $my_wallet;
} elseif ($filtro_tipo == 'enviados') {
    $where_clause .= " AND m.remetente = :my_wallet";
    $params[':my_wallet'] = $my_wallet;
} else {
    $where_clause .= " AND (m.remetente = :my_wallet OR m.destinatario = :my_wallet)";
    $params[':my_wallet'] = $my_wallet;
}

// 2. Filtro de Busca
if (!empty($filtro_busca)) {
    $where_clause .= " AND (m.id LIKE :busca OR m.remetente LIKE :busca OR m.destinatario LIKE :busca OR m.referencia LIKE :busca OR sender.user LIKE :busca OR receiver.user LIKE :busca)";
    $params[':busca'] = "%$filtro_busca%";
}

// 3. Filtro de Data
if (!empty($data_inicio)) {
    $where_clause .= " AND m.dataehora >= :data_inicio";
    $params[':data_inicio'] = $data_inicio . " 00:00:00";
}
if (!empty($data_fim)) {
    $where_clause .= " AND m.dataehora <= :data_fim";
    $params[':data_fim'] = $data_fim . " 23:59:59";
}

// --- TOTAL DE REGISTROS ---
try {
    $sql_count = "SELECT COUNT(*) 
                  FROM mempool m
                  LEFT JOIN usersblock sender ON m.remetente = sender.wallet
                  LEFT JOIN usersblock receiver ON m.destinatario = receiver.wallet" . $where_clause;
    
    $stmtCount = $pdo->prepare($sql_count);
    $stmtCount->execute($params);
    $total_registros = $stmtCount->fetchColumn();
    $total_paginas = ceil($total_registros / $itens_por_pagina);
} catch (PDOException $e) {
    $total_registros = 0;
    $total_paginas = 1;
}

// --- BUSCAR DADOS ---
$sql_order = ($ordem == 'asc') ? 'ASC' : 'DESC';

$sql = "SELECT 
            m.*,
            sender.user AS nome_remetente,
            receiver.user AS nome_destinatario
        FROM mempool m
        LEFT JOIN usersblock sender ON m.remetente = sender.wallet
        LEFT JOIN usersblock receiver ON m.destinatario = receiver.wallet
        $where_clause
        ORDER BY m.dataehora $sql_order 
        LIMIT :limit OFFSET :offset";

try {
    $stmt = $pdo->prepare($sql);
    foreach ($params as $key => $val) {
        $stmt->bindValue($key, $val);
    }
    $stmt->bindValue(':limit', $itens_por_pagina, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $transacoes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $erro = "Erro ao buscar transações: " . $e->getMessage();
}

function gerarLinkPagina($pagina) {
    $params = $_GET;
    $params['pagina'] = $pagina;
    return '?' . http_build_query($params);
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Meus Recibos - 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>
        /* === ESTILOS ESPECÍFICOS PARA RECIBOS === */
        
        /* Limpeza de fundo preto */
        html, body { background: none !important; background-color: transparent !important; }
        
        body {
            background: url('rpg-login-background.jpg') no-repeat center center fixed !important;
            background-size: cover !important;
            color: white;
            min-height: 100vh;
        }

        .receipts-container {
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
        }

        /* Card de Filtros */
        .filter-card {
            background-color: rgba(0, 5, 20, 0.85); /* Vidro Transparente */
            border: 2px solid var(--primary);
            box-shadow: 0 0 15px rgba(0, 0, 255, 0.2);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 30px;
        }

        /* Grid do Formulário */
        .filter-form {
            display: grid;
            /* Cria colunas flexíveis, mínimo 160px */
            grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
            gap: 15px;
            align-items: end;
        }

        /* Grupo do Botão - Ocupa linha inteira e centraliza */
        .full-width-btn-container {
            grid-column: 1 / -1; /* Força ocupar todas as colunas */
            display: flex;
            justify-content: center; /* Centraliza o botão */
            margin-top: 10px;
        }

        .form-group { display: flex; flex-direction: column; gap: 5px; }
        .form-group label { color: #ccc; font-size: 0.85rem; font-weight: bold; text-align: center; }

        .filter-input {
            background: rgba(0,0,0,0.8);
            border: 1px solid var(--primary);
            color: white;
            padding: 10px;
            border-radius: 5px;
            outline: none;
            width: 100%;
            text-align: center;
        }
        .filter-input:focus { border-color: var(--neon-bright); box-shadow: 0 0 5px var(--primary); }

        .btn-filter {
            background: var(--primary);
            color: white;
            border: 2px solid var(--primary);
            padding: 10px 40px; /* Botão mais largo */
            border-radius: 8px;
            cursor: pointer;
            font-weight: bold;
            text-transform: uppercase;
            font-size: 1rem;
            transition: all 0.3s;
            min-width: 200px;
        }
        .btn-filter:hover { 
            background: #000; 
            box-shadow: 0 0 20px var(--neon-bright); 
            color: var(--primary);
        }

        /* --- LISTA DE TRANSAÇÕES --- */
        .transactions-list { display: flex; flex-direction: column; gap: 15px; }

        .transaction-card {
            background-color: rgba(0, 0, 0, 0.85);
            border: 1px solid #444;
            border-radius: 10px;
            padding: 15px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            transition: transform 0.2s;
            position: relative;
            overflow: hidden;
        }
        .transaction-card:hover { transform: translateY(-2px); border-color: #666; }

        .type-in { border-left: 5px solid #28a745; box-shadow: inset 10px 0 20px -10px rgba(40, 167, 69, 0.2); }
        .value-in { color: #28a745; font-size: 1.4rem; font-weight: bold; text-shadow: 0 0 5px #28a745; }

        .type-out { border-left: 5px solid #ff2222; box-shadow: inset 10px 0 20px -10px rgba(255, 34, 34, 0.2); }
        .value-out { color: #ff2222; font-size: 1.4rem; font-weight: bold; text-shadow: 0 0 5px #ff2222; }

        .trans-header {
            display: flex; justify-content: space-between; align-items: center;
            border-bottom: 1px dashed #444; padding-bottom: 8px;
        }
        .trans-id { font-family: monospace; color: #888; font-size: 0.9rem; margin-left: 10px; }
        .trans-date { color: #aaa; font-size: 0.8rem; font-style: italic; }
        
        .trans-body { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
        .trans-info { font-size: 0.95rem; color: #ddd; line-height: 1.5; }
        
        .user-tag { color: var(--neon-bright); font-weight: bold; font-size: 1.1rem; }
        .wallet-tag { 
            font-family: 'Courier New', monospace; 
            color: #aaa; font-size: 0.8rem; 
            display: block; margin-top: 2px; word-break: break-all;
        }
        
        .trans-ref { font-size: 0.8rem; color: #888; background: rgba(255,255,255,0.05); padding: 5px; border-radius: 4px; margin-top: 5px; }

        /* PAGINAÇÃO */
        .pagination { display: flex; justify-content: center; gap: 10px; margin-top: 40px; margin-bottom: 20px; flex-wrap: wrap; }
        .pagination a {
            padding: 10px 15px; background: rgba(0,0,0,0.8); border: 1px solid var(--primary); color: var(--primary);
            text-decoration: none; border-radius: 5px; font-weight: bold; transition: 0.3s;
        }
        .pagination a:hover { background: var(--primary); color: #fff; box-shadow: 0 0 10px var(--primary); }
        .pagination .active { background: var(--primary); color: #fff; border-color: var(--primary); box-shadow: 0 0 15px var(--neon-bright); }
        .pagination .disabled { opacity: 0.5; pointer-events: none; border-color: #444; color: #888; }

        @media (max-width: 600px) {
            .trans-body { flex-direction: column; align-items: flex-start; }
            .value-in, .value-out { align-self: flex-end; }
        }
    </style>
</head>
<body>

    <div class="receipts-container">
        
        <div class="listing-header-centered" style="text-align:center; margin-bottom:30px; margin-top:30px;">
            <h1 style="color: var(--primary); text-shadow: 0 0 10px var(--primary); font-size: 2.5rem; margin-bottom: 15px;">
                HISTÓRICO DE TRANSAÇÕES
            </h1>
            <a href="mercado/mercado.php">
                <button class="btn-filter" style="width:auto; min-width:auto; padding: 10px 30px;">Voltar ao Mercado</button>
            </a>
        </div>

        <div class="filter-card">
            <form method="GET" class="filter-form">
                
                <div class="form-group">
                    <label>Tipo</label>
                    <select name="tipo" class="filter-input">
                        <option value="todos" <?= $filtro_tipo == 'todos' ? 'selected' : '' ?>>Todas</option>
                        <option value="recebidos" <?= $filtro_tipo == 'recebidos' ? 'selected' : '' ?>>Recebidos (+)</option>
                        <option value="enviados" <?= $filtro_tipo == 'enviados' ? 'selected' : '' ?>>Enviados (-)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Ordem</label>
                    <select name="ordem" class="filter-input">
                        <option value="desc" <?= $ordem == 'desc' ? 'selected' : '' ?>>Mais Recentes</option>
                        <option value="asc" <?= $ordem == 'asc' ? 'selected' : '' ?>>Mais Antigos</option>
                    </select>
                </div>

                <div class="form-group" style="grid-column: span 2; /* Ocupa 2 espaços se possível */">
                    <label>Buscar</label>
                    <input type="text" name="busca" value="<?= htmlspecialchars($filtro_busca) ?>" class="filter-input" placeholder="ID, Usuário, Carteira...">
                </div>

                <div class="form-group">
                    <label>De:</label>
                    <input type="date" name="data_inicio" value="<?= $data_inicio ?>" class="filter-input">
                </div>

                <div class="form-group">
                    <label>Até:</label>
                    <input type="date" name="data_fim" value="<?= $data_fim ?>" class="filter-input">
                </div>

                <div class="full-width-btn-container">
                    <button type="submit" class="btn-filter">
                        <i class="fas fa-search"></i> FILTRAR RESULTADOS
                    </button>
                </div>
            </form>
        </div>

        <div class="transactions-list">
            <?php if (isset($erro)): ?>
                <div style="color:red; text-align:center; padding:20px; border:1px solid red; background:rgba(255,0,0,0.2);">
                    <?= $erro ?>
                </div>
            <?php elseif (empty($transacoes)): ?>
                <div style="text-align:center; padding:40px; color:#888; font-style:italic;">
                    <i class="fas fa-receipt fa-3x" style="margin-bottom:15px;"></i><br>
                    Nenhuma transação encontrada com estes filtros.
                </div>
            <?php else: ?>
                
                <?php foreach ($transacoes as $t): 
                    $is_entrada = ($t['destinatario'] == $my_wallet);
                    $card_class = $is_entrada ? 'type-in' : 'type-out';
                    $valor_class = $is_entrada ? 'value-in' : 'value-out';
                    $sinal = $is_entrada ? '+' : '-';
                    
                    $remetente = $t['nome_remetente'] ?? 'Sistema/Externo';
                    $destinatario = $t['nome_destinatario'] ?? 'Sistema/Externo';

                    if ($t['remetente'] == $my_wallet) $remetente = "Você";
                    if ($t['destinatario'] == $my_wallet) $destinatario = "Você";
                ?>
                    <div class="transaction-card <?= $card_class ?>">
                        <div class="trans-header">
                            <span>
                                <?php if ($is_entrada): ?>
                                    <i class="fas fa-arrow-down" style="color:#28a745"></i> <strong>RECEBIDO</strong>
                                <?php else: ?>
                                    <i class="fas fa-arrow-up" style="color:#ff2222"></i> <strong>ENVIADO</strong>
                                <?php endif; ?>
                                <span class="trans-id">#<?= $t['id'] ?></span>
                            </span>
                            <span class="trans-date">
                                <i class="far fa-clock"></i> <?= date('d/m/Y H:i', strtotime($t['dataehora'])) ?>
                            </span>
                        </div>

                        <div class="trans-body">
                            <div class="trans-info">
                                <?php if ($is_entrada): ?>
                                   
                                    <span class="wallet-tag">Wallet: <?= htmlspecialchars($t['remetente']) ?></span>
                                <?php else: ?>
                                    
                                    <span class="wallet-tag">Wallet: <?= htmlspecialchars($t['destinatario']) ?></span>
                                <?php endif; ?>
                            </div>
                            
                            <div class="<?= $valor_class ?>">
                                <?= $sinal ?> R$ <?= number_format($t['valor'], 2, ',', '.') ?>
                            </div>
                        </div>

                        <?php if (!empty($t['referencia'])): ?>
                            <div class="trans-ref">
                                <strong>Ref:</strong> <?= htmlspecialchars($t['referencia']) ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>

            <?php endif; ?>
        </div>

        <?php if ($total_paginas > 1): ?>
            <div class="pagination">
                <?php if ($pagina_atual > 1): ?>
                    <a href="<?= gerarLinkPagina($pagina_atual - 1) ?>">« Anterior</a>
                <?php else: ?>
                    <a class="disabled">« Anterior</a>
                <?php endif; ?>

                <a class="active">Página <?= $pagina_atual ?> de <?= $total_paginas ?></a>

                <?php if ($pagina_atual < $total_paginas): ?>
                    <a href="<?= gerarLinkPagina($pagina_atual + 1) ?>">Próxima »</a>
                <?php else: ?>
                    <a class="disabled">Próxima »</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>

    </div>

</body>
</html>