<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "<script>window.top.location.href='index.php';</script>"; // Redirect parent window to login page
    exit();
}

// Database connection
include 'connect.php';

// Fetch top 5 sold products in the last 7 days
$sql = "SELECT pr_Name, SUM(quantity_sold) AS total_sold 
        FROM sell 
        WHERE sell_time >= NOW() - INTERVAL 7 DAY 
        GROUP BY pr_Name 
        ORDER BY total_sold DESC 
        LIMIT 5";

$result = mysqli_query($conn, $sql);

$products = [];
$quantities = [];

while ($row = mysqli_fetch_assoc($result)) {
    $products[] = $row['pr_Name'];
    $quantities[] = $row['total_sold'];
}

mysqli_close($conn);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Top 5 Products Sold This Week</title>
    <script src="js/chart.js"></script>
    <style>
        /* Set canvas size to 50px by 50px */
        #chart-container {
            width: 400px;
            height: 400px;
        }
        canvas {
            width: 400px !important;
            height: 400px !important;
        }
    </style>
</head>
<body>
    <h2>Top 5 Products Sold in the Last 7 Days</h2>
    <div id="chart-container">
        <canvas id="topProductsChart"></canvas>
    </div>
    
    <script>
        var ctx = document.getElementById('topProductsChart').getContext('2d');
        var topProductsChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: <?php echo json_encode($products); ?>,
                datasets: [{
                    label: 'Quantity Sold',
                    data: <?php echo json_encode($quantities); ?>,
                    backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4CAF50', '#9966FF'],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: false, // Disable responsiveness
                maintainAspectRatio: false // Allow custom size
            }
        });
    </script>
</body>
</html>
