<?php
require_once '../db.php';


$sql = "SELECT
          c.id AS menu_category_id,
          c.name AS menu_category_name,
          c.slug AS menu_category_slug,
          i.*
        FROM menu_categories c
        LEFT JOIN menu_items i ON i.category_id = c.id
        ORDER BY c.id ASC, i.id ASC";

$result = $conn->query($sql);

$categories = [];
$categoryMap = [];

while ($row = $result->fetch_assoc()) {
  $categoryId = $row['menu_category_id'];

  if (!isset($categoryMap[$categoryId])) {
    $categories[] = [
      "id" => $categoryId,
      "name" => $row['menu_category_name'],
      "slug" => $row['menu_category_slug'],
      "items" => []
    ];
    $categoryMap[$categoryId] = count($categories) - 1;
  }

  if ($row['id'] !== null) {
    $item = $row;
    unset($item['menu_category_id'], $item['menu_category_name'], $item['menu_category_slug']);
    $categories[$categoryMap[$categoryId]]['items'][] = $item;
  }
}

echo json_encode($categories);
