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.strftime("%Y-%m-%d %H:%M")
				if booking.checkout_at
					check_out_time = booking.checkout_at.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.zone.parse(arr_time[0].strip).utc.strftime("%H:%M%p")
	          end_time = Time.zone.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
		else
			render :json => { :status => false }
		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 dining_facility.current_checkin_booking.nil?
					if params[:checkin_time].present?
						checkin_at = Time.zone.parse(params[:checkin_time])
					else
						checkin_at = Time.current
					end

					checkout_at = nil
					lookup_checkout_time = Lookup.collection_of("checkout_time")
					today = Time.current
					if !lookup_checkout_time.empty?

						lookup_checkout_time.each do |checkout_time|
							start_time, end_time = checkout_time[0].split("-").map{ |t| Time.zone.parse(t.strip).strftime("%H:%M%p") }
							if start_time <= today.strftime("%H:%M%p") && today.strftime("%H:%M%p") <= end_time
								checkout_at = checkin_at + (checkout_time[1]).to_i.minutes
							end
						end
					end

					booking = nil
					ActiveRecord::Base.transaction do
						booking = Booking.create({
							:dining_facility_id => params[:dining_id],
							:type => "TableBooking",
							:checkin_by => current_login_employee.name,
							:checkin_at => checkin_at,
							:checkout_at => checkout_at,
							:booking_status => "assign",
							:reserved_at => checkout_at,
							:reserved_by => current_login_employee.name })

						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, :checkin_at => booking.checkin_at.strftime("%Y-%m-%d %H:%M"), :checkout_at => booking.checkout_at.strftime("%Y-%m-%d %H:%M") }
				else
					render :json => { :status => false, :error_message => "Booking already exist!" }
				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
	rescue ActiveRecord::RecordInvalid => exception
		render :json => { :status => false, :error_message => exception.message }
	end

	def request_time
		if !params[:booking_id].nil? && !params[:time].nil?
			time = Time.zone.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.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.zone.parse(params[:checkout_time]).utc
			if dining_facility.check_time(checkout_at, booking, "checkout")
				checkout_time = checkout_at
				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.strftime("%Y-%m-%d %H:%M:%S"), :checkout_at => booking.checkout_at.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
