Thank you very much for your email. Just before receiving your reply, the issue got resolved. So I didn't get a chance to apply your suggestion. I managed to fix the error after following Tim Hunt's (https://moodle.org/user/view.php?id=93821&course=5) instruction on this forum; https://moodle.org/mod/forum/discuss.php?d=199860
Step 1) Fire SQL queries
A) SELECT * FROM mdl_course c WHERE NOT EXISTS (SELECT 1 FROM mdl_context ctx WHERE ctx.instanceid = c.id AND ctx.contextlevel = 50)
B) SELECT * FROM mdl_course_modules cm WHERE NOT EXISTS (SELECT 1 FROM mdl_context ctx WHERE ctx.instanceid = cm.id AND ctx.contextlevel = 70)
C) SELECT * FROM mdl_block_instances bi WHERE NOT EXISTS (SELECT 1 FROM mdl_context ctx WHERE ctx.instanceid = bi.id AND ctx.contextlevel = 80)
If all those quries return no rows, then I am really confused by the error you are seeing.
FROM mdl_context ctx
LEFT JOIN mdl_context parent ON ctx.path LIKE CONCAT('%/', parent.id, '/', ctx.id)
WHERE parent.id IS NULL OR ctx.path <> CONCAT(parent.path, '/', ctx.id)
If everything is OK, that query will return one row with contextlevel = 10, but in your case it should return more.
Step 2) Run PHP script
Save the following script into a file called fixup.php using a plain text editor.
Upload it to the root folder of your Moodle site (the same folder that contains files called config.php and pluginfile.php) then visit the URL .../fixup.php with your web browser. Hopefully, it will work, but I have to say this is just my best guess. It might be a good idea to set Debugging to developer level before running the script. Please take the moodle website folder backup.
The alternative is to read the code, and work out exactly what the move_courses function does, and do the same thing manually in the database. That is more complex, but might be a bit safer.
require_once($CFG->dirroot . '/course/lib.php');
move_courses(array(1,2,3,4,5,6,7,8,9,10), 1); // the numbers from 1 to 10 are courses ids then ',1' is the category where you will be moving all your courses.
Delete fixup.php file or keep it to use again in the future for the same problem
Comment out or delete the following lines from config.php file
//$CFG->debug = (E_ALL | E_STRICT);
Reorganise your courses back to the categories where they were before.
I still don't know what was the issue, but after following these steps I managed to fix the issue. I hope these steps will be useful for someone who has a similar issue.
Thank you very much Ken and Tim Hunt for your prompt support on this forum.
All the best!