Why did the Soviets invade Afghanistan during the cold war?

The Soviets invaded, at least in part, to provide support to the Parcham fraction of the Afghani Communist Party. Until the invasion, the People's Democratic Party of Afghanistan (PDPA) and thus the government of Afghanistan had been in the hands of the leaders of the Khalq faction. The Khalq faction had introduced progressive reforms including women's rights, something which the deeply Islamic Afghanis in rural areas did not agree with. The US government aided anti-government rebels in order to provoke Soviet military intervention and thus weaken their power. This idea worked, the Soviets invaded, but they had no victory. It was to the USSR what the Vietnam War is to the US.