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('created_at desc').take
     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)
    end
    if item_code.present?
      transaction = transaction.where(item_code: item_code)
    end
    transaction
  end
end
