<?php
	
	if(!isset($CFG)) {
		require('config.php');
	}
	require_once($CFG->dirroot.'/course/lib.php');
	require_once($CFG->libdir.'/dmllib.php');
	require_once($CFG->libdir.'/accesslib.php');
	require_once($CFG->libdir.'/adminlib.php');
	require_once($CFG->libdir.'/datalib.php');
	
	$courses = explode("\n",file_get_contents('bulkcourses.csv'));
	$newcategories = explode("\n",file_get_contents('bulkcats.csv'));
	foreach($newcategories as $newcatname) {
		$data = new stdClass();
		$data->name = $newcatname;
		$data->parent = 0;
		$data->sortorder = 999;
		$data->id = insert_record('course_categories',$data);
		$data->context = get_context_instance(CONTEXT_COURSECAT, $data->id);
		mark_context_dirty($data->context->path);
		fix_course_sortorder();
	}

	$categories = get_records('course_categories');
	$users = get_records('user');
	// Test - create one course
	foreach($courses as $course) {
		$category = $categories[rand(1,count($categories))];
		$prefix = strtoupper(substr($category->name,0,4));
		$data = new stdClass();
		$data->shortname = $prefix . ' ' . rand(100, 3000);
		$data->startdate = time() + rand(0,86400);		// Generate random number (course start between now and a day from now)
		$data->category = $category->id;
		$data->numsections = 10;
		$data->hiddensections = 0;
		$data->newsitems = 5;
		$data->showgrades = 1;
		$data->showreports = 0;
		$data->format = (rand() % 2 == 0) ? 'topics' : 'weeks';
		$data->MAX_FILE_SIZE = 2097152;
		$data->maxbytes = 2097152;
		$data->metacourse = (rand(1,10)==10) ? 1 : 0;
		$data->fullname = ($data->metacourse) ? trim($course) . ' metacourse' : trim($course);
		$data->defaultrole = 0;
		$data->enrollable = 1;
		$data->enrolstartdate = 0;
		$data->enrolstartdisabled = ($data->enrolstartdate > 0) ? 0 : 1;
		$data->enrolenddate = 0;
		$data->enrolenddisabled = $data->enrolstartdisabled;
		$data->enrolperiod = 0;
		$data->expirynotify = 0;
		$data->notifystudents = 0;
		$data->expirythreshold = 864000;
		$data->groupmode = 0;
		$data->groupmodeforce = 0;
		$data->visible = 1;
		$data->guest = 0;
		$data->timemodified = time();
		if($course = create_course($data)) {
/*			echo "Created course ".$course->fullname." (".$course->shortname.") with id ".$course->id;
			echo "<br>";*/
			$context = get_context_instance(50, $course->id);
			$total_students = rand(5,count($users));
			$total_teachers = rand(1,5);
			if(!$data->metacourse) {
				for($i=1;$i<=$total_students;$i++) {
					$student = $users[rand(1,count($users))];
					role_assign(5,$student->id,'',$context->id);
				}
			}
			for($i=1;$i<=$total_teachers;$i++) {
				$teacher = $users[rand(1,count($users))];
				role_assign(3,$teacher->id,'',$context->id);
			}
		} else {
			echo "Failed to create course ".$data->fullname." (".$course->shortname.")";
			echo "<br>";
		}
	}
?>
