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

		table_bookings = Booking.where("dining_facility_id = #{dining_id} and sale_id IS NOT NULL")
		if !table_bookings.nil?
			table_bookings.each do |table_booking|
				if table_booking.sale.sale_status != 'waste' && table_booking.sale.sale_status != 'spoile'
					@sale_data.push(table_booking.sale)
				end
			end
		end

		if @booking
	      	@booking.booking_orders.each do |booking_order|
	      		arr_order_items = Array.new
	        	@order = Order.find(booking_order.order_id)
		        if (@order.status == "new")
		        	@orders.push(@order)

					@order.order_items.each do |item|
						if !item.set_menu_items.nil?
							instance_item_sets = JSON.parse(item.set_menu_items)
							arr_instance_item_sets = Array.new
							instance_item_sets.each do |instance_item|
							  item_instance_name = MenuItemInstance.find_by_item_instance_code(instance_item["item_instance_code"]).item_instance_name
							  item.price = item.price.to_f + instance_item["price"].to_f
							  arr_instance_item_sets.push(item_instance_name)
							end
							item.set_menu_items = arr_instance_item_sets
						end

						arr_item = Hash.new
						if item.qty.to_i > 1
							i = 1
							while i <= item.qty.to_i do 
								arr_item = {'order_items_id' => item.order_items_id, 
									'order_id' => item.order_id, 
									'order_item_status' => item.order_item_status, 
									'item_order_by' => item.item_order_by,
									'item_code' => item.item_code,
									'item_instance_code' => item.item_instance_code,
									'item_name' => item.item_name,
									'alt_name' => item.alt_name,
									'account_id' => item.account_id,
									'qty' => '1.0',
									'price' => item.price,
									'remark' => item.remark,
									'options' => item.options,
									'set_menu_items' => item.set_menu_items,
									'taxable' => item.taxable,
									'completed_by' => item.completed_by,
									'created_at' => item.created_at,
									'updated_at' => item.updated_at}
								i += 1
								@order_items.push({@order.order_id => arr_item})
								arr_order_items.push(arr_item)
							end
						else
							arr_order_items.push(item)
							@order_items.push({@order.order_id => item})
						end
					end
					@order_items.push({'all_order' => arr_order_items})
		        end
	      	end
	    else
	      @booking = nil
	    end
	end

	def create
		cashier_type = params[:cashier_type]
		order_ids = params[:order_ids]
		arr_order_ids = nil
		if !params[:arr_order_ids].nil?
			arr_order_ids = JSON.parse(params[:arr_order_ids])
		end
		orders = nil
		if !params[:orders].empty? 
			orders = JSON.parse(params[:orders])
		end
		order_items = nil
		if !params[:order_items].empty?
			order_items = JSON.parse(params[:order_items])
		end

		status = false
		if !ShiftSale.current_shift.nil?
	    	#create Bill by Booking ID
	      	table = 0
	    	if !params[:booking_id].empty?
		        booking  = Booking.find(params[:booking_id])
		        # for Multiple Cashier by Zone
		        if booking.dining_facility_id.to_i>0
		        	table = DiningFacility.find(booking.dining_facility_id)
		            cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id)
		        else
		        	table = nil
		        	cashier_zone = nil
		        end

		        # shift_by_terminal = ShiftSale.find_by_cashier_terminal_id_and_shift_closed_at(cashier_zone.cashier_terminal_id,nil)
		        # get_cashier_by_terminal = Employee.find(shift_by_terminal.employee_id)

				if booking
					if booking.sale_id.nil?
					  sale = Sale.new
					  status, sale_id = sale.generate_invoice_from_booking(params[:booking_id], current_user, current_user, cashier_type,params[:current_checkin_induties_count])
					  sale_data = Sale.find_by_sale_id(sale_id)
					else
					  status = true
					  sale_id = booking.sale_id
					  sale_data = Sale.find_by_sale_id(sale_id)
					end
				end
			else
				if params[:type] == "Table"
					type = "TableBooking"
				else
					type = "RoomBooking"
				end

				booking = Booking.create({:dining_facility_id => params[:dining_id],:type => type,
	                                :checkin_at => Time.now.utc, :checkin_by =>  current_user.name,
	                                :booking_status => "assign" })

				if !orders.nil?
					orders.each do |order|
						BookingOrder.find_by_order_id(order["id"]).delete
						BookingOrder.create({:booking_id => booking.booking_id, :order_id => order["id"]})
					end
				elsif !order_items.nil?
					order_item_count = 0
					order_id_count = 0
					order_id = nil

					arr_order_ids.each do |order|
						order.each do |odr|
							data = Order.find(odr[0])
							if data.order_items.count == odr[1]
								order_id = odr[0]
								order_id_count += 1
							else
								order_item_count += 1
							end
						end
					end

					# puts order_id
					# puts order_ids.count
					# puts order_id_count
					# puts order_items.count
					# puts order_item_count

					if !order_id.nil?
						if order_id_count > 1
							puts "order_id_count > 1"

							updated_order_id = Array.new
							arr_order_ids.each do |order|
								order.each do |odr|
									data = Order.find(odr[0])
									if data.order_items.count != odr[1]
										updated_order_id.push(odr[0])
									end
								end
							end

							# puts "updated_order_id"
							# puts updated_order_id

							if !updated_order_id.empty?
								order_ids.each do |odr_id|
									unless updated_order_id.include?(odr_id)
										BookingOrder.find_by_order_id(odr_id).delete
										BookingOrder.create({:booking_id => booking.booking_id, :order_id => odr_id})
									end
								end

								order_items.each do |order_item|
									if updated_order_id.include?(order_item["order_id"])
								       	update_order_item(order_id, order_item)
								    end
							    end
							else
								order_ids.each do |odr_id|
									new_order_status = true
									order_items.each do |order_item|
										orderItem = OrderItem.find_by_order_id(odr_id)
										if !orderItem.nil?
											if order_item["id"] == orderItem.order_items_id
												if orderItem.qty.to_f != order_item['qty'].to_f
													new_order_status = false
												end
											end
										end
								    end

								    # puts new_order_status

									if new_order_status
								    	BookingOrder.find_by_order_id(odr_id).delete
										BookingOrder.create({:booking_id => booking.booking_id, :order_id => odr_id})
								    else
								    	customer = Customer.find(params[:customer_id])
										order_type = "dine_in"
										if !customer.nil?
											if customer.customer_type == "Takeaway"
												order_type = "takeaway"
											elsif customer.customer_type == "Delivery"
												order_type = "delivery"
											end
										end

										# begin
										order = create_order(params,order_type,order_items.count,current_user)

									    BookingOrder.create({:booking_id => booking.booking_id, :order_id => order.order_id})

									    order_items.each do |order_item|
									    	update_order_item(order.order_id, order_item)
									    end
								    end
								end
							end
						else
							# puts "order_id_count < 1"
							new_order_status = true
							order_items.each do |order_item|
								orderItem = OrderItem.find(order_item["id"])
								if !orderItem.nil?
									if order_item["id"] == orderItem.order_items_id
										if orderItem.qty.to_f != order_item['qty'].to_f
											new_order_status = false
										end
									end
								end
						    end

						    # puts new_order_status

						    if new_order_status
						    	BookingOrder.find_by_order_id(order_id).delete
								BookingOrder.create({:booking_id => booking.booking_id, :order_id => order_id})
						    	order_items.each do |order_item|
									update_order_item(order_id, order_item)
							    end
						    else
						    	customer = Customer.find(params[:customer_id])
								order_type = "dine_in"
								if !customer.nil?
									if customer.customer_type == "Takeaway"
										order_type = "takeaway"
									elsif customer.customer_type == "Delivery"
										order_type = "delivery"
									end
								end

								# begin
								order = create_order(params,order_type,order_items.count,current_user)

							    BookingOrder.create({:booking_id => booking.booking_id, :order_id => order.order_id})

							    order_items.each do |order_item|
							    	update_order_item(order.order_id, order_item)
							    end
						    end
						end
					else
						if order_ids.count == 1 && order_item_count == 1
							if order_id_count == 0 
								customer = Customer.find(params[:customer_id])
								order_type = "dine_in"
								if !customer.nil?
									if customer.customer_type == "Takeaway"
										order_type = "takeaway"
									elsif customer.customer_type == "Delivery"
										order_type = "delivery"
									end
								end

								# begin
								order = create_order(params,order_type,order_items.count,current_user)

							    BookingOrder.create({:booking_id => booking.booking_id, :order_id => order.order_id})

							    order_items.each do |order_item|
							    	update_order_item(order.order_id, order_item)
							    end
							else
								BookingOrder.find_by_order_id(order_ids[0]).delete
								BookingOrder.create({:booking_id => booking.booking_id, :order_id => order_ids[0]})
								order_items.each do |order_item|
									update_order_item(order_ids[0], order_item)
							    end
						    end
						else
							customer = Customer.find(params[:customer_id])
							order_type = "dine_in"
							if !customer.nil?
								if customer.customer_type == "Takeaway"
									order_type = "takeaway"
								elsif customer.customer_type == "Delivery"
									order_type = "delivery"
								end
							end

							# begin
							order = create_order(params,order_type,order_items.count,current_user)

						    BookingOrder.create({:booking_id => booking.booking_id, :order_id => order.order_id})

						    order_items.each do |order_item|
						    	update_order_item(order.order_id, order_item)
						    end
						end
					end
				end

				sale = Sale.new
				status, sale_id = sale.generate_invoice_from_booking(booking.booking_id, current_user, current_user, cashier_type ,params[:current_checkin_induties_count])
	    	end

			Promotion.promo_activate(sale)
			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: status }
	    else
	      render :json => { status: false, error_message: 'No Current Open Shift!'}
	    end
	end

	def create_order(params,order_type,items_count,current_user)
		order = Order.new
	    order.source = "cashier"
	    order.order_type = order_type
	    order.customer_id = params[:customer_id] == ""? "CUS-000000000001" : params[:customer_id] # for no customer id from mobile
	    order.item_count = items_count
	    order.status = "new"
	    order.table_id = params[:dining_id]  # this is dining facilities's id
	    order.waiters = current_user.name
	    order.employee_name = current_user.name
	    order.guest_info = nil
	    order.save!

	    return order
	end

	def update_order_item(order_id, order_item)
		orderItem = OrderItem.find(order_item["id"])
    	if orderItem.qty.to_f != order_item['qty'].to_f
    		set_menu_items_obj = Array.new
    		if !orderItem.set_menu_items.nil?
	    		instance_item_sets = JSON.parse(orderItem.set_menu_items)
	    		instance_item_sets.each_with_index do |instance_item, instance_index|
	    			instance_item_sets[instance_index]["quantity"] = (instance_item["quantity"].to_i - order_item['qty'].to_i).to_s
	    			set_menu_items_obj.push({'item_instance_code' => instance_item["item_instance_code"], 'quantity' => order_item['qty'].to_i, 'price' => instance_item["price"]})
	    		end
	    		orderItem.set_menu_items = instance_item_sets.to_json
	    	end

    		same_order = OrderItem.find_by_order_id(order_id)
    		if same_order.nil?
	    		OrderItem.processs_item(orderItem.item_code, 
	    			orderItem.item_instance_code, 
	    			orderItem.item_name, 
	    			orderItem.alt_name, 
	    			orderItem.account_id,
					order_item['qty'],
					orderItem.price, 
					orderItem.options, 
					set_menu_items_obj.to_json, 
					order_id,
					orderItem.item_order_by, 
					orderItem.taxable)
	    	else
	    		same_order.qty = same_order.qty.to_f + order_item['qty'].to_f
	    		same_order.set_menu_items = set_menu_items_obj.to_json
	    		same_order.save
	    	end
	    	orderItem.qty = orderItem.qty.to_f - order_item['qty'].to_f
    	else
	    	orderItem.order_id = order_id
	    end
    	orderItem.save!
	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

	#Shop Name in Navbor
	helper_method :shop_detail
	def shop_detail
		@shop = Shop.first
	end

end
