Brazil's president secured a historic fourth term after overturning a first-round defeat.