Spain is planning to give legal status to about 500,000 undocumented migrants as part of a major new policy.