class Booking < ApplicationRecord
  self.primary_key = "booking_id"

  #primary key - need to be unique
  before_create :generate_custom_id

  belongs_to :dining_facility, :optional => true
  belongs_to :sale, :optional => true
  has_many :booking_orders
  has_many :orders, :through => :booking_orders
  scope :active, -> {where("booking_status != 'moved'")}

  def self.update_dining_facility(booking_arr, newd, old)
    table = DiningFacility.find(newd)
    exist = table.get_booking

    if exist
      # order exists
      booking_arr.each do |booking|
        booking.dining_facility_id = newd
        booking.booking_status = 'moved'
        booking.save
        booking.booking_orders.each do |bo|
          bo.booking_id = exist.booking_id
          bo.save
        end
      end
    else
      # new table
      booking_arr.each do |booking|
        booking.dining_facility_id = newd
        booking.save
      end
    end

     new_dining = DiningFacility.find(newd)
     new_dining.make_occupied
     old_dining = DiningFacility.find(old)
     old_dining.make_available

     return new_dining.type
  end

  def self.search(filter,from,to)
    if filter.blank?
        keyword = ''
    else
        keyword = "booking_id LIKE ? OR checkin_by LIKE ? OR booking_status LIKE? OR checkout_by LIKE? OR sale_id ='#{filter}'","%#{filter}%","%#{filter}%","%#{filter}%","%#{filter}%"
    end

    if from.present? && to.present?
       booking = Booking.where("DATE_FORMAT(created_at,'%d-%m-%Y') >= ?" + " AND DATE_FORMAT(created_at,'%d-%m-%Y') <= ? and NOT booking_status = 'void' ", from,to)
       query = booking.where(keyword)
    else
        where("booking_id LIKE ? OR checkin_by LIKE ? OR booking_status LIKE? OR checkout_by LIKE? OR sale_id ='#{filter}'","%#{filter}%","%#{filter}%","%#{filter}%","%#{filter}%")
    end

  end

  private
  def generate_custom_id
    self.booking_id = SeedGenerator.generate_id(self.class.name, "BKI")
  end
end
