class StockJournal < ApplicationRecord
  belongs_to :shop
  SALES_TRANS = "sale"
  ORDER_TRANS = "order"
  STOCK_CHECK_TRANS = "stock_check"

  scope :created_at_between, -> (from, to) { where(created_at: from..to)}

  def self.add_to_journal(item_instance_code, qty, old_balance, stock_message, inventory_definition, trans_ref, trans_type) # item => saleObj | balance => Stock journal

    balance = calculate_balance(old_balance, qty)

    if balance < old_balance
      credit = 0
      debit = qty.abs
    else
      credit = qty.abs
      debit = 0
    end

    journal = StockJournal.create(
      item_code: item_instance_code,
      credit: credit,
      debit: debit,
      balance: balance,
      inventory_definition_id: inventory_definition.id,
      remark: stock_message,
      trans_ref: trans_ref,
      trans_type: trans_type
    )
  end

  def self.calculate_balance(balance, qty)
    return balance.to_i - qty.to_i
  end

  def self.from_stock_check(item)
    stock_journal = StockJournal.where("item_code=?", item.item_code).order("id DESC").first
    if stock_journal.nil?
      old_blance = 0
      inventory_definition_id = InventoryDefinition.find_by_item_code(item.item_code).id
    else
      old_blance = stock_journal.balance
      inventory_definition_id = stock_journal.inventory_definition_id
    end
    # definition_id = InventoryDefinition.find_by_item_code(item.item_code)
    journal = StockJournal.new
    journal.item_code = item.item_code
    journal.inventory_definition_id = inventory_definition_id
    journal.debit = 0
    journal.credit = item.stock_count
    journal.balance = item.stock_count + old_blance.to_i
    journal.remark = StockJournal::STOCK_CHECK_TRANS
    journal.trans_ref = item.id
    journal.trans_type = StockJournal::STOCK_CHECK_TRANS
    journal.save
  end


  def self.inventory_balances(from,to)
    query = StockJournal.select("mii.item_instance_name as item_instance_name,balance")
          .joins("join menu_item_instances mii on mii.item_instance_code=stock_journals.item_code")
          .group("mii.item_instance_name")
          .order("mii.item_instance_name ASC")
    if !from.nil? && !to.nil?
      query = query.created_at_between(from, to)
    end
  end

  def self.update_stock_journal(item_instance_code,remark)
    product = InventoryDefinition.find_by_item_code(item_instance_code)
    if !product.nil?
      stock = self.where("item_code=?", item_instance_code).order("id DESC").first
      stock.remark = remark
      stock.save
    end
  end

  def self.delete_stock_journal(item_code)
    self.where("item_code=?", item_code).delete_all
  end

end
