You got it for "free" because the mobile carrier wanted to induce you to be a customer. The phone indeed did cost the mobile carrier money to buy the phone from the equipment manufacturer. The carrier is gambling that the "investment" that they've made in you will come back to them in the way of the charges that you pay every month for service. They're hoping that the ARPU
Generally phones sold by a carrier are sold at discount or "given" to a subscriber at a significant discount to make service attractive to the prospective subscriber. Apple's iPhone is a definite exception to this since there's no carrier subsidy at all which to me seems a wee bit strange as I don't see what the incentive is for you to get this phone to just give AT&T the "privilege" of having you indebted to them for two years with no advantage for the subscriber but lots of advantage for the carrier.
Some of the handsets weren't cheap, like around $50.