class CardSaleTran < ApplicationRecord

	belongs_to :sale

    def self.search(filter,from,to,payment_type,status_type)
	    if filter.blank?
	        keyword = ''
	    else
	        keyword = " s.cashier_name LIKE ? OR c.name LIKE ? OR s.sale_id LIKE ?","%#{filter}%","%#{filter}%","%#{filter}%"
	    end

	    if payment_type.blank?
	    	payment = ''
	    else
	    	payment = " app LIKE '#{payment_type}'"
	    end

	    if status_type.blank?
	    	status = ''
	    else
	    	status = " status = '#{status_type}'"
	    end

	    if from.present? && to.present?

	        # cardSale = CardSaleTran.where("DATE_FORMAT(req_date,'%Y-%m-%d') >= ?" + " AND DATE_FORMAT(req_date,'%Y-%m-%d') <= ? and status IS NULL ", from,to)
	        from_date = from.strftime("%Y-%m-%d")
	        to_date = to.strftime("%Y-%m-%d")
	        query  = CardSaleTran.joins("Join sales s ON s.sale_id = card_sale_trans.sale_id"+
	        								" JOIN customers c ON c.customer_id = s.customer_id")
	        cardSale = query.where("req_date >= ? and req_date <= ? and status is not null",from_date,to_date)
	        query1 = cardSale.where(keyword)
	        query2 = query1.where(payment)
	        query3 = query2.where(status)

	    end
    end

    def self.searchReport(from,to,payment_type,shift_sale_range,shift)

	    if payment_type.blank?
	    	payment = ''
	    else
	    	payment = " app LIKE '#{payment_type}'"	
	    end

	    if from.present? && to.present?

	        query  = CardSaleTran.joins("Join sales s ON s.sale_id = card_sale_trans.sale_id"+
	        								" JOIN customers c ON c.customer_id = s.customer_id")
	        cardSale = query.where("DATE_FORMAT(req_date,'%Y-%m-%d') >= ? and DATE_FORMAT(req_date,'%Y-%m-%d') <= ? and status = 'Approved'",from,to)

	        if shift.present?
	        	query1 = cardSale.where("s.shift_sale_id in (?)", shift.to_a)
	        elsif shift_sale_range.present?	
	        	query1 = cardSale.where("s.shift_sale_id in (?)",shift_sale_range.to_a)
	        else
	        	query1 = cardSale.where("DATE_FORMAT(s.receipt_date,'%Y-%m-%d') between ? and ?",from,to)
	        end
	        query2 = query1.where(payment)

	    end
    end

    def self.get_by_shift_sale_by_card(from,to,status)
	  	query = ShiftSale.select("shift_sales.id ,shift_started_at AS opening_date,
	                          shift_closed_at As closing_date,")
	                          .order("shift_sales.id DESC")
	  	return query = query.where("shift_sales.shift_started_at >= ?" , from)
	  	byebug
	end

end