<?php
include 'conexao.php';

// Verifica se há dados
$hasData = $pdo->query("SELECT COUNT(*) FROM vendas")->fetchColumn() > 0;

if ($hasData) {
    // Consultas para estatísticas
    $stats = [
        'total_vendido' => $pdo->query("SELECT COUNT(*) FROM vendas")->fetchColumn(),
        'volume_total' => $pdo->query("SELECT SUM(preco) FROM vendas")->fetchColumn(),
        'preco_medio' => $pdo->query("SELECT AVG(preco) FROM vendas")->fetchColumn(),
        'total_emitido' => $pdo->query("SELECT COUNT(*) FROM personagens")->fetchColumn() + 
                          $pdo->query("SELECT COUNT(*) FROM fichaspersonagens")->fetchColumn(),
        'ultimo_preco' => $pdo->query("SELECT preco FROM vendas ORDER BY dataehora DESC LIMIT 1")->fetchColumn(),
        'variacao' => function() use ($pdo) {
            $ultimos = $pdo->query("SELECT preco FROM vendas ORDER BY dataehora DESC LIMIT 2")->fetchAll(PDO::FETCH_COLUMN);
            return count($ultimos) > 1 ? (($ultimos[0] - $ultimos[1]) / $ultimos[1] * 100) : 0;
        }
    ];

    // Dados para o gráfico
    $queryAll = "SELECT preco, dataehora as timestamp FROM vendas ORDER BY dataehora ASC";
    $resultAll = $pdo->query($queryAll);
    
    $dataPoints = [];
    while ($row = $resultAll->fetch(PDO::FETCH_ASSOC)) {
        $dataPoints[] = [
            'x' => $row['timestamp'],
            'y' => (float)$row['preco']
        ];
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Painel Completo de NFTs</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/luxon@3.0.1"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@1.2.0"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@1.2.1"></script>
    <style>
        :root {
            --primary: #4bc0c0;
            --secondary: #9966ff;
            --dark: #121212;
            --light: #f8f9fa;
        }
        body {
            font-family: 'Segoe UI', sans-serif;
            background-color: var(--dark);
            color: var(--light);
            margin: 0;
            padding: 20px;
        }
        .dashboard {
            max-width: 1200px;
            margin: 0 auto;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #333;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-card {
            background: #1e1e1e;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s;
        }
        .stat-card:hover {
            transform: translateY(-5px);
        }
        .stat-value {
            font-size: 28px;
            font-weight: bold;
            color: var(--primary);
            margin: 10px 0;
        }
        .stat-label {
            font-size: 14px;
            color: #aaa;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .chart-container {
            background: #1e1e1e;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .chart-wrapper {
            position: relative;
            height: 500px;
            width: 100%;
        }
        .controls {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        button {
            background: #333;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: bold;
        }
        button:hover {
            background: #444;
            transform: translateY(-2px);
        }
        .btn-primary {
            background: var(--primary);
            color: #121212;
        }
        .btn-primary:hover {
            background: #3aa8a8;
        }
        .positive {
            color: #4CAF50;
        }
        .negative {
            color: #F44336;
        }
        .price-display {
            font-size: 24px;
            text-align: center;
            margin: 20px 0;
        }
        .current-price {
            font-size: 32px;
            color: var(--primary);
            font-weight: bold;
        }
        .view-all {
            text-align: center;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="dashboard">
        <?php if ($hasData): ?>
            <div class="header">
                <h1>Painel de NFTs</h1>
                <div class="price-display">
                    Preço Atual: <span class="current-price">R$ <?= number_format($stats['ultimo_preco'], 2) ?></span>
                    <span class="<?= $stats['variacao']() >= 0 ? 'positive' : 'negative' ?>">
                        (<?= $stats['variacao']() >= 0 ? '+' : '' ?><?= number_format($stats['variacao'](), 2) ?>%)
                    </span>
                </div>
            </div>

            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-label">Total de NFTs Emitidos</div>
                    <div class="stat-value"><?= number_format($stats['total_emitido']) ?></div>
                    <div class="stat-label">Personagens: <?= $pdo->query("SELECT COUNT(*) FROM personagens")->fetchColumn() ?></div>
                    <div class="stat-label">Fichas: <?= $pdo->query("SELECT COUNT(*) FROM fichaspersonagens")->fetchColumn() ?></div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">NFTs Vendidos</div>
                    <div class="stat-value"><?= number_format($stats['total_vendido']) ?></div>
                    <div class="stat-label">Últimos 7 dias: <?= $pdo->query("SELECT COUNT(*) FROM vendas WHERE dataehora >= NOW() - INTERVAL 7 DAY")->fetchColumn() ?></div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Volume Total</div>
                    <div class="stat-value">R$ <?= number_format($stats['volume_total'], 2) ?></div>
                    <div class="stat-label">Média diária: R$ <?= number_format($stats['volume_total'] / max(1, $stats['total_vendido']), 2) ?></div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Preço Médio</div>
                    <div class="stat-value">R$ <?= number_format($stats['preco_medio'], 2) ?></div>
                    <div class="stat-label">Mínimo: R$ <?= number_format($pdo->query("SELECT MIN(preco) FROM vendas")->fetchColumn(), 2) ?></div>
                    <div class="stat-label">Máximo: R$ <?= number_format($pdo->query("SELECT MAX(preco) FROM vendas")->fetchColumn(), 2) ?></div>
                </div>
            </div>

            <div class="chart-container">
                <h2>Histórico Completo de Vendas</h2>
                <div class="controls">
                    <button onclick="zoomLastWeek()">Última Semana</button>
                    <button onclick="zoomLastMonth()">Último Mês</button>
                    <button onclick="resetZoom()">Todo Período</button>
                    <button onclick="exportChart()">Exportar Imagem</button>
                </div>
                <div class="chart-wrapper">
                    <canvas id="chartAll"></canvas>
                </div>
                <div class="view-all">
                    <button class="btn-primary" onclick="window.location.href='todasmovimentacoesnfts.php'">Verificar Todas as Movimentações</button>
                </div>
            </div>

            <script>
                // Configuração do gráfico
                const ctxAll = document.getElementById('chartAll').getContext('2d');
                
                const chartAll = new Chart(ctxAll, {
                    type: 'line',
                    data: {
                        datasets: [{
                            label: 'Preço (R$)',
                            data: <?= json_encode($dataPoints) ?>,
                            borderColor: '#4bc0c0',
                            backgroundColor: 'rgba(75, 192, 192, 0.1)',
                            borderWidth: 3,
                            tension: 0.1,
                            fill: true,
                            pointRadius: 4,
                            pointHoverRadius: 8,
                            pointBackgroundColor: '#4bc0c0',
                            pointBorderColor: '#fff',
                            pointBorderWidth: 2
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            x: {
                                type: 'time',
                                time: {
                                    parser: 'yyyy-MM-dd HH:mm:ss',
                                    tooltipFormat: 'dd/MM/yyyy HH:mm',
                                    unit: 'day',
                                    displayFormats: {
                                        day: 'dd/MM'
                                    }
                                },
                                ticks: {
                                    maxRotation: 45,
                                    minRotation: 45,
                                    color: '#aaa'
                                },
                                grid: {
                                    color: 'rgba(255, 255, 255, 0.1)'
                                },
                                title: {
                                    display: true,
                                    text: 'Data',
                                    color: '#fff'
                                }
                            },
                            y: {
                                beginAtZero: false,
                                ticks: {
                                    color: '#aaa'
                                },
                                grid: {
                                    color: 'rgba(255, 255, 255, 0.1)'
                                },
                                title: {
                                    display: true,
                                    text: 'Preço (R$)',
                                    color: '#fff'
                                }
                            }
                        },
                        plugins: {
                            zoom: {
                                zoom: {
                                    wheel: { enabled: true },
                                    pinch: { enabled: true },
                                    mode: 'xy'
                                },
                                pan: {
                                    enabled: true,
                                    mode: 'xy'
                                }
                            },
                            tooltip: {
                                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                                titleColor: '#4bc0c0',
                                bodyColor: '#fff',
                                borderColor: '#4bc0c0',
                                borderWidth: 1,
                                callbacks: {
                                    label: function(context) {
                                        return 'R$ ' + context.parsed.y.toFixed(2);
                                    },
                                    afterLabel: function(context) {
                                        if (context.dataIndex > 0) {
                                            const prevValue = context.chart.data.datasets[0].data[context.dataIndex-1].y;
                                            const change = context.parsed.y - prevValue;
                                            const changePercent = (change / prevValue) * 100;
                                            return [
                                                'Variação: ' + (change >= 0 ? '+' : '') + change.toFixed(2),
                                                'Percentual: ' + (change >= 0 ? '+' : '') + changePercent.toFixed(2) + '%'
                                            ];
                                        }
                                        return '';
                                    }
                                }
                            },
                            legend: {
                                labels: {
                                    color: '#fff',
                                    font: {
                                        size: 14
                                    }
                                }
                            }
                        }
                    },
                    plugins: [ChartZoom]
                });

                // Funções de controle
                function zoomLastWeek() {
                    const now = luxon.DateTime.now().toJSDate();
                    const oneWeekAgo = luxon.DateTime.now().minus({weeks: 1}).toJSDate();
                    chartAll.options.scales.x.min = oneWeekAgo;
                    chartAll.options.scales.x.max = now;
                    chartAll.update();
                }

                function zoomLastMonth() {
                    const now = luxon.DateTime.now().toJSDate();
                    const oneMonthAgo = luxon.DateTime.now().minus({months: 1}).toJSDate();
                    chartAll.options.scales.x.min = oneMonthAgo;
                    chartAll.options.scales.x.max = now;
                    chartAll.update();
                }

                function resetZoom() {
                    chartAll.options.scales.x.min = undefined;
                    chartAll.options.scales.x.max = undefined;
                    chartAll.update();
                }

                function exportChart() {
                    const link = document.createElement('a');
                    link.download = 'grafico-nfts.png';
                    link.href = document.getElementById('chartAll').toDataURL('image/png');
                    link.click();
                }
            </script>

        <?php else: ?>
            <div class="chart-container">
                <h2>Nenhum dado de venda encontrado</h2>
                <p>Não há transações registradas no banco de dados.</p>
                <div class="view-all">
                    <button class="btn-primary" onclick="window.location.href='todasmovimentacoesnfts.php'">Verificar Movimentações</button>
                </div>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>