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

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

if ($hasData) {
    // Consultas para estatísticas
    $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();
    
    // Estatísticas de Itens
    $total_personagens = $pdo->query("SELECT COUNT(*) FROM personagens")->fetchColumn();
    $total_fichas = $pdo->query("SELECT COUNT(*) FROM fichaspersonagens")->fetchColumn();
    $total_emitido = $total_personagens + $total_fichas;

    // Preço Atual e Variação
    $ultimo_preco = $pdo->query("SELECT preco FROM vendas ORDER BY dataehora DESC LIMIT 1")->fetchColumn();
    $ultimos = $pdo->query("SELECT preco FROM vendas ORDER BY dataehora DESC LIMIT 2")->fetchAll(PDO::FETCH_COLUMN);
    
    $variacao = 0;
    if (count($ultimos) > 1) {
        $variacao = (($ultimos[0] - $ultimos[1]) / $ultimos[1]) * 100;
    }

    // --- CORREÇÃO PRINCIPAL AQUI ---
    $queryAll = "SELECT preco, dataehora FROM vendas ORDER BY dataehora ASC";
    $resultAll = $pdo->query($queryAll);
    
    $dataPoints = [];
    while ($row = $resultAll->fetch(PDO::FETCH_ASSOC)) {
        $dataPoints[] = [
            // Convertemos a data para MILISSEGUNDOS (Timestamp) para o gráfico não se perder
            'x' => strtotime($row['dataehora']) * 1000, 
            'y' => (float)$row['preco']
        ];
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <title>Painel de Mercado - Mavilla</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link rel="stylesheet" href="css/dashboard.css">
    
    <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@2.0.1"></script>

    <style>
        /* === ESTILOS ESPECÍFICOS DO GRÁFICO === */
        
        /* Garante fundo transparente */
        body {
            background: url('rpg-login-background.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
            font-family: 'Segoe UI', sans-serif;
            margin: 0; padding: 20px;
        }

        .dashboard-container {
            max-width: 1200px;
            margin: 0 auto;
        }

        /* Header com Preço */
        .price-header {
            text-align: center;
            margin-bottom: 30px;
            background: rgba(0, 5, 30, 0.8);
            border: 2px solid #0000FF;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 0 15px rgba(0,0,255,0.3);
        }
        
        .current-price {
            font-size: 2.5rem;
            font-weight: bold;
            color: #0000FF;
            text-shadow: 0 0 10px #0000FF;
        }
        
        .variation { font-size: 1.2rem; font-weight: bold; margin-left: 10px; }
        .positive { color: #28a745; text-shadow: 0 0 5px #28a745; }
        .negative { color: #ff2222; text-shadow: 0 0 5px #ff2222; }

        /* Grid de Estatísticas */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: rgba(0, 0, 0, 0.7);
            border: 1px solid #333;
            border-left: 4px solid #0000FF;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
        }
        .stat-val { font-size: 1.5rem; font-weight: bold; color: white; margin: 5px 0; }
        .stat-label { color: #aaa; font-size: 0.9rem; text-transform: uppercase; }

        /* Container do Gráfico */
        .chart-box {
            background: rgba(0, 5, 30, 0.9);
            border: 2px solid #0000FF;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 0 20px rgba(0,0,255,0.2);
            position: relative;
        }
        
        .chart-wrapper {
            position: relative;
            height: 400px; /* Altura fixa para o canvas */
            width: 100%;
        }

        /* Botões de Controle */
        .controls {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .btn-ctrl {
            background: #000;
            color: #0000FF;
            border: 1px solid #0000FF;
            padding: 8px 15px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: bold;
            transition: 0.3s;
        }
        .btn-ctrl:hover {
            background: #0000FF;
            color: white;
            box-shadow: 0 0 10px #0000FF;
        }
        
        .btn-back {
            display: block;
            width: 200px;
            margin: 30px auto;
            padding: 12px;
            text-align: center;
            background: #000;
            color: white;
            border: 2px solid #0000FF;
            border-radius: 8px;
            font-weight: bold;
            cursor: pointer;
        }
        .btn-back:hover { background: #0000FF; box-shadow: 0 0 15px #0000FF; }

    </style>
</head>
<body>

<div class="dashboard-container">
    
    
    <div style="text-align:center; margin-bottom:20px;">
        <h1><font color="white">RPG Era Medieval: Ferro & Fogo Pelo Poder</font></h1>
     <a href="dashboard.php" class="btn-back">Menu Principal</a>
        <a href="mercado/mercado.php" class="btn-back">Mercado</a>
    </div>

    <?php if ($hasData): ?>
        
        <div class="price-header">
            <div style="font-size:0.9rem; color:#aaa; text-transform:uppercase; letter-spacing:1px;">Preço Atual</div>
            <div>
                <span class="current-price">R$ <?= number_format($ultimo_preco, 2, ',', '.') ?></span>
                <span class="variation <?= $variacao >= 0 ? 'positive' : 'negative' ?>">
                    <?= $variacao >= 0 ? '▲' : '▼' ?> <?= number_format(abs($variacao), 2, ',', '.') ?>%
                </span>
            </div>
        </div>

        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-label">Volume Total</div>
                <div class="stat-val" style="color:#28a745;">R$ <?= number_format($volume_total, 2, ',', '.') ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">NFTs Vendidos</div>
                <div class="stat-val"><?= number_format($total_vendido) ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Total Emitido</div>
                <div class="stat-val" style="color:#0000FF;"><?= number_format($total_emitido) ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Preço Médio</div>
                <div class="stat-val">R$ <?= number_format($preco_medio, 2, ',', '.') ?></div>
            </div>
        </div>

        <div class="chart-box">
            <h3 style="text-align:center; color:#0000FF; margin-top:0;">Histórico de Valorização</h3>
            
            <div class="controls">
                <button class="btn-ctrl" onclick="resetZoom()">Zoom Total</button>
                <button class="btn-ctrl" onclick="zoomDays(7)">7 Dias</button>
                <button class="btn-ctrl" onclick="zoomDays(30)">30 Dias</button>
            </div>

            <div class="chart-wrapper">
                <canvas id="chartAll"></canvas>
            </div>
            
            <p style="text-align:center; color:#666; font-size:0.8rem; margin-top:10px;">
                <i>Arraste para mover (Pan) • Use a roda do mouse + Ctrl para Zoom (PC) • Pinça para Zoom (Mobile)</i>
            </p>
        </div>

        <script>
            const ctx = document.getElementById('chartAll').getContext('2d');
            const rawData = <?= json_encode($dataPoints) ?>;

            // Configuração do Gráfico
            const chart = new Chart(ctx, {
                type: 'line',
                data: {
                    datasets: [{
                        label: 'Preço (R$)',
                        data: rawData,
                        borderColor: '#0000FF',       
                        backgroundColor: 'rgba(0, 0, 255, 0.1)', 
                        borderWidth: 2,
                        pointBackgroundColor: '#000', 
                        pointBorderColor: '#00f3ff',  
                        pointRadius: 4, // Pontos um pouco maiores
                        pointHoverRadius: 7,
                        fill: true,
                        tension: 0.3 
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        mode: 'index',
                        intersect: false,
                    },
                    plugins: {
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.9)',
                            titleColor: '#00f3ff',
                            bodyColor: '#fff',
                            borderColor: '#0000FF',
                            borderWidth: 1,
                            callbacks: {
                                label: function(context) {
                                    return ' R$ ' + context.parsed.y.toFixed(2).replace('.', ',');
                                }
                            }
                        },
                        legend: { display: false }, 
                        zoom: {
                            pan: { enabled: true, mode: 'x' },
                            zoom: {
                                wheel: { enabled: true, modifierKey: 'ctrl' },
                                pinch: { enabled: true },
                                mode: 'x'
                            }
                        }
                    },
                    scales: {
                        x: {
                            type: 'time',
                            time: {
                                unit: 'day',
                                tooltipFormat: 'dd/MM/yyyy HH:mm',
                                displayFormats: { day: 'dd/MM', hour: 'HH:mm' }
                            },
                            grid: { color: 'rgba(255,255,255,0.05)' },
                            ticks: { color: '#aaa' }
                        },
                        y: {
                            beginAtZero: false,
                            grid: { color: 'rgba(255,255,255,0.05)' },
                            ticks: { 
                                color: '#aaa',
                                callback: function(value) { return 'R$ ' + value.toFixed(2); }
                            }
                        }
                    }
                }
            });

            // Funções de Controle de Zoom
            function resetZoom() {
                chart.resetZoom();
            }

            function zoomDays(days) {
                const now = new Date();
                const past = new Date();
                past.setDate(now.getDate() - days);
                
                chart.zoomScale('x', {min: past.getTime(), max: now.getTime()}, 'default');
            }
        </script>

    <?php else: ?>
        <div class="chart-box" style="margin-top:50px; text-align:center;">
            <h2 style="color:#0000FF;">Mercado Aguardando Transações</h2>
            <p style="color:#ccc;">Ainda não há histórico de vendas para gerar o gráfico.</p>
            <a href="mercado/mercado.php" class="btn-back" style="display:inline-block; width:auto;">Voltar</a>
        </div>
    <?php endif; ?>

</div>

</body>
</html>