<?php

namespace local_treestudyplan\local\ungradedscanners;


class assign_scanner extends scanner_base {
    
    protected function get_ungraded_submissions(){
        global $DB;
       //SELECT asgn_sub.id as submissionid, a.id as instanceid, asgn_sub.userid as userid, asgn_sub.timemodified as timesubmitted, asgn_sub.attemptnumber , a.maxattempts
       $sql =   "SELECT DISTINCT asgn_sub.userid
                    FROM {assign_submission} asgn_sub
                    JOIN {assign} a ON a.id = asgn_sub.assignment
                    LEFT JOIN {assign_grades} ag ON ag.assignment = asgn_sub.assignment AND ag.userid = asgn_sub.userid AND
                    asgn_sub.attemptnumber = ag.attemptnumber
                    WHERE a.id = {$this->gi->iteminstance} 
                    AND asgn_sub.status = 'submitted'
                    AND asgn_sub.userid > 0 
                    AND a.grade <> 0 AND (ag.id IS NULL OR asgn_sub.timemodified >= ag.timemodified)
                    ";
        
        return $DB->get_fieldset_sql($sql);
    }

    protected function get_graded_users(){
        global $DB;
        $sql = "SELECT DISTINCT g.userid 
                FROM {grade_grades} g 
                LEFT JOIN {grade_items} gi on g.itemid = gi.id 
                WHERE gi.itemmodule = 'assign' AND gi.iteminstance = {$this->gi->iteminstance}
                AND g.finalgrade IS NOT NULL"; // MAy turn out to be needed, dunno
        return $DB->get_fieldset_sql($sql);
    }


    public function count_ungraded($course_userids=[]){
        $ungraded = $this->get_ungraded_submissions();

        if(count($course_userids) > 0){
            $ungraded = array_intersect($ungraded,$course_userids);
        }
        return count($ungraded);
    }

    public function count_graded($course_userids=[]){
        $ungraded = $this->get_ungraded_submissions();
        $graded = $this->get_graded_users();

        if(count($course_userids) > 0){
            $ungraded = array_intersect($ungraded,$course_userids);
            $graded = array_intersect($graded,$course_userids);
        }

        // determine how many id's have a grade, but also an ungraded submission
        $dual = array_intersect($ungraded,$graded);
        // subtract those from the graded count
        return count($graded) - count($dual);
    }

    public function has_ungraded_submission($userid)
    {
        $ungraded = $this->get_ungraded_submissions();
        return in_array($userid,$ungraded);
    }

}