https://www.acmicpc.net/problem/6064
k=int(input())
for i in range(k):
m,n,x,y=map(int,input().split())
num=x
while 1:
if num%n==y:
print(num)
break
if n==y and num%n==0:
print(num)
break
if num>m*n:
print("-1")
break
num+=m