Optimus & Bumblebee travel to the past (probably in pursuit of some Decepticons, that decided to go back in time and awaken Megatron early, and alter the events of the preceding three movies, creating a nightmarish alternate All-Hail-Megatron reality), and adopt appropriate alternate modes (including a then shiny new blue and red COE).
Bumblebee is able to escape back to the future, but Optimus is left in the past.
Optimus cannot risk interfering with history anymore than he has, and has sparing access to appropriate resources, so he parks himself out of sight somewhere for 40yrs, and waits for the time stream to catch up.
Based on RotF Jetfire's poor health, and even more so on DotM Megatron's condition, we know that conditions on Earth are not as kind to Transformers as those on Cybertron, leading to relatively rapid decay, at least superficially, in the absence of appropriate resources. (But then, a modern human being wouldn't look so good if they were stranded in the stone age for a couple decades, so it seems understandable.)
Back to the Future Prime winds up, for one reason or another, pressured into abandoning his vow of silence/secrecy, and comes out of hiding early, teaming up with his 'past' self before that self travels back in time (maybe the time traveling Prime tries to dodge a paradox by introducing himself as Ultra Magnus, now that his paint has faded to rusted white).
This still produces a paradox, of course, but as far as most audiences are concerned, it'll be 'resolved' when Paradox Prime sacrifices himself heroically and prevents the time travel from occurring, leaving us with two years to gripe about the abundant plot holes, but buy up every version of pre-rusted COE time traveling Prime we can get.
Oh, and alternate time-line Megatron/Galvatron somehow survives the change in the time stream, effectively resurrecting him for the next two movies.