<?php
require_once './shikanisha.kts.php';

$category = isset($_GET['category']) ? $conn->real_escape_string($_GET['category']) : null;
$subcategory = isset($_GET['subcategory']) ? $conn->real_escape_string($_GET['subcategory']) : null;

$labels = [];
$stock = [];
$margins = [];

if ($category === 'beverage' || !$category) {
    $query = "SELECT 
                beverage_name AS item_name,
                quantity,
                buying_price,
                selling_price
              FROM beverages";
    
    if ($subcategory) {
        $query .= " WHERE cat = '$subcategory'";
    }
    
    $query .= " ORDER BY quantity DESC LIMIT 10";
    
    $result = $conn->query($query);
    
    while ($row = $result->fetch_assoc()) {
        $labels[] = $row['item_name'];
        $stock[] = floatval($row['quantity']);
        $margin = (($row['selling_price'] - $row['buying_price']) / $row['buying_price']) * 100;
        $margins[] = floatval($margin);
    }
}

if (($category === 'food' || !$category) && empty($labels)) {
    $query = "SELECT 
                name AS item_name,
                cost_price AS buying_price,
                price AS selling_price
              FROM food";
    
    if ($subcategory) {
        $query .= " WHERE food_group = '$subcategory'";
    }
    
    $query .= " ORDER BY price DESC LIMIT 10";
    
    $result = $conn->query($query);
    
    while ($row = $result->fetch_assoc()) {
        $labels[] = $row['item_name'];
        $stock[] = 0; // Food quantity not tracked in this example
        $margin = (($row['selling_price'] - $row['buying_price']) / $row['buying_price']) * 100;
        $margins[] = floatval($margin);
    }
}

$response = [
    'labels' => $labels,
    'stock' => $stock,
    'margins' => $margins
];

header('Content-Type: application/json');
echo json_encode($response);
?>