Pakistan beat South Africa by three wickets in fourth ODI