0) { $parent = queryOne("SELECT ParentCategoryID FROM Categories WHERE ID = ?", [$parentCategoryID]); if (!$parent) { jsonResponse(['OK' => false, 'ERROR' => 'invalid_parent', 'MESSAGE' => 'Parent category not found']); } if ((int) $parent['ParentCategoryID'] > 0) { jsonResponse(['OK' => false, 'ERROR' => 'nesting_too_deep', 'MESSAGE' => 'Subcategories cannot have their own subcategories (max 2 levels)']); } } if ($categoryID > 0) { // Update existing category queryTimed(" UPDATE Categories SET Name = ?, SortOrder = ?, OrderTypes = ?, ParentCategoryID = ?, ScheduleStart = ?, ScheduleEnd = ?, ScheduleDays = ? WHERE ID = ? ", [$name, $sortOrder, $orderTypes, $parentCategoryID, $scheduleStart, $scheduleEnd, $scheduleDays, $categoryID]); jsonResponse(['OK' => true, 'CategoryID' => $categoryID, 'MESSAGE' => 'Category updated']); } elseif ($businessID > 0 && strlen($name) > 0) { // Insert new category queryTimed(" INSERT INTO Categories (BusinessID, Name, SortOrder, OrderTypes, ParentCategoryID, ScheduleStart, ScheduleEnd, ScheduleDays, AddedOn) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW()) ", [$businessID, $name, $sortOrder, $orderTypes, $parentCategoryID, $scheduleStart, $scheduleEnd, $scheduleDays]); $newId = lastInsertId(); jsonResponse(['OK' => true, 'CategoryID' => (int) $newId, 'MESSAGE' => 'Category created']); } else { jsonResponse(['OK' => false, 'ERROR' => 'invalid_params', 'MESSAGE' => 'CategoryID required for update, or BusinessID and Name for insert']); } } catch (Exception $e) { jsonResponse(['OK' => false, 'ERROR' => 'server_error', 'MESSAGE' => $e->getMessage(), 'DETAIL' => '']); }