<?php
require_once('shikanisha.kts.php'); // Include your database connection script

// Set the number of items per page
$itemsPerPage = 10;

// Get the page number from the URL parameter, default to 1 if not set
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;

// Calculate the offset for the SQL query
$offset = ($page - 1) * $itemsPerPage;

// Initialize an array to store lunch items
$lunchItems = [];

// Fetch lunch items from the database with pagination
$query = "SELECT food_id AS product_id, name AS product_name,cat, price AS selling_price, description, image FROM food WHERE category = 'Breakfast' LIMIT $offset, $itemsPerPage";
$result = mysqli_query($conn, $query);

if ($result) {
    // Loop through the result set and add each lunch item to the array
    while ($row = mysqli_fetch_assoc($result)) {
        $lunchItems[] = [
            'name' => $row['product_name'],
            'food_id' => $row['product_id'],
            'price' => $row['selling_price'],
            'description' => $row['description'],
            'cat' => $row['cat'],
            'image' => $row['image']
        ];
    }

    // Get the total number of lunch items for pagination
    $totalItemsQuery = "SELECT COUNT(*) AS total FROM food WHERE category = 'Breakfast'";
    $totalItemsResult = mysqli_query($conn, $totalItemsQuery);
    $totalItemsRow = mysqli_fetch_assoc($totalItemsResult);
    $totalItems = $totalItemsRow['total'];

    // Calculate the total number of pages
    $totalPages = ceil($totalItems / $itemsPerPage);

    // Close the database connection
    mysqli_close($conn);

    // Construct the pagination array
    $pagination = [
        'currentPage' => $page,
        'totalPages' => $totalPages
    ];

    // Encode the array of lunch items and pagination as JSON and output it
    header('Content-Type: application/json');
    echo json_encode(['items' => $lunchItems, 'pagination' => $pagination]);
} else {
    // Handle database query error
    echo json_encode(['error' => 'Failed to fetch lunch items']);
}
?>
