<?php 
include "database/database.php";
include "database/data.php";

// Initialize an array to track item types with sales
$item_types_with_sales = [];

$sql = "SELECT sum(total) as total_sell, item_type FROM ".$sell_data." GROUP BY item_type";
$result = $connection->query($sql);

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $total_sell = $row['total_sell'];
        $item_type = $row['item_type'];

        // Update the category with the total sell
        $query = "UPDATE ".$catagories." SET total='$total_sell' WHERE type = '$item_type'";
        if ($connection->query($query)) {
            // Update success
        } else {
            // Update fail
        }

        // Add the item type to the array of item types with sales
        $item_types_with_sales[] = $item_type;
    }
}

// Set categories with no sales to zero
if (!empty($item_types_with_sales)) {
    $query = "UPDATE ".$catagories." SET total='0' WHERE type NOT IN ('" . implode("','", $item_types_with_sales) . "')";
    if ($connection->query($query)) {
        // Update success
    } else {
        // Update fail
    }
} else {
    // If there were no sales, set all categories to zero
    $query = "UPDATE ".$catagories." SET total='0'";
    if ($connection->query($query)) {
        // Update success
    } else {
        // Update fail
    }
}

?>

