<?php
include 'conexao.php';

// Busca dados das últimas 10 vendas
$query = "SELECT quantidade, preco, dataehora FROM vendas ORDER BY dataehora DESC LIMIT 10";

try {
    $result = $pdo->query($query);

    $labels = [];
    $values = [];

    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $labels[] = $row['dataehora'];
        $values[] = $row['preco'];
    }

    // Inverter para ordem cronológica
    $labels = array_reverse($labels);
    $values = array_reverse($values);
    
} catch (PDOException $e) {
    die("Erro na consulta ao banco de dados: " . $e->getMessage());
}

// Busca o preço mais recente
$lastPrice = $pdo->query("SELECT preco FROM vendas ORDER BY dataehora DESC LIMIT 1")->fetchColumn();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Gráfico de Variação de Preço de Vendas</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: black;
            color: white;
            margin: 0;
            padding: 0;
        }

        .container {
            width: 80%; 
            margin: auto;
            background-color: black;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .current-price {
            font-size: 24px;
            margin-bottom: 10px;
            text-align: center;
        }
        
        #myChart {
            width: 100%;
            height: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <canvas id="myChart"></canvas>
    </div>

    <script>
        var labels = <?php echo json_encode($labels); ?>;
        var values = <?php echo json_encode($values); ?>;

        var ctx = document.getElementById('myChart').getContext('2d');
        var chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Preço',
                    data: values,
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    borderColor: 'rgba(75, 192, 192, 1)',
                    borderWidth: 1,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                scales: {
                    y: {
                        beginAtZero: false
                    },
                    x: {
                        ticks: {
                            maxRotation: 45,
                            minRotation: 45
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                var label = context.dataset.label || '';
                                if (label) label += ': ';
                                if (context.parsed.y !== null) {
                                    label += 'R$ ' + context.parsed.y.toFixed(2);

                                    if (context.dataIndex > 0) {
                                        var prevValue = values[context.dataIndex - 1];
                                        var change = context.parsed.y - prevValue;
                                        label += ' (' + (change >= 0 ? '+' : '') + change.toFixed(2) + ')';
                                    }
                                }
                                return label;
                            }
                        }
                    }
                }
            }
        });
    </script>

    <div class="container">
        <h2 class="current-price">Preço atual: R$ <?php echo number_format($lastPrice, 2); ?></h2>
    </div>
</body>
</html>