class Api::CheckInProcessController < Api::ApiController
	# before_action  :authenticate
	def check_in_time
		if params[:dining_id]	
			dining_facility = DiningFacility.find(params[:dining_id])	
			if params[:booking_id]
				data = Booking.where("dining_facility_id = #{params[:dining_id]} AND booking_id = '#{params[:booking_id]}'")
				if data.count > 0
					booking = data[0]
				else
					booking = nil
				end
			else	
				booking = dining_facility.get_current_booking
			end
			if !booking.nil?

				# DiningFacility.check_in_booking(params[:dining_id])

				table = DiningFacility.find(params[:dining_id])
    				#Send to background job for processing
   				if ENV["SERVER_MODE"] == 'cloud'
			        from = request.subdomain  + "." + request.domain
			    else 
			        from = ""
			    end
      			ActionCable.server.broadcast "check_in_booking_channel",table: table,from:from
				check_out_time = nil
				extra_minutes = nil
				alert_time_min = 0
				check_in_time = booking.checkin_at.utc.getlocal.strftime("%Y-%m-%d %H:%M")
				if booking.checkout_at
					check_out_time = booking.checkout_at.utc.getlocal.strftime("%Y-%m-%d %H:%M")
					if booking.reserved_at
						extra_minutes = (booking.checkout_at - booking.reserved_at) / 1.minutes
					end
				end

				lookup_checkout_time = Lookup.collection_of("checkout_alert_time")
				
				if !lookup_checkout_time.empty?
					now = Time.now.utc
			        lookup_checkout_time.each do |checkout_time|
			          arr_time = checkout_time[0].split("-")
			          start_time = Time.parse(arr_time[0].strip).utc.strftime("%H:%M%p")
			          end_time = Time.parse(arr_time[1].strip).utc.strftime("%H:%M%p")
			          if start_time <= now && now <= end_time
			            alert_time_min = checkout_time[1].to_i
			          end
			        end
					render :json => { :status => true, :check_in_time => check_in_time, :check_out_time => check_out_time, :alert_time_min => alert_time_min, :extra_minutes => extra_minutes }
				else
					render :json => { :status => true }
				end
				
			else 
				render :json => { :status => false, :error_message => "No current booking!" }
			end
		end
	end

	def check_in_process
		if params[:dining_id]
			dining_facility = DiningFacility.find(params[:dining_id])		
			if dining_facility.is_active && dining_facility.status == "available"
				if params[:checkin_time]
					checkin_at = nil
					if !params[:checkin_time].empty?
						checkin_at = Time.parse(params[:checkin_time]).utc
					else
						checkin_at = Time.now.utc
					end

					if !checkin_at.nil?
						if dining_facility.check_time(checkin_at, "checkin")
							booking = dining_facility.get_current_booking
							if booking.nil?
								
								booking = Booking.create({:dining_facility_id => params[:dining_id],:type => "TableBooking",
								                                :checkin_by=>current_login_employee.name,:checkin_at => checkin_at,:checkout_at =>nil, :booking_status => "assign", :reserved_at => nil, :reserved_by => nil })
								if booking.save!
									dining_facility.status = "occupied"
									dining_facility.save!
									render :json => { :status => true, :booking_id => booking.booking_id, :checkin_at => booking.checkin_at.utc.getlocal.strftime("%Y-%m-%d %H:%M:%S"), :message => "Check-in success" }
								else
									render :json => { :status => false, :error_message => "Booking does not create successfully!" }
								end
							else
								render :json => { :status => false, :error_message => "Booking already exist!" }
							end
						else
							render :json => { :status => false, :error_message => "Checkin time not available!" }
						end
					else
						render :json => { :status => false, :error_message => "Operation failed!" }
					end
				else
					booking = dining_facility.get_current_checkout_booking
					if booking.nil?
						lookup_checkout_time = Lookup.collection_of("checkout_time")
						
						if !lookup_checkout_time.empty?
							today = Time.now.utc.getlocal
							checkout_at = Time.now.utc.getlocal

							lookup_checkout_time.each do |checkout_time|
								arr_time = checkout_time[0].split("-")
								start_time = Time.parse(arr_time[0].strip).utc.getlocal.strftime("%H:%M%p")
								end_time = Time.parse(arr_time[1].strip).utc.getlocal.strftime("%H:%M%p")
								if start_time <= today.strftime("%H:%M%p") && today.strftime("%H:%M%p") <= end_time
									checkout_at = checkout_at + (checkout_time[1]).to_i.minutes
								end
							end

							if checkout_at.strftime("%Y-%m-%d %H:%M%p") >= today.strftime("%Y-%m-%d %H:%M%p")
								# if dining_facility.type == "Table"
								# 	type = "TableBooking"
								# else
								# 	type = "RoomBooking"
								# end
								
								booking = Booking.create({:dining_facility_id => params[:dining_id],:type => "TableBooking",
						                                :checkin_by=>current_login_employee.name,:checkin_at => Time.now.utc,:checkout_at =>checkout_at, :booking_status => "assign", :reserved_at => checkout_at, :reserved_by => current_login_employee.name })
								if booking.save!
									dining_facility.status = "occupied"
									dining_facility.save!
								end
								terminal = DiningFacility.find_by_id(booking.dining_facility_id)
								cashier_terminal 	= CashierTerminal.find_by_id(terminal.zone_id)

								if ENV["SERVER_MODE"] != "cloud" #no print in cloud server

									unique_code = "CheckInOutPdf"
									printer = PrintSetting.find_by_unique_code(unique_code)

								   	# print when complete click 
							    	order_queue_printer = Printer::OrderQueuePrinter.new(printer)

							    	if !printer.nil?
							    		order_queue_printer.print_check_in_out(printer, cashier_terminal, booking, dining_facility)
							    	end
							    end							
								render :json => { :status => true, :booking_id => booking.booking_id, :checkout_at => booking.checkout_at.utc.getlocal.strftime("%Y-%m-%d %H:%M") }
							else
								render :json => { :status => true }
							end
						else
							render :json => { :status => true }
						end
					else
						render :json => { :status => false, :error_message => "Booking already exist!" }
					end
				end
			else
      			error_message = "#{dining_facility.type} is not available!"
      			render :json => { :status => false, :error_message => error_message }
			end
		else
      		error_message = "dining_id is required!"
      		render :json => { :status => false, :error_message => error_message }
		end
	end

	def request_time
		if !params[:booking_id].nil? && !params[:time].nil?
			time = Time.parse(params[:time])
			booking = Booking.find(params[:booking_id])

			checkout_at = booking.checkout_at.utc

			hr = (time.strftime("%H").to_i).to_int
			min = (time.strftime("%M").to_i).to_int
			checkout_at = checkout_at + hr.hour + min.minutes

			booking.checkout_at = checkout_at
			booking.save!

			render :json => { :status => true, :checkout_at => booking.checkout_at.utc.getlocal.strftime("%Y-%m-%d %H:%M") }
		elsif !params[:booking_id].nil? && params[:time].nil? 
			error_message = "time is required!"
      		render :json => { :status => false, :error_message => error_message }
		elsif params[:booking_id].nil? && !params[:time].nil?
			error_message = "booking_id is required!"
      		render :json => { :status => false, :error_message => error_message }
		else
      		error_message = "booking_id and time are required!"
      		render :json => { :status => false, :error_message => error_message }
		end
	end

	def check_out_process
		if !params[:booking_id].nil? && !params[:checkout_time].nil?
			booking = Booking.find(params[:booking_id])
			dining_facility = DiningFacility.find(booking.dining_facility_id)
			checkout_at = Time.parse(params[:checkout_time]).utc
			if dining_facility.check_time(checkout_at, booking, "checkout")
				checkout_time = checkout_at.getlocal
				booking.checkout_at = checkout_time
				booking.reserved_at = checkout_time
				booking.reserved_by = current_login_employee.name
				if booking.save!
					render :json => { :status => true, :checkin_at => booking.checkin_at.utc.getlocal.strftime("%Y-%m-%d %H:%M:%S"), :checkout_at => booking.checkout_at.utc.getlocal.strftime("%Y-%m-%d %H:%M:%S"), :message => "Checkout success." }
				end
			else
				render :json => { :status => false, :error_message => "Checkout time not available!" }
			end
		else
			render :json => { :status => false, :error_message => "booking_id and checkout_time are required!" }
		end
	end

	private
	  def check_in_process_params
	    params.permit(:dining_id,:booking_id,:time)
	  end
end
