class StockJournal < ApplicationRecord

  SALES_TRANS = "sale"
  STOCK_CHECK_TRANS = "stock_check"

  def self.add_to_journal(item, balance, stock_message, inventory_definition) # item => saleObj | balance => Stock journal
    journal = StockJournal.new
    journal.credit = balance

    balance = calculate_balance(balance, item.qty)
    
    journal.item_code = item.item_instance_code
    journal.inventory_definition_id = inventory_definition.id
    journal.debit = item.qty
    journal.balance = balance
    journal.remark = stock_message
    journal.trans_ref = item.id
    journal.trans_type = StockJournal::SALES_TRANS
    journal.save
  end

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

  def self.from_stock_check(item)
    definition_id = InventoryDefinition.find_by_item_code(item.item_code)
    journal = StockJournal.new
    journal.item_code = item.item_code
    journal.inventory_definition_id = definition_id.id
    journal.debit = 0
    journal.credit = item.stock_count
    journal.balance = item.stock_count
    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(today,from,to,from_time,to_time)
    if !from.nil? && !to.nil?
      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")
            if !from_time.nil? && !to_time.nil?
              query = query.where("DATE_FORMAT(CONVERT_TZ(stock_journals.created_at,'+00:00','+06:30'),'%Y-%m-%d') between '#{from}' and '#{to}'")
            else  
              query = query.where("DATE_FORMAT(CONVERT_TZ(stock_journals.created_at,'+00:00','+06:30'),'%Y-%m-%d') between '#{from}' and '#{to}' and DATE_FORMAT(CONVERT_TZ(stock_journals.created_at,'+00:00','+06:30'),'%H:%M') between '#{from_time}' and '#{to_time}'")
            end
      query = query.group("mii.item_instance_name")
            .order("mii.item_instance_name ASC")
    else
      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")
            .where("DATE_FORMAT(stock_journals.created_at,'%Y-%m-%d') = '#{today}'")
            .group("mii.item_instance_name")
            .order("mii.item_instance_name ASC")
    end
  end

end
