-- Handle event fire

local function toggleDoor(player, door)
	local motor = rightMotor
	if door == "left" then
		motor = leftMotor
	end
	-- Check distance to the character's Torso. If too far, don't do anything
	if player.Character and player.Character:FindFirstChild("Torso") then	
		local torso = player.Character:FindFirstChild("Torso")
		local toTorso = torso.Position - cabinet.Bottom.Position
		if toTorso.magnitude < clickDistance then
			if open then
				motor.DesiredAngle = 0
				open = false
			else
				motor.DesiredAngle = math.pi/2
				open = true
			end
		end
	end
end

for _, Part in pairs(cabinet:GetChildren()) do
	if Part:FindFirstChild("ROBLOXInteractionEvent") and (string.match(Part.Name, "Door") or string.match(Part.Name, "Handle") or string.match(Part.Name, "Padding")) then
		local event = Part:FindFirstChild("ROBLOXInteractionEvent")
		local door = "right"
		if string.match(Part.Name, "Left") then
			door = "left"
		end
		event.OnServerEvent:connect(function(player, arguments) toggleDoor(player, door) end)
	end
end
