class InventoryDefinition < ApplicationRecord

  scope :active, -> {where(:is_active => true)}

  def self.calculate_product_count(saleObj=nil,saleobj_after_req_bill=nil)
    if !saleObj.nil?
      saleObj.sale_items.each do |item|
        found, inventory_definition = find_product_in_inventory(item)
        if found
          check_balance(item,inventory_definition)
        end
      end
    else
      saleobj_after_req_bill.each do |item|
        found, inventory_definition = find_product_in_inventory(item)
        if found
          check_balance(item,inventory_definition)
        end
      end
    end
  end

  def self.find_product_in_inventory(item)
    product = InventoryDefinition.find_by_item_code(item.item_instance_code)
    if product.nil?
      return false, nil
    else
      stock_check_item = StockCheckItem.find_by_item_code(item.item_instance_code)
      if stock_check_item.nil?
        return false, nil
      else
        return true, product
      end
    end
  end

  def self.check_balance(item,inventory_definition) # item => saleItemOBj
     stock = StockJournal.where('item_code=?', item.item_instance_code).order("id DESC").first 
     unless stock.nil?
       modify_balance(item, stock, inventory_definition)
     else
       StockJournal.add_to_journal(item, 0, "out of stock", inventory_definition)
     end
  end

  def self.modify_balance(item, stock, inventory_definition) #saleitemObj
     if stock.balance.to_i >= item.qty
       puts ">> stock is greater than order qty"
       StockJournal.add_to_journal(item, stock.balance, "ok", inventory_definition)
     else
       puts " << stock is less than order qty"
        data = item
        extra_qty = item.qty.to_i - stock.balance.to_i
        if stock.balance.to_i > 0
          item.qty = stock.balance.to_i
          StockJournal.add_to_journal(item, stock.balance, "ok", inventory_definition)
          data.qty = extra_qty
          StockJournal.add_to_journal(data, 0, "out of stock", inventory_definition)
        else
          StockJournal.add_to_journal(item, stock.balance, "out of stock", inventory_definition)
        end
     end
  end

  def self.search_by_category(cat_id)
     @inventory_definitions =   InventoryDefinition.select("inventory_definitions.*,
                 mi.name as item_name,mii.item_instance_name as instance_name," +
                 "mi.item_code as item_code,mii.item_instance_code as instance_code," +
                "mc.name as menu_category_name,mc.id as menu_category_id ")
                .joins("JOIN menu_item_instances mii ON mii.item_instance_code = inventory_definitions.item_code" +
                     " JOIN menu_items mi ON mi.id = mii.menu_item_id" +
                     " JOIN menu_categories mc ON mc.id = mi.menu_category_id ")
                .where("mc.id=#{cat_id}")
                .group("mi.menu_category_id,inventory_definitions.item_code")
                .order("mi.menu_category_id desc")        
  end

  def self.get_by_category(filter)
    least_stock = "SELECT (CASE WHEN stock_journals.remark != 'out of stock'
                  THEN (SELECT min(balance) FROM stock_journals
                                  WHERE item_code = inventory_definitions.item_code AND remark != 'out of stock'
                                      ORDER BY created_at DESC LIMIT 1) ELSE 0 END)
                                      FROM stock_journals
                                        WHERE stock_journals.item_code = inventory_definitions.item_code
                                      ORDER BY stock_journals.created_at DESC LIMIT 1"

    @inventory_definitions = InventoryDefinition.select("inventory_definitions.*,
                (CASE WHEN sj.credit IS NULL THEN 0 ELSE sj.credit END) as credit,
                (CASE WHEN sj.debit IS NULL THEN 0 ELSE sj.debit END) as debit,
                (#{least_stock}) as balance,"+
                "acc.title as account_name,mi.name as item_name,
                 mii.item_instance_name as instance_name," +
                "mc.name as menu_category_name,mc.id as menu_category_id "
                )
                .joins(" LEFT JOIN stock_journals sj ON sj.inventory_definition_id=inventory_definitions.id")                
                .joins("JOIN menu_item_instances mii ON mii.item_instance_code = inventory_definitions.item_code" +
                     " JOIN menu_items mi ON mi.id = mii.menu_item_id" +
                     " JOIN menu_categories mc ON mc.id = mi.menu_category_id ")
                .joins(" JOIN accounts acc ON acc.id = mi.account_id")
                .where("inventory_definitions.item_code LIKE ? OR inventory_definitions.min_order_level LIKE ? 
                  OR inventory_definitions.max_stock_level LIKE ? OR sj.balance LIKE ? OR mi.name LIKE ? 
                  OR mii.item_instance_name LIKE ? OR mc.name LIKE ?","%#{filter}%","%#{filter}%","%#{filter}%",
                  "%#{filter}%","%#{filter}%","%#{filter}%","%#{filter}%")
                .group("mi.menu_category_id,inventory_definitions.item_code")
                .order("mi.name asc,acc.title desc,mi.menu_category_id desc,balance ASC")
  end

end
