class Origami::SplitBillController < BaseOrigamiController
	authorize_resource :class => false

	def index
		@webview = false
	    if check_mobile
	      @webview = true
	    end

		dining_id = params[:dining_id]
		@cashier_type = params[:type]
		@table = DiningFacility.find(dining_id)
		@booking = @table.get_booking
		@orders = Array.new
		@order_items = Array.new
		@sale_data = Array.new
		@current_user = current_user

		@sale_data = @table.current_sales

		if @booking
			@orders = @booking.orders
			@order = @orders[0]
			@order_items = []
			order_items = []

			@booking.order_items.each do |item|
				if item.set_menu_items.present?
					set_menu_items = JSON.parse(item.set_menu_items)
					item.set_menu_items = set_menu_items.map { |x| x["item_instance_name"] }
					item.price = item.price + set_menu_items.inject(0.0) { |sum, x| sum + x["item_instance_name"].to_f }
				end

				@order_items += item.qty.to_i.times.map { i = item.as_json; i["qty"] = 1; order_items << i; { item.order_id => i } }
			end

			@order_items << { 'all_order' => order_items }
    else
      @booking = nil
    end
	end

	def create
		cashier_type = params[:cashier_type]
		dining_id = params[:dining_id]
		order_ids = params[:order_ids]
		arr_order_ids = JSON.parse(params[:arr_order_ids]) if params[:arr_order_ids].present?
		orders = JSON.parse(params[:orders]) if params[:orders].present?
		order_items = JSON.parse(params[:order_items]) if params[:order_items].present?

		if !ShiftSale.current_shift.nil?
    	#create Bill by Booking ID
			table = DiningFacility.find_by(id: params[:dining_id]) if params[:dining_id].present?

			Booking.transaction do
	    	if params[:booking_id].present?
	        booking = Booking.find(params[:booking_id])
				else
					type = "TableBooking" if params[:type] == "Table"
					type ||= "RoomBooking"

					split_orders = []
					new_order = nil

					booking = Booking.create({:dining_facility_id => table.id, :type => type, :checkin_at => Time.current, :checkin_by =>  current_user.name, :booking_status => "assign" })

					if orders.present?
						split_orders += orders.map { |x| x["id"] }
					end

					if order_items.present?
						order_items = order_items.inject([]) do |arr, v|
							v["qty"] = v["qty"].to_i
							if i = arr.find { |x| x["id"] == v["id"] }
								i["qty"] = i["qty"] + v["qty"]
							else
								arr << v
							end
							arr
						end

						Order.includes(:order_items).where(order_id: order_ids).each do |order|
							if order.order_items.any? { |x| order_items.none? { |y| x.order_items_id == y["id"] && x.qty == y["qty"] } }
								new_order ||= Order.create({ source: "cashier", order_type: order.order_type, customer_id: order.customer_id, item_count: order_items.length, waiters: current_user.name })
								order.order_items.each do |order_item|
									if split_item = order_items.find { |x| x["id"] == order_item.order_items_id }
										if split_item["qty"] == order_item.qty
											new_order.order_items << order_item
										else
											order_item.qty = order_item.qty - split_item["qty"]
											order_item.save
											order_item_dup = order_item.dup
											order_item_dup.qty = split_item["qty"]
											new_order.order_items << order_item_dup
										end
									end
								end
							else
								split_orders << order
							end
						end
					end

					if new_order.present?
						booking.orders << new_order
					end

					if split_orders.present?
						BookingOrder.where(order_id: split_orders).update_all(booking_id: booking.booking_id)
					end
	    	end

				if booking.sale.nil?
					sale_data = Sale.generate_invoice_from_booking(booking, current_user, current_user, cashier_type, params[:current_checkin_induties_count])
					Promotion.promo_activate(sale_data)
				end

				if ENV["SERVER_MODE"] == 'cloud'
					from = request.subdomain  + "." + request.domain
				else
					from = ""
				end

				ActionCable.server.broadcast "bill_channel", table: table, from:from

				render :json => { status: true }
			end
    else
      render :json => { status: false, error_message: 'No Current Open Shift!'}
    end
	end

	def update_sale
		sale = Sale.find(params[:sale_id])
		sale.equal_persons = params[:total_customer].to_i
		sale.save!

		render :json => { status: true }
	end
end
