<?php
namespace local_treestudyplan;
require_once($CFG->libdir.'/externallib.php');

use \local_treestudyplan\studyplan;

class cascadeusersync {
    private const METHOD = "manual";
    private $studyplan;

    function __construct(studyplan $studyplan){
        $this->studyplan = $studyplan;
    }

    function sync(){
        global $DB;

        /*  Explainer:
            This script uses {enrol}.customtext4 to store a json array of all studyplans that need this cohort sync to exist.
            Since the cohort-sync enrolment method uses only customint1 and customint2, this is a safe place to store the data.
            (Should the cohortsync script at any future time be modified to use customtext fields, it is still extremely unlikely that 
            customtext4 will be used.)
            Because of the overhead involved in keeping an extra table up to date and clean it up if cohort syncs are removed outside of this script,
            it was determined to be the simplest and cleanest solution.
        */

        $enrol = \enrol_get_plugin(self::METHOD);
        // Find the courses that need to be synced to the associated cohorts
        $courseids = $this->studyplan->get_linked_course_ids();
        // And find the users that are linked to this studyplan.
        $userids = $this->studyplan->get_linked_user_ids();
        // Get the roleid to use for synchronizations
        $roleid = get_config("local_treestudyplan","csync_roleid");

        // Next, for each course that is linked:
        foreach($courseids as $courseid){
            $course = \get_course($courseid);
            if(count($userids) > 0){
                // Get the manual enrol instance for this course
                $instanceparams = ['courseid' => $courseid, 'enrol' => 'manual'];
                if(!($instance = $DB->get_record('enrol', $instanceparams))){
                    if ($instanceid = $enrol->add_default_instance($course)) {
                        $instance = $DB->get_record('enrol', array('id' => $instanceid));
                    }
                    else {
                        // Instance not added for some reason, so report an error somewhere
                        // (or not)
                        $instance = null; 
                    }
                }
                if($instance !== null){
                    foreach($userids as $uid){
                        // Try a manual registration - it will just be updated if it is already there....
                        $enrol->enrol_user($instance,$uid,$roleid);
                    }
                }    
            }


            // We do not do any autoremoval for user syncs, to avoid students losing access to the course data
            
        }
    }
}