class StockCheckItem < ApplicationRecord
  belongs_to :stock_check

  def create(stock_id, item)
    journal_id, balance = StockCheckItem.find_journal(item['sku'])
    remark, different = StockCheckItem.stock_different(item['qty'], balance )
    self.stock_check_id = stock_id
    self.item_code = item['sku']
    self.stock_count = item['qty']
    self.stock_journal_id = journal_id
    self.stock_balance = balance
    self.different = different
    self.remark = remark
    self.save
  end

  def self.find_journal(item_code)
     journal = StockJournal.where('item_code=?', item_code).order("id DESC").first
     if journal
       return journal.id, journal.balance
     else
       return nil, 0
     end
  end

  def self.stock_different(stock_check_qty, journal_balance)
      if stock_check_qty.to_i == journal_balance.to_i
        return 'match', stock_check_qty
      elsif stock_check_qty.to_i > journal_balance.to_i
        return 'missing order item', stock_check_qty.to_i - journal_balance.to_i
      elsif stock_check_qty.to_i < journal_balance.to_i
        return 'missing stock', stock_check_qty.to_i - journal_balance.to_i
      end
  end

  def self.get_transaction(from, to, item_code)
    transaction = all
    if !from.nil? && !to.nil?
      transaction = transaction.where('created_at between ? and ?', from, to).order("item_code asc, different desc")
    end
    if item_code.present?
      transaction = transaction.where(item_code: item_code).order("item_code asc, different desc")
    end
    transaction
  end

  def self.get_items_with_category(id)
  query =   StockCheckItem.select("stock_check_items.*,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("JOIN menu_item_instances mii ON mii.item_instance_code = stock_check_items.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("stock_check_items.stock_check_id=#{id}")
                .group("mi.menu_category_id,stock_check_items.item_code")
                .order("acc.title desc,mi.menu_category_id desc")
  return query
  end
end
