<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php");
    exit();
}

include "db_connect.php";

// 1️⃣ Daily Sales & Profit for Last 7 Days
$salesData = [];
$profitData = [];
$dates = [];
$query = "
    SELECT DATE(sale_datetime) AS day,
           SUM(total_sale) AS total_sales,
           SUM(profit) AS total_profit
    FROM sales
    WHERE sale_datetime >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    GROUP BY day
    ORDER BY day ASC
";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
    $dates[] = $row['day'];
    $salesData[] = floatval($row['total_sales']);
    $profitData[] = floatval($row['total_profit']);
}

// 2️⃣ Top-Selling Products (Last 7 Days)
$topProducts = [];
$topProductsQty = [];
$query = "
    SELECT p.name, SUM(s.quantity) AS total_sold
    FROM sales s
    JOIN products p ON s.product_id = p.id
    WHERE s.sale_datetime >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    GROUP BY s.product_id
    ORDER BY total_sold DESC
    LIMIT 5
";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
    $topProducts[] = $row['name'];
    $topProductsQty[] = intval($row['total_sold']);
}

// 3️⃣ Discounts & Refunds
$query = "
    SELECT 
        SUM(discount) AS total_discount,
        SUM(CASE WHEN refunded=1 THEN total_sale ELSE 0 END) AS total_refund,
        SUM(total_sale) AS total_sales
    FROM sales
    WHERE sale_datetime >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
";
$row = mysqli_fetch_assoc(mysqli_query($conn, $query));
$totalDiscount = floatval($row['total_discount']);
$totalRefund = floatval($row['total_refund']);
$totalSales = floatval($row['total_sales']);

// 4️⃣ Low Stock Products
$lowStockProducts = [];
$lowStockQty = [];
$query = "SELECT name, quantity FROM products WHERE quantity < 5";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
    $lowStockProducts[] = $row['name'];
    $lowStockQty[] = intval($row['quantity']);
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Admin Dashboard - Data Analysis</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { font-family: Arial; background: #f0f2f5; margin:0; padding:20px; }
        h2 { text-align:center; color:#2c3e50; margin-bottom:20px; }
        .charts { display:flex; flex-wrap:wrap; gap:20px; justify-content:center; }
        .chart-container { background:white; padding:20px; border-radius:10px; box-shadow:0 4px 10px rgba(0,0,0,0.1); width:45%; min-width:350px; }
        table { border-collapse: collapse; width: 100%; margin-top: 10px; }
        th, td { border:1px solid #ccc; padding:8px; text-align:center; }
        th { background:#007bff; color:white; }
    </style>
</head>
<body>
    <h2>Admin Dashboard - Data Analysis & Visualization</h2>

    <div class="charts">
        <!-- Daily Sales & Profit -->
        <div class="chart-container">
            <canvas id="salesProfitChart"></canvas>
        </div>

        <!-- Top Selling Products -->
        <div class="chart-container">
            <canvas id="topProductsChart"></canvas>
        </div>

        <!-- Discounts & Refunds -->
        <div class="chart-container">
            <canvas id="discountRefundChart"></canvas>
        </div>

        <!-- Low Stock Products -->
        <div class="chart-container">
            <h3>Low Stock Products</h3>
            <table>
                <tr><th>Product</th><th>Quantity</th></tr>
                <?php foreach($lowStockProducts as $i => $name): ?>
                <tr>
                    <td><?= htmlspecialchars($name) ?></td>
                    <td><?= $lowStockQty[$i] ?></td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>
    </div>

    <script>
        // 1️⃣ Daily Sales & Profit Line Chart
        new Chart(document.getElementById('salesProfitChart'), {
            type: 'line',
            data: {
                labels: <?= json_encode($dates) ?>,
                datasets: [
                    {
                        label: 'Daily Sales (KES)',
                        data: <?= json_encode($salesData) ?>,
                        borderColor: 'rgba(54,162,235,1)',
                        backgroundColor: 'rgba(54,162,235,0.2)',
                        fill: true,
                        tension: 0.4
                    },
                    {
                        label: 'Daily Profit (KES)',
                        data: <?= json_encode($profitData) ?>,
                        borderColor: 'rgba(75,192,192,1)',
                        backgroundColor: 'rgba(75,192,192,0.2)',
                        fill: true,
                        tension: 0.4
                    }
                ]
            },
            options: { responsive:true, plugins: { legend: { position: 'top' } } }
        });

        // 2️⃣ Top Selling Products Bar Chart
        new Chart(document.getElementById('topProductsChart'), {
            type: 'bar',
            data: {
                labels: <?= json_encode($topProducts) ?>,
                datasets: [{
                    label: 'Quantity Sold',
                    data: <?= json_encode($topProductsQty) ?>,
                    backgroundColor: 'rgba(231,76,60,0.7)'
                }]
            },
            options: { responsive:true, plugins: { legend: { display: false } } }
        });

        // 3️⃣ Discounts & Refunds Doughnut Chart
        new Chart(document.getElementById('discountRefundChart'), {
            type: 'doughnut',
            data: {
                labels: ['Total Discounts', 'Total Refunds', 'Net Sales'],
                datasets: [{
                    data: [<?= $totalDiscount ?>, <?= $totalRefund ?>, <?= $totalSales - $totalDiscount - $totalRefund ?>],
                    backgroundColor: ['rgba(241,196,15,0.7)','rgba(231,76,60,0.7)','rgba(46,204,113,0.7)']
                }]
            },
            options: { responsive:true }
        });
    </script>
</body>
</html>
