<?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 Tots items
$totsItems = [];

// Fetch Tots items from the database with pagination
$query = "SELECT 
    t.tot_id AS food_id,
    t.name AS name,
    t.price AS price,
    b.image_location AS image,
    b.description AS description,
    'Tot' AS cat  -- Adding 'Tots' as the category column
FROM 
    tots t
JOIN 
    (SELECT DISTINCT tot_id, image_location, description FROM beverages) b 
    ON t.tot_id = b.tot_id LIMIT $offset, $itemsPerPage";
$result = mysqli_query($conn, $query);

if ($result) {
    // Loop through the result set and add each Tots item to the array
    while ($row = mysqli_fetch_assoc($result)) {
        $totsItems[] = [
            'name' => $row['name'],
            'food_id' => $row['food_id'],
            'price' => $row['price'],
            'description' => $row['description'],
            'image' => $row['image'],
            'cat' => $row['cat'] // Include the category in the array
        ];
    }

    // Get the total number of Tots items for pagination
    $totalItemsQuery = "SELECT COUNT(*) AS products FROM tots";
    $totalItemsResult = mysqli_query($conn, $totalItemsQuery);
    $totalItemsRow = mysqli_fetch_assoc($totalItemsResult);
    $totalItems = $totalItemsRow['products'];

    // 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 Tots items and pagination as JSON and output it
    header('Content-Type: application/json');
    echo json_encode(['items' => $totsItems, 'pagination' => $pagination]);
} else {
    // Handle database query error
    echo json_encode(['error' => 'Failed to fetch Tots items']);
}
?>
