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_one  :cashier_terminal_by_dining_facility, through: :dining_facility, source: :cashier_terminal
  has_one  :current_shift_by_dining_facility, through: :dining_facility, source: :current_shift
  has_many :booking_orders
  has_many :orders, :through => :booking_orders
  has_many :order_items, :through => :orders do
    def to_sale_items
      sale_items = []
      proxy_association.load_target.select(&:order_items_id).each do |order_item|
        menu_category = order_item.menu_category || OpenStruct.new(name: 'Product', code: '') #get menu category for menu items
        alt_name = order_item.alt_name.present? ? order_item.alt_name : '-'
        sale_items << SaleItem.new({
            menu_category_name: menu_category.name,
            menu_category_code: menu_category.code,
            product_name:       order_item.item_name,
            product_code:       order_item.item_code,
            product_alt_name:   alt_name,
            account_id:         order_item.account_id,
            is_taxable:         order_item.taxable,
            item_instance_code: order_item.item_instance_code,
            qty:                order_item.qty,
            unit_price:         order_item.price,
            price:              order_item.qty * order_item.price,
            taxable_price:      order_item.qty * order_item.price,
            status:             order_item.remark
        })
        if order_item.set_menu_items
          JSON.parse(order_item.set_menu_items).each do |item|
            instance  = MenuItemInstance.find_by_item_instance_code(item["item_instance_code"])
            menu_item = instance.menu_item
            menu_category = menu_item.menu_category #get menu category for menu items
            alt_name = menu_item.alt_name.present? ? menu_item.alt_name : '-'
            puts alt_name
            sale_items << SaleItem.new({
              menu_category_name: menu_category.name,
              menu_category_code: menu_category.code,
              product_name:       instance.item_instance_name,
              product_code:       menu_item.item_code,
              product_alt_name:   alt_name,
              account_id:         menu_item.account_id,
              is_taxable:         menu_item.taxable,
              item_instance_code: item["item_instance_code"],
              qty:                item["quantity"],
              unit_price:         item["price"],
              price:              item["quantity"].to_f * item["price"].to_f,
              taxable_price:      item["quantity"].to_f * item["price"].to_f
            })
          end
      end
    end
      sale_items
    end
  end

  scope :active, -> { where('booking_status != ?', 'moved') }
  scope :today, -> { where('created_at >= ?', Time.current) }
  scope :assign, -> { where(booking_status: 'assign') }

  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("bookings.created_at BETWEEN ? AND ? 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

  def self.get_booking_id(order_no)
    return BookingOrder.where(order_id: order_no).first.booking_id
  end

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