Hey there!
Your code seems mostly correct, but the issue lies in how PHP PDO works with lastInsertId(). This method only returns the ID of the last inserted record and not after an UPDATE query. Since your logic includes an UPDATE query right after the INSERT, calling $db->lastInsertId() at that point will not reflect the inserted ID anymore.
To fix this, simply move the call to $db->lastInsertId() directly after the INSERT query, and it should work as expected.
Best regards,
t045t