<?php
// Include database connection or any necessary files
require_once('shikanisha.kts.php');

// Default values for pagination
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 10; // Number of items per page

// Define specific categories
$categories = array('Meat', 'Chicken', 'Vegetables', 'Fish', 'Drinks');

// Initialize an array to store fetched items
$allItems = array();

// Loop through each category and fetch all items with pagination
foreach ($categories as $category) {
    // Fetch all items count from the database based on the category
    $countQuery = "SELECT COUNT(*) as total FROM products WHERE food_group = '$category'";
    $countResult = mysqli_query($conn, $countQuery);
    $rowCount = mysqli_fetch_assoc($countResult)['total'];

    // Calculate total pages
    $totalPages = ceil($rowCount / $limit);

    // Calculate offset for pagination
    $offset = ($page - 1) * $limit;

    // Fetch items from the database based on the category with pagination
    $query = "SELECT * FROM products WHERE food_group = '$category' LIMIT $limit OFFSET $offset";
    $result = mysqli_query($conn, $query);

    // Initialize an array to store fetched items for this category
    $categoryItems = array();

    // Check if there are any items fetched for this category
    if (mysqli_num_rows($result) > 0) {
        // Fetch items data from the result set
        while ($row = mysqli_fetch_assoc($result)) {
            $categoryItems[] = $row;
        }
    }

    // Add category items and pagination info to the overall items array
    $allItems[$category]['items'] = $categoryItems;
    $allItems[$category]['total_items'] = $rowCount;
    $allItems[$category]['total_pages'] = $totalPages;
}

// Output the items in JSON format
echo json_encode($allItems);

// Close database connection
mysqli_close($conn);
?>
