class OrderItem < ApplicationRecord
  self.primary_key = "order_items_id"

  #primary key - need to be unique
  before_create :generate_custom_id

  #Associations
  belongs_to :order, autosave: true

  #Validation
  validates_presence_of :item_code, :item_name, :qty
  validates :qty, numericality: { :greater_than => 0 }
  validates_associated :order

  #This Method - handle how items is added into order
  # order_item : {
  #     order_item_code : "",
  #     item_instance_code : "",
  #     quantity : 0,
  #     option_values : [],
  #     sub_order_items : [],
  # }
  def self.processs_item (item_code, menu_name, alt_name, account_id, qty,price, options, set_menu_items, order_id, item_order_by)

    orderitem = OrderItem.create do |oitem|
      oitem.order_id = order_id
      oitem.item_code = item_code
      oitem.item_name = menu_name
      oitem.alt_name = alt_name
      oitem.account_id = account_id
      oitem.qty       = qty
      oitem.price   = price
      oitem.options     = options
      oitem.set_menu_items = set_menu_items
      oitem.item_order_by = item_order_by #person who order this. * If emenu - it will be login user on the app
    end

    #logger.debug orderitem.to_yml
    orderitem.save!
  end

  #Origami : Cashier : to show order items details
  def self.get_order_items_details(booking_id)
    # booking_orders = BookingOrder.where("booking_id=?",booking.booking_id)
    # if booking_orders
    #    booking_orders.each do |book_order|
    #     order_details = OrderItem.select("order_items.item_name,order_items.qty,order_items.price,(order_items.qty*order_items.price) as total_price")
    #        .joins("left join orders on orders.order_id = order_items.order_id")
    #        .where("order_items.order_id=?",book_order.order)
    #     return order_details
    #   end
    # else
    #   return false
    # end

    order_details = OrderItem.select("order_items.item_name,order_items.qty,order_items.price,(order_items.qty*order_items.price) as total_price")
           .joins("left join orders on orders.order_id = order_items.order_id")
           .joins("left join booking_orders on booking_orders.order_id = order_items.order_id")
           .joins("left join bookings on bookings.booking_id = booking_orders.booking_id")
           .where("bookings.booking_id=?",booking_id)

    return order_details
  end

  private
  def generate_custom_id
    self.order_items_id = SeedGenerator.generate_id(self.class.name, "ODI")
  end
end
