<?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;
$availability = isset($_GET['availability']) ? intval($_GET['availability']) : null;

$data = [];

if ($category === 'beverage') {
    $query = "SELECT 
                beverage_name AS item_name,
                category,
                cat AS subcategory,
                quantity,
                buying_price,
                selling_price
              FROM beverages
              WHERE 1=1";
    
    if ($subcategory) {
        $query .= " AND cat = '$subcategory'";
    }
    
    if ($availability === 1) {
        $query .= " AND quantity > 0";
    } elseif ($availability === 0) {
        $query .= " AND quantity <= 0";
    }
    
    $result = $conn->query($query);
    
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
} elseif ($category === 'food') {
    $query = "SELECT 
                name AS item_name,
                category,
                food_group AS subcategory,
                price AS selling_price,
                cost_price AS buying_price,
                -- Quantity would need to be tracked in another table
                0 AS quantity
              FROM food
              WHERE 1=1";
    
    if ($subcategory) {
        $query .= " AND food_group = '$subcategory'";
    }
    
    $result = $conn->query($query);
    
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
} else {
    // Get both beverages and food
    $queryBeverages = "SELECT 
                        beverage_name AS item_name,
                        'beverage' AS category,
                        cat AS subcategory,
                        quantity,
                        buying_price,
                        selling_price
                      FROM beverages";
    
    $resultBeverages = $conn->query($queryBeverages);
    
    while ($row = $resultBeverages->fetch_assoc()) {
        $data[] = $row;
    }
    
    $queryFood = "SELECT 
                    name AS item_name,
                    'food' AS category,
                    food_group AS subcategory,
                    0 AS quantity,
                    cost_price AS buying_price,
                    price AS selling_price
                  FROM food";
    
    $resultFood = $conn->query($queryFood);
    
    while ($row = $resultFood->fetch_assoc()) {
        $data[] = $row;
    }
}

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