class Origami::SalesController < BaseOrigamiController
  def show
    @webview = false
    if check_mobile
      @webview = true
    end


    @tables   = Table.unscope(:order).all.active.order('status desc')
    @rooms    = Room.unscope(:order).all.active.order('status desc')
    @complete = Sale.completed_sale("cashier")
    @orders   = Order.includes("sale_orders").where("DATE_FORMAT(CONVERT_TZ(date, '+00:00', '<%= Time.zone.formatted_offset %>'), '%Y-%m-%d') = ? and status != 'billed' and source != 'quick_service'",Time.current.strftime('%Y-%m-%d')).order('date desc')
    @customers = Customer.pluck("customer_id, name")
    @sale = Sale.find(params[:sale_id])
    @order = SaleOrder.find_by_sale_id(@sale.sale_id).order_id
    @booking = BookingOrder.find_by_order_id(@order).booking_id
    if Booking.find(@booking).dining_facility_id.to_i>0
      @table_id = Booking.find(@booking).dining_facility_id
      @dining  = DiningFacility.find(@table_id)
    else
      @table_id = nil
      @dining  = nil
    end
  end

  def add_to_existing_invoice
    dining = params[:dining_id]
    sale_id = params[:sale_id]
    tax_type = params[:tax_type]

    Sale.transaction do
      table = DiningFacility.find(dining)
      booking = table.current_checkin_booking

      sale = Sale.find(sale_id)
      existing = sale.booking

      sale.sale_items << booking.order_items.to_sale_items
      sale.orders << booking.orders

      sale.compute(booking.orders[0].source, tax_type)

      type = "ADD_TO_EXISTING"
      receipt_no = sale.receipt_no
      action_by = current_user.name
      order_ids = booking.orders.map(&:order_id)

      remark = "#{action_by} add to existing order #{order_ids.to_s} to Receipt No=>#{receipt_no} in #{table.name}"
      sale_audit = SaleAudit.record_audit_sale(sale_id, remark, action_by, type)

      booking.orders.update_all(status: "billed")
      booking.order_items.update_all(order_item_status: "billed")
      BookingOrder.where(booking_id: booking.booking_id).update_all(booking_id: existing)

      booking.booking_status = "moved"
      booking.save
    end
  end

end
