<?php
namespace local_treestudyplan;

class teachingfinder {
    const TABLE = "local_treestudyplan_teachers";


    public static function list_my_plans(){
        global $USER,$DB;
        $userid = $USER->id;

        $records = $DB->get_records(self::TABLE,['teacher_id' => $userid]);
        if(count($records) == 0){
            // initiate a search if the cache is empty
            self::update_teaching_cache($userid);
             $DB->get_records(self::TABLE,['teacher_id' => $userid]);
        }
        $list = [];
        foreach($records as $r){
            $list[] = studyplan::findById($r->studyplan_id);
        }
        return $list;
    }


    /**
     * Find The active studyplans where the specified user is a teacher
     * (Has the  mod/assign::grade capability in one of the linked courses)
     * TODO: OPTIMIZE THIS CHECK!!!
     */
    public static function update_teaching_cache($userid){
        global $DB;
        $list = [];

        // First find all active study plans

        $sql = "SELECT p.id FROM {local_treestudyplan_page} p 
            WHERE startdate <= NOW() and enddate >= NOW()";
        $page_ids = $DB->get_fieldset_sql($sql, []);

        // then parse them to see if the user has the grading permission in any of them 
        // (Which would make them a teacher for all intents and purposes)

        foreach($page_ids as $page_id) {
            $sql = "SELECT i.course_id FROM {local_treestudyplan_item} i 
                    INNER JOIN {local_treestudyplan_line} l ON i.line_id = l.id 
                    WHERE l.page_id = :page_id AND i.course_id IS NOT NULL";
            $course_ids = $DB->get_fieldset_sql($sql, ["page_id" => $page_id]);

            $linked = false;
            foreach($course_ids as $cid){
                $coursecontext =  \context_course::instance($cid);
                if (is_enrolled($coursecontext, $userid, 'mod/assign:grade')){
                    $linked = true; 
                    break; // No need to search further
                }
            }

            if($linked)
            {
                $list[] = $page_id;
            }

        }

        // Now, clear the database of all records for this user
        $DB->delete_records(self::TABLE,["teacher_id"=>$userid]);
        // And add new records for the found studyplans
        $now = time();
        foreach($list as $page_id){
            // Retrieve the studyplan id from the page
            //TODO: Change this when page management is implemented to return the page instead of the plan
            $planid = $DB->get_field("local_treestudyplan_page","studyplan_id",["id" => $page_id]);
            $DB->insert_record(self::TABLE,["teacher_id"=>$userid,"studyplan_id"=>$planid,"update_time"=>$now]);
        }

        return $list;
    }

    public static function list_teacher_ids(){
        global $DB;
        return $DB->get_fieldset_sql("SELECT DISTINCT teacher_id FROM {".self::TABLE."}");
    }

    public static function get_update_time($teacher_id): int {
        global $DB;
        $r = $DB->get_field_sql("SELECT MIN(update_time)FROM {".self::TABLE."} WHERE teacher_id=:teacher_id",
                                ["teacher_id" => $teacher_id]);
        return (int)($r->update_time);
    }


}