
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

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