When you burn oil or gas, they heat the surroundings. Energy is transferred from the chemicals to the surroundings. The original source of this energy is the Sun. Plants use the Sun's energy to produce sugars and oxygen from carbon dioxide and water, during photosynthesis. This energy is stored in the chemicals the plant produces.
Animals eat the plants and so the energy is transferred to their bodies.
In the conditions on Earth millions of years ago, plants and animals decayed, and the organic chemicals their bodies were made of became the source of fossil fuels we now use. This process happened before they had time to decay in the air. Anaerobic bacteria are thought to have acted on them to start the process of changing the into crude oil or gas. Perhaps there were some chemical reactions between the decaying organisms and the salts in the mud and water surrounding them. We know that there is a difference in the chemicals in oil from different parts of the world.