<?php
// Proteção de conexão
if (!defined('CONEXAO_CARREGADA')) {
    if (file_exists('../conexao.php')) require_once '../conexao.php';
    elseif (file_exists('conexao.php')) require_once 'conexao.php';
}

// Busca apenas as últimas 5 vendas para o gráfico (Zoom no recente)
$query = "SELECT preco, dataehora FROM vendas ORDER BY dataehora DESC LIMIT 5";

try {
    $result = $pdo->query($query);
    $rows = $result->fetchAll(PDO::FETCH_ASSOC);

    // Se não tiver dados suficientes, cria fake para não quebrar
    if (count($rows) < 2) {
        $rows = [
            ['preco' => 0.10, 'dataehora' => date('Y-m-d H:i:s', strtotime('-1 hour'))],
            ['preco' => 0.10, 'dataehora' => date('Y-m-d H:i:s')]
        ];
    }

    // Inverte para cronológico (Antigo -> Novo)
    $rows = array_reverse($rows);

    $labels = [];
    $data = [];
    
    foreach ($rows as $row) {
        $labels[] = date('d/m H:i', strtotime($row['dataehora']));
        $data[] = (float)$row['preco'];
    }
    
    $ultimoPreco = end($data);
    
    // Calcula variação
    $penultimoPreco = isset($data[count($data)-2]) ? $data[count($data)-2] : $ultimoPreco;
    $variacao = ($penultimoPreco > 0) ? (($ultimoPreco - $penultimoPreco) / $penultimoPreco) * 100 : 0;
    
    $corTendencia = $variacao >= 0 ? '#00ff7f' : '#ff2222';
    $iconeTendencia = $variacao >= 0 ? '▲' : '▼';
    $sinal = $variacao >= 0 ? '+' : '';

} catch (PDOException $e) {
    echo "Erro no gráfico.";
    exit;
}
?>

<div class="mini-chart-wrapper">
    <div class="chart-header">
        <span class="chart-title">PREÇO DO NFT</span>
        <div class="chart-value" style="color: <?= $corTendencia ?>">
            R$ <?= number_format($ultimoPreco, 2, ',', '.') ?>
            <span class="chart-change">
                <?= $iconeTendencia ?> <?= $sinal . number_format($variacao, 2) ?>%
            </span>
        </div>
    </div>
    
    <div class="canvas-container">
        <canvas id="nftMiniChart"></canvas>
    </div>
</div>

<script>
    if (typeof Chart === 'undefined') {
        document.write('<script src="https://cdn.jsdelivr.net/npm/chart.js"><\/script>');
    }
</script>

<style>
    .mini-chart-wrapper {
        /* Fundo Transparente Escuro para misturar com o painel */
        background: rgba(0, 0, 0, 0.3); 
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
    }

    .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 5px;
        padding-bottom: 5px;
        border-bottom: 1px dashed #333;
    }

    .chart-title {
        color: #ccc;
        font-size: 0.8rem;
        text-transform: uppercase;
        font-weight: bold;
        letter-spacing: 1px;
    }

    .chart-value {
        font-size: 1.1rem;
        font-weight: bold;
        text-shadow: 0 0 5px rgba(0,0,0,0.5);
    }

    .chart-change {
        font-size: 0.7rem;
        margin-left: 5px;
    }

    /* Altura controlada para encaixar no dashboard */
    .canvas-container {
        position: relative;
        flex-grow: 1; /* Ocupa o espaço restante */
        width: 100%;
        min-height: 150px;
    }
</style>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        const ctx = document.getElementById('nftMiniChart').getContext('2d');
        const rawData = <?= json_encode($data) ?>;

        // Cria gradiente Neon Vertical
        const gradient = ctx.createLinearGradient(0, 0, 0, 300);
        gradient.addColorStop(0, 'rgba(0, 243, 255, 0.4)'); 
        gradient.addColorStop(1, 'rgba(0, 243, 255, 0.0)'); 

        new Chart(ctx, {
            type: 'line',
            data: {
                labels: <?= json_encode($labels) ?>,
                datasets: [{
                    label: 'Preço (R$)',
                    data: rawData,
                    borderColor: '#00f3ff', // Linha Azul Neon
                    borderWidth: 2,
                    backgroundColor: gradient,
                    fill: true,
                    pointBackgroundColor: '#000',
                    pointBorderColor: '#00ff7f', // Pontos Verdes
                    pointRadius: 4, // Pontos visíveis
                    pointHoverRadius: 6,
                    pointBorderWidth: 2,
                    tension: 0 // LINHAS RETAS (Sem curva)
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(0, 0, 0, 0.9)',
                        titleColor: '#00f3ff',
                        bodyColor: '#fff',
                        borderColor: '#00f3ff',
                        borderWidth: 1,
                        displayColors: false,
                        callbacks: {
                            label: function(context) {
                                return 'R$ ' + context.parsed.y.toFixed(2);
                            },
                            afterLabel: function(context) {
                                if (context.dataIndex > 0) {
                                    let prev = context.dataset.data[context.dataIndex - 1];
                                    let current = context.parsed.y;
                                    let change = ((current - prev) / prev) * 100;
                                    let sign = change >= 0 ? '+' : '';
                                    return 'Var: ' + sign + change.toFixed(2) + '%';
                                }
                                return '';
                            }
                        }
                    }
                },
                scales: {
                    x: { 
                        display: true, 
                        grid: { color: 'rgba(255,255,255,0.1)' },
                        ticks: { color: '#888', font: { size: 9 } }
                    }, 
                    y: { 
                        display: true, 
                        grid: { color: 'rgba(255,255,255,0.1)' },
                        ticks: { color: '#888', font: { size: 9 } }
                    }  
                },
                layout: { padding: 5 }
            }
        });
    });
</script>