class InDuty < ApplicationRecord
	belongs_to :dining_facility, foreign_key: 'dinning_id'
	belongs_to :commissioner, foreign_key: 'commissioner_ids'

	def self.get_induty_by_shift(shift_sale_range,shift,from,to,commissioner)
	    ## => left join -> show all sales although no orders
	    if commissioner.blank?
	      commissioner = ''
	    else
	      if commissioner.present?
	        commissioner = " and CAST(in_duties.commissioner_ids AS SIGNED INTEGER) = #{commissioner}"
	      end
	    end

	    query = InDuty.select("in_duties.*,sales.receipt_no, commissioners.name,dining_facilities.name as dining_name")
					.joins(" LEFT JOIN commissioners on commissioners.id = CAST(in_duties.commissioner_ids AS SIGNED INTEGER)")
					.joins(" LEFT JOIN dining_facilities on dining_facilities.id = in_duties.dinning_id")
					.joins(" JOIN sales on sales.sale_id = in_duties.sale_id")
	    if shift.present?
	      query = query.where("sales.shift_sale_id in (?) #{commissioner} and sales.sale_status= 'completed' and sale_payments.payment_amount != 0", shift.to_a)
	              .joins("join sale_payments on sale_payments.sale_id = sales.sale_id")
	              .group("sales.sale_id, in_duties.commissioner_ids")
	    elsif shift_sale_range.present?
	      query = query.where("sales.sale_status='completed' #{commissioner} and sale_payments.payment_amount != 0 and sales.shift_sale_id in (?)",shift_sale_range.to_a)
	              .joins("join sale_payments on sale_payments.sale_id = sales.sale_id")
	              .group("sales.sale_id, in_duties.commissioner_ids")
	    else
	      query = query.where("sales.sale_status='completed' and sales.receipt_date between ? and ? #{commissioner} and sale_payments.payment_amount != 0",from,to)
	              .joins("join sale_payments on sale_payments.sale_id = sales.sale_id")
	              .group("sales.sale_id, in_duties.commissioner_ids")
	    end
	    return query
	end
end
