class MenuCategory < ApplicationRecord
  belongs_to :menu
  has_many :children, :class_name => "MenuCategory", foreign_key: "menu_category_id"
  belongs_to :parent, :class_name => "MenuCategory", foreign_key: "menu_category_id", optional: true
  has_many :menu_items

  validates_presence_of :name, :menu, :code, :order_by

  default_scope { order('order_by asc') }

  def self.destroyCategory(menu_category)
  	# find the sub menu item of current item
    sub_menu_cat = MenuCategory.where("menu_category_id=?",menu_category.id)
    if sub_menu_cat.length != 0
      sub_menu_cat.each do |sub|    
        if destroyCategory(sub)
        end
      end
      # find the items of current menu item
      items = MenuItem.where("menu_category_id=?",menu_category.id)
      items.each do |item|
        abc = MenuItem.deleteRecursive(item)
      end 
      menu_category.destroy
      return true
    else
      items = MenuItem.where("menu_category_id=?",menu_category.id)
      items.each do |item|
        abc = MenuItem.deleteRecursive(item)
      end 
      menu_category.destroy
      return false
    end
  end

end
