
#Description
#total_revenue = sum of all sub-total from sales table
#total_discounts = sum of all discount (overall) from sales tables
#total_taxes = sum of all taxes from sales table (Service + Goverment Tax (commercial_taxes))
#grand_total = total_revenue - total_discounts + total_taxes
#nett_sales = grand_total - commercial_taxes
#cash_sales = cash payment total revenue
#credit_sales = credit payment total revenue
#others_sales = [Sum of each of other payment type --- mpu, jcb, visa,master, rebate, vochure]
#commercial_taxes = Total Goverment tax due
#cash_in = Payment receive
#Cash_out = Payment issues for misc payments

class ShiftSale < ApplicationRecord
  belongs_to :cashier_terminal
  belongs_to :employee, :foreign_key => 'employee_id'

  def self.current_shift
    today_date = DateTime.now.strftime("%Y-%m-%d")
    shift = ShiftSale.where("DATE(shift_started_at)=? and shift_started_at is not null and shift_closed_at is null",today_date).take
    return shift
  end

  def self.current_open_shift(current_user)
    #if current_user
      #find open shift where is open today and is not closed and login by current cashier
      today_date = DateTime.now.strftime("%Y-%m-%d")
      shift = ShiftSale.where("DATE(shift_started_at)=? and shift_started_at is not null and shift_closed_at is null and employee_id = #{current_user}",today_date).take
      return shift
    #end
  end

  def create(opening_balance,cashier_terminal, current_user)
    self.cashier_terminal_id = cashier_terminal
    self.shift_started_at = DateTime.now
    self.employee_id = current_user.id
    self.opening_balance = opening_balance
    self.save
  end

  def update(sale)
    saleobj = Sale.find_by_sale_id(sale)
    cash = saleobj.get_cash_amount
    credit = saleobj.get_credit_amount
    other_sales = saleobj.get_other_amount
    tax = saleobj.get_commerical_tax
    self.total_revenue = self.total_revenue.to_f + saleobj.total_amount.to_f
    self.total_discounts = self.total_discounts + saleobj.total_discount
    self.total_taxes = self.total_taxes + saleobj.total_tax
    self.grand_total = self.grand_total + saleobj.grand_total
    self.cash_sales = self.cash_sales.to_f + cash.to_f
    self.credit_sales = self.credit_sales.to_i + credit.to_f
    self.other_sales = self.other_sales.to_i + other_sales.to_f
    self.nett_sales = self.grand_total.to_i -  self.commercial_taxes
    self.commercial_taxes = self.commercial_taxes.to_i + tax.to_f
    self.save

  end

  def get_closing_balance(shift)
     shiftobj = ShiftSale.find(shift)
     closing_balance = shiftobj.grand_total + shiftobj.cash_in - shiftobj.cash_out + shiftobj.total_cash
     return closing_balance
  end
end
