<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Teacher_Rating extends Controller_UserEnvi {

    public function before() {
        Cookie::set('fD', 'true'); // Ставим кук fD, чтоб иметь возможность скачать отчет TODO

        $this->model_rating = new Model_Teacher_Rating;
        $this->model_discipline = new Model_Teacher_Map;

        parent::before();
    }

    // Получить из кука SGID выбранную ранее группу для данной дисциплины
    private function getStudyGroupID_ForFilter($id)
    {
        # $id = disciplineID
        $SG_array = json_decode(Cookie::get('SGID', null), true);
        if ($SG_array !== null) 
        {
            if (array_key_exists($id, $SG_array))
                return $SG_array[$id];
        }
        return 0;
    }

    // Настройки дисциплины и выбранная группа(для фильтра)
    private function getDisciplineInformation($id) {

        $temp = $this->model_discipline->getDisciplineInfoByID($id);
        $disciplineInfo['ExamType'] = $temp[0]['ExamType'];
        $disciplineInfo['ID'] = $id;
        $disciplineInfo['isMilestone'] = $temp[0]['isMilestone'];
        $disciplineInfo['StudyGroupID_Filter'] = $this->getStudyGroupID_ForFilter($id);

        return $disciplineInfo;
    }


    // Страница оценивания в течение семестра
    public function action_edit()
    {
        $twig = Twig::factory('teacher/rating');
        $twig->User = $this->UserInfo;
        $id = $this->request->param('id');

        // Шапка таблицы: структура УКД (модули и мероприятия)
        $structure = $this->model_rating->GetMapForDiscipline($this->UserInfo['TeacherID'], $id);

        if($structure->count() == 0)
            throw HTTP_Exception::factory (404, "Для дисциплины с ID $id не создана УКД или такой дисциплины не существует!");
        
		$structureHandled = array();
        $maxRate = 0; $i = 0; $temp_moduleID = 0;

        foreach($structure as $row)
        {
            if($row['ModuleID'] != $temp_moduleID)
            {
                $i++; // todo
                $temp_moduleID = $row['ModuleID'];
            }
            if ($i == 1)
                $twig->SubjectName = $row['SubjectName'];

            if(!isset($structureHandled[$i]['SubmodulesCount']))
            {
                $structureHandled[$i]['SubmodulesCount'] = 0;
                $structureHandled[$i]['MaxRate'] = 0;
            }
            $j = $structureHandled[$i]['SubmodulesCount'] += 1;
            $structureHandled[$i]['MaxRate'] += (int) $row['MaxRate'];
            $structureHandled[$i]['ModuleTitle'] = $row['ModuleName'];
            $structureHandled[$i]['ModuleType'] = $row['ModuleType'];
            if ($row['ModuleType'] == "exam") {
                $twig->examSubmoduleID = $row['SubmoduleID'];
            }
                    
            $structureHandled[$i][$j]['SubmoduleID'] = $row['SubmoduleID'];
            $structureHandled[$i][$j]['Title'] = $row['SubModuleName'];
            //$structureHandled[$i][$j]['Description'] = $row['SubmoduleDescription']; // Описание
            $structureHandled[$i][$j]['MaxRate'] = (int) $row['MaxRate'];
            $maxRate += $row['MaxRate'];

            if ($row['ModuleType'] == "exam" || $row['ModuleType'] == "extra") {
                $structureHandled[$i][$j]['SubmoduleID'] = -1;
            }
        }
        $structureHandled['ModulesCount'] = $i;
        $structureHandled['MaxRate'] = (int) $maxRate; 
        // end Шапка таблицы


        // Студенты и их баллы
        $students = $this->model_rating->GetStudentsForRating($this->UserInfo['TeacherID'], $id);

        $rateHandled = array();
        $groupsHandled = array();
        $i_g = 0; $i_s = 0; $curGroup = 0;

        foreach($students as $row) {
            // Группа
            if ($curGroup !== $row['GroupID']) 
            {
                $curGroup = $row['GroupID'];
                $i_g++;
                $rateHandled[$i_g]['GroupID'] = $row['GroupID'];
                $rateHandled[$i_g]['GroupNum'] = $row['GroupNum']; // № группы
                $rateHandled[$i_g]['GradeNum'] = $row['GradeNum']; // № курса
                $rateHandled[$i_g]['isAttached'] = $row['isAttached']; // #1

                if ($row['Degree'] == 'bachelor')
                    $rateHandled[$i_g]['GradeTitle'] = $row['GradeNum'].' курс';

                if ($row['Degree'] == 'specialist')
                    $rateHandled[$i_g]['GradeTitle'] = $row['GradeNum'].' курс';

                if ($row['Degree'] == 'master')
                    $rateHandled[$i_g]['GradeTitle'] = 'Магистратура, '.$row['GradeNum'].' год';

                $groupsHandled[$curGroup] = $rateHandled[$i_g]['GradeTitle']." ".$row['GroupNum']." группа"; 
            }

            // Студенты
            $curStudent = array();
            $i_s++;
            $curStudent['ID'] = $row['ID'];
            $curStudent['Last'] = $row['Last'];
            $curStudent['First'] = $row['First'];
            $curStudent['Second'] = $row['Second'];
            $curStudent['isAttached'] = $row['isAttached']; // #1

            // Баллы студента
            $rates = $this->model_rating->getMapForStudent($row['ID'], $id);
            $i_r = 0;
            $curStudent['RateResult'] = 0;
            foreach($rates as $r) {
                $i_r++;
                $curStudent['Rates'][$i_r]['Rate'] = $r['Rate'];
                $curStudent['RateResult'] += $r['Rate'];

                if ($r['ModuleType'] == 'exam')
                    $curStudent['Rates'][$i_r]['SubmoduleID'] = -1;
                else if ($r['ModuleType'] == 'extra')
                    $curStudent['Rates'][$i_r]['SubmoduleID'] = -2;
                else 
                    $curStudent['Rates'][$i_r]['SubmoduleID'] = $r['SubmoduleID'];

                $curStudent['Rates'][$i_r]['Type'] = $r['ModuleType'];
            }
            $rateHandled[$i_g]['Students'][$i_s] = $curStudent;

            /*
            $i_s++;
            $rateHandled[$i_g]['Students'][$i_s]['ID'] = $row['ID'];
            $rateHandled[$i_g]['Students'][$i_s]['Last'] = $row['Last'];
            $rateHandled[$i_g]['Students'][$i_s]['First'] = $row['First'];
            $rateHandled[$i_g]['Students'][$i_s]['Second'] = $row['Second'];
            $rateHandled[$i_g]['Students'][$i_s]['isAttached'] = $row['isAttached']; // #1

            // Баллы студента
            $rate = $this->model_rating->getMapForStudent($row['ID'], $id);
            $i_r = 0;
            $rateHandled[$i_g]['Students'][$i_s]['RateResult'] = 0;
            foreach($rate as $r) {
                $i_r++;
                $rateHandled[$i_g]['Students'][$i_s]['Rates'][$i_r]['Rate'] = $r['Rate'];
                $rateHandled[$i_g]['Students'][$i_s]['RateResult'] += $r['Rate'];

                if ($r['ModuleType'] == 'exam')
                    $rateHandled[$i_g]['Students'][$i_s]['Rates'][$i_r]['SubmoduleID'] = -1;
				else if ($r['ModuleType'] == 'extra')
					$rateHandled[$i_g]['Students'][$i_s]['Rates'][$i_r]['SubmoduleID'] = -2;
                else 
                    $rateHandled[$i_g]['Students'][$i_s]['Rates'][$i_r]['SubmoduleID'] = $r['SubmoduleID'];
            }
            */
        }

        // На вывод
        $twig->headerRate = $structureHandled; 
        $twig->rateTable = $rateHandled;
        $twig->groups = $groupsHandled;

        $twig->disciplineInfo = $this->getDisciplineInformation($id);
        $twig->disciplineInfo_JSON = json_encode($twig->disciplineInfo);

		$this->response->body($twig);
    }

    // Страница оценивания в сессию
    public function action_exam()
    {
        $twig = Twig::factory('teacher/exam');
        $twig->User = $this->UserInfo;
        $id = $this->request->param('id');

        // Шапка таблицы: структура УКД (модули и мероприятия)
        $structure = $this->model_rating->GetMapForDisciplineExam($this->UserInfo['TeacherID'], $id);

        if($structure->count() == 0)
            throw HTTP_Exception::factory (404, "Страница не найдена");

        
        $structureHandled = array();
        $maxRate = 0; $i = 0; $temp_moduleID = 0; $try_1 = 0; // try = 1 - экзамен, = 2, 3 - пересдачи
        $examRate = 0;
        $try = 0;

        foreach($structure as $row)
        {
            if($row['ModuleID'] != $temp_moduleID)
            {
               ++$i; // todo
               $temp_moduleID = $row['ModuleID'];
            }
            if ($i == 1)
                $twig->SubjectName = $row['SubjectName'];

            if(!isset($structureHandled[$i]['SubmodulesCount']))
            {
                $structureHandled[$i]['SubmodulesCount'] = 0;
                $structureHandled[$i]['MaxRate'] = 0;
            }
            $j = $structureHandled[$i]['SubmodulesCount'] += 1;
            $structureHandled[$i]['MaxRate'] += (int) $row['MaxRate'];
            $structureHandled[$i]['ModuleTitle'] = $row['ModuleName'];
            $structureHandled[$i]['ModuleType'] = $row['ModuleType'];
            if ($row['ModuleType'] == "exam")
                $twig->examSubmoduleID = $row['SubmoduleID'];
                    
            $structureHandled[$i][$j]['SubmoduleID'] = $row['SubmoduleID'];
            if ($row['ModuleType'] == 'extra') {
                $structureHandled[$i][$j]['Title'] = 'Добор баллов';
                $maxRate += $row['MaxRate'];
            }
            else {
                if ($try === 0)
                    $structureHandled[$i][$j]['Title'] = 'Основная сдача';
                else
                    $structureHandled[$i][$j]['Title'] = 'Пересдача '.$try;
                $examRate = $row['MaxRate'];
                $try++;
            }
            //$structureHandled[$i][$j]['Description'] = $row['SubmoduleDescription']; // Описание
            $structureHandled[$i][$j]['MaxRate'] = (int) $row['MaxRate'];
           
        }
        $structureHandled['ModulesCount'] = $i;
        $structureHandled['MaxRate'] = (int) $maxRate; 
        // end Шапка таблицы

        // Студенты и их баллы по экзамену
        $students = $this->model_rating->GetStudentsForRating($this->UserInfo['TeacherID'], $id);

        $rateHandled = array();
        $groupsHandled = array();
        $i_g = 0; 
        $i_s = 0; 
        $curGroupID = 0;

        foreach($students as $row) {
            // Группа 
            if ($curGroupID !== $row['GroupID']) {
                $curGroupID = $row['GroupID'];
                $i_g++;
                $rateHandled[$i_g]['GroupID'] = $row['GroupID'];
                $rateHandled[$i_g]['GroupNum'] = $row['GroupNum']; // № группы
                $rateHandled[$i_g]['GradeNum'] = $row['GradeNum']; // № курса
                $rateHandled[$i_g]['isAttached'] = $row['isAttached']; // #1

                if ($row['Degree'] == 'bachelor')
                    $rateHandled[$i_g]['GradeTitle'] = $row['GradeNum'].' курс';

                if ($row['Degree'] == 'specialist')
                    $rateHandled[$i_g]['GradeTitle'] = $row['GradeNum'].' курс';

                if ($row['Degree'] == 'master')
                    $rateHandled[$i_g]['GradeTitle'] = 'Магистратура, '.$row['GradeNum'].' год';

                $groupsHandled[$curGroupID] = $rateHandled[$i_g]['GradeTitle']." ".$row['GroupNum']." группа"; 
                $i_s = 0;
            }

            // Студенты   
            $curStudent = array();
            $curStudent['ID'] = $row['ID'];
            $curStudent['Last'] = $row['Last'];
            $curStudent['First'] = $row['First'];
            $curStudent['Second'] = $row['Second'];
            $curStudent['isAttached'] = $row['isAttached']; // #1
            $curStudent['RateResult'] = 0;

            // Баллы студента
            $i_r = 0;
            $examRate = 0;
            $extraNum = 0;
            $rate = $this->model_rating->getMapForStudentExam($row['ID'], $id);

            $lastExam = -1;
            $lastExtra = -1;
            $lastNilExam = -1;
            $lastNilExtra = -1;

            foreach($rate as $r) {
                
                $curRate = array();
                $curRate['SubmoduleID'] = $r['SubmoduleID'];
                $curRate['Rate'] = $r['Rate'];
                $curRate['ModuleType'] = $r['ModuleType'];

                if (!is_null($r['Rate'])) 
                {
	                if ($r['ModuleType'] == 'exam') {
	        			if ($lastExam >= 0) {
	    					$curStudent['Rates'][$lastExam]['Block'] = 'True';
	        			}
	        			$lastExam = $i_r;
	        		} else if ($r['ModuleType'] == 'extra') {

	        			if ($lastExtra >= 0) {
	    					$curStudent['Rates'][$lastExtra]['Block'] = 'True';
	        			}
	        			$lastExtra = $i_r;
	        			$curStudent['Rate'] += $r['Rate'];
	        		}
        		} else {
    				if ($r['ModuleType'] == 'exam' && $lastNilExam < 0) {
    					$lastNilExam = $i_r;
    				}
					else if ($r['ModuleType'] == 'extra' && $lastNilExtra < 0) {
						$lastNilExtra = $i_r;
					}
					else {
						$curRate['Block'] = 'True';
					}
        		}


                $curStudent['Rates'][$i_r] = $curRate;
                $i_r++;
            }


            $curStudent['RateResult'] += $examRate;
            $total = $this->model_rating->GetStudentRate($row['ID'], $id);
            $total = $total[0]['Num'];
            if (is_null($total)) $total = 0;
            
            if ($lastExam >= 0) {
        		$curStudent['RateResult'] += $curStudent['Rates'][$lastExam]['Rate'];
            }
            $curStudent['RateSemesterResult'] = $total - $curStudent['RateResult'];
            $curStudent['RateResult'] = $total;

            $magic_bottom = 32;
            $magic_top = 38;

            $extra_rate = 0;
            if ($curStudent['RateSemesterResult'] >= $magic_bottom && 
            	$curStudent['RateSemesterResult'] <= $magic_top) 
            {
            	$extra_rate = $magic_top - $curStudent['RateSemesterResult'];
        	}
        	if ($lastExtra >= 0) {
	            $curStudent['Rates'][$lastExtra]['MaxRate'] = $extra_rate;
            } 
            if ($lastNilExtra >= 0) {
    			$curStudent['Rates'][$lastNilExtra]['MaxRate'] = $extra_rate;
        	}

            $rateHandled[$i_g]['Students'][$i_s] = $curStudent;
            $i_s++;
        }

        // На вывод
	    $twig->headerRate = $structureHandled;
        $twig->rateTable = $rateHandled;
        $twig->groups = $groupsHandled;

        $twig->disciplineInfo = $this->getDisciplineInformation($id);
        $twig->disciplineInfo_JSON = json_encode($twig->disciplineInfo);

        $this->response->body($twig);
    }
}