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'")}
  scope :today, -> {where("created_at >= #{Time.now.utc}")}

  def self.sync_booking_records(bookings)
    if !bookings.nil?
      bookings.each do |b|
        booking = TableBooking.find_by_booking_id(b['booking_id'])
        # unless TableBooking.exists?(b['booking_id'])
        if booking.nil?
          booking = TableBooking.new
        end
        booking.booking_id = b['booking_id']
        booking.dining_facility_id = b['dining_facility_id']
        # booking.type = b['type']
        booking.checkin_at = b['checkin_at']
        booking.checkin_by = b['checkin_by']
        booking.checkout_at = b['checkout_at']
        booking.checkout_by = b['checkout_by']
        booking.reserved_at = b['reserved_at']
        booking.reserved_by = b['reserved_by']
        booking.booking_status = b['booking_status']
        booking.sale_id = b['sale_id']
        booking.customer_id = b['customer_id']
        booking.save
      end
      puts '....... Booking sync completed ......'
    end
  end

  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}' OR df.name LIKE ?","%#{filter}%","%#{filter}%","%#{filter}%","%#{filter}%","%#{filter}%"
    end

    if from.present? && to.present?
       booking = Booking.joins(" LEFT JOIN dining_facilities df ON df.id=bookings.dining_facility_id")
              .where("DATE_FORMAT(bookings.created_at,'%d-%m-%Y') >= ?" + " AND DATE_FORMAT(bookings.created_at,'%d-%m-%Y') <= ? and NOT bookings.booking_status = 'void' ", from,to)
       query = booking.where(keyword)
    else
        joins(" LEFT JOIN dining_facilities df ON df.id=bookings.dining_facility_id")
        .where("booking_id LIKE ? OR checkin_by LIKE ? OR booking_status LIKE? OR checkout_by LIKE? OR sale_id ='#{filter}' OR df.name LIKE ?","%#{filter}%","%#{filter}%","%#{filter}%","%#{filter}%","%#{filter}%")
    end
    .order("sale_id DESC")
  end

  def self.get_sync_data(sale_id)
    @orders = Order.select('orders.*')
                   .joins('left join sale_orders on sale_orders.order_id = orders.order_id')
                   .where('sale_orders.sale_id=?', sale_id)

    @order_items = OrderItem.select('order_items.*')
                            .joins('left join sale_orders on sale_orders.order_id = order_items.order_id')
                            .where('sale_orders.sale_id=?', sale_id)

    @assigned_order_items = AssignedOrderItem.select('assigned_order_items.*')
                                             .joins('left join sale_orders on sale_orders.order_id=assigned_order_items.order_id')
                                             .where('sale_orders.sale_id=?', sale_id)

    @bookings = TableBooking.where('sale_id=?', sale_id)

    @sales = Sale.where("sale_id=?", sale_id)

    @sale_items = SaleItem.where("sale_id=?", sale_id)

    @sale_taxes = SaleTax.where("sale_id=?", sale_id)

    @sale_orders = SaleOrder.where("sale_id=?", sale_id)

    @sale_audits = SaleAudit.where("sale_id=?", sale_id)

    @sale_payments = SalePayment.where("sale_id=?", sale_id)

    @shift_sales = ShiftSale.select('shift_sales.*')
                            .joins('left join sales on sales.shift_sale_id = shift_sales.id')
                            .where('sales.sale_id=?', sale_id)

    return @orders, @order_items, @sales, @sale_items, @sale_taxes, @sale_payments, @sale_orders, @sale_audits, @bookings, @assigned_order_items, @shift_sales
  end

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