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

class Controller_Teacher_Discipline_Rating extends Controller_Environment_Teacher
{
    // id дисциплины
    private $id;
    /** @var  Model_Discipline */
    private $discipline;


    public function before() {
        parent::before();

        // make it possible to download files
        Cookie::set('fD', 'true');

        $this->id = (int) $this->request->param('id');
        $this->discipline = Model_Discipline::load($this->id);
        if (!$this->discipline->exists()) {
            throw new InvalidArgumentException(Error::DISCIPLINE_NOT_FOUND);
        }

        $this->setSemesterByDiscipline($this->discipline);
    }

    public function action_history() {
        $this->twig->set([
            'Discipline' => $this->discipline,
            'Logs'       => Model_Rating::getHistory($this->id),
        ])->set_filename('teacher/discipline/history');
    }

    public function action_rating() {
        $pageType = $this->request->param('type');
        $this->discipline['LocalizedExamType'] = RusLang::tr($this->discipline->Type);

        $map = Model_Map::of($this->discipline);
        $modules = $map->getModules('all');
        $submodules = $map->getSubmodules('all');

        foreach ($submodules as &$submodule) {
            $moduleID = $submodule['ModuleID'];
            $modules[$moduleID]['Submodules'][] = &$submodule;
            $modules[$moduleID]['MaxRate'] += $submodule['Rate'];
        }

        $students = Model_Rating::GetStudentsForRating($this->id)->as_array('GroupID');
        // TODO: add subgroup numbers to filter by subgroup in UI
        $exams = [];
        foreach ($students as &$group) {
            foreach ($group as &$student) {
                $recordBookID = $student['RecordBookID'];
                $rates = Model_Rating::getRatesAll($this->id, $recordBookID);
                foreach ($rates as $rate) {
                    if ($rate['ModuleType'] == 'exam') {
                        $submoduleID = $rate["SubmoduleID"];
                        $exams[$recordBookID][$submoduleID]['Rate'] = $rate['Rate'];
                        $exams[$recordBookID][$submoduleID]['Absence'] = $rate['ExamPeriodOption'] == 'absence';
                        $exams[$recordBookID][$submoduleID]['AutoPass'] = $rate['ExamPeriodOption'] == 'pass';
                    }
                }
            }
        }

        $this->twig->set([
            'Discipline' => $this->discipline,
            'Modules'    => $modules,
            'Groups'     => $this->discipline->getAllGroups()->groupByUniqueKey('ID'),
            'Students'   => $students,
            'Rates'      => Model_Rating::getRatesForDiscipline($this->discipline),
            'Exams'      => $exams,
        ])->set_filename("teacher/discipline/rating/$pageType");
    }
}