class Settings::OutOfStockController < ApplicationController
  def index
    @menu_items = MenuItem.joins(:menu_item_instances).where(menu_item_instances: {is_out_of_stock: true}).select('menu_item_instances.id, menu_item_instances.item_instance_code, menu_item_instances.item_instance_name, menu_items.name, menu_item_instances.is_out_of_stock, menu_item_instances.item_attributes')
  end

  def show
  end

  def new
    @menus    = Menu.order('created_at asc')
    @menu     = MenuCategory.active.where("menu_id =#{@menus[0].id}").order('order_by asc')
  end

  def update
    items_arr = []
    JSON.parse(params[:item_instance_code]).each { |i|
      i["item_instance_code"] = i["item_instance_code"].downcase.to_s
      items = i["item_instance_code"]
      items_arr.push(items)
     }

    item_instance = MenuItemInstance.where(item_instance_code: [items_arr])
    date = Time.current

    unless item_instance.nil?
      if !item_instance.first.is_out_of_stock?
        item_instance.update(is_out_of_stock: true)
        items_arr.each do |i|
          item_code = MenuItemInstance.find_by(item_instance_code: i).menu_item.item_code
          # OutOfStock.create_out_of_stock(date,i)
          ActionCable.server.broadcast "out_of_stock_channel", item_code: item_code, item_instance_code: i, status: true
        end
      elsif item_instance.first.is_out_of_stock?
        item_instance.update(is_out_of_stock: false)
      end
    end

    result = {:status=> true, :message => "Out of Stock was created successfully",:data=> item_instance}
    render :json => result.to_json
  end

  def destroy
    item_instance = MenuItemInstance.find_by_id(params[:id])
    unless item_instance.nil?
      item_instance.update(is_out_of_stock: false)
      
      item_code = item_instance.menu_item.item_code
      ActionCable.server.broadcast "out_of_stock_channel", item_code: item_code, item_instance_code: item_instance.item_instance_code, status: false
      flash[:message] = 'Out of stock was successfully destroyed.'
      render :json => {:status=> "Success", :url => settings_out_of_stock_index_url }.to_json
    end
  end

  def reset_all
    item_instance = MenuItemInstance.where(is_out_of_stock: true)
    unless item_instance.nil?
      item_instance.update(is_out_of_stock: false)
      item_instance.each do |i|
        item_code = i.menu_item.item_code
        ActionCable.server.broadcast "out_of_stock_channel", item_code: item_code, item_instance_code: i.item_instance_code, status: false
      end
      flash[:message] = 'Out of stock was successfully destroyed.'
      render :json => {:status=> "Success", :url => settings_out_of_stock_index_url }.to_json
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_menu_item_instance
      @item_instance = MenuItemInstance.find_by_item_instance_code(params[:item_code])
    end
end
