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

class Controller_Handler_Map extends Controller_Handler {
		
        public function before() {
            $this->model = new Model_Teacher_Map;
            $this->setAccessLevel(self::ACCESS_USER);
            parent::before();
        }
        
		private function privateDeleteSubmodule($SubmoduleID) {
			$result = $this->model->deleteSubmodule($this->user['TeacherID'], $SubmoduleID);
			return $result[0]['Num'];
		}
		
		// Добавление преподавателем дисциплины
		public function action_AddDiscipline() {
			$data['success'] = false;
            $this->post -> rule('Grade', 'not_empty')
                        -> rule('Grade', 'digit')
						-> rule('SubjectID', 'not_empty')
                        -> rule('SubjectID', 'digit')
						-> rule('ExamType', 'not_empty')
						-> rule('LectionCount', 'not_empty')
                        -> rule('LectionCount', 'digit')
						-> rule('PracticeCount', 'not_empty')
                        -> rule('PracticeCount', 'digit')
						-> rule('DepartmentID', 'not_empty')
                        -> rule('DepartmentID', 'digit');
            if($this->post->check()) {
					$result = $this->model->AddDiscipline(
						$this->user['TeacherID'],
						$this->post->offsetGet('Grade'),
						$this->post->offsetGet('SubjectID'),
						$this->post->offsetGet('ExamType'),
						$this->post->offsetGet('LectionCount'),
						$this->post->offsetGet('PracticeCount'),
						$this->post->offsetGet('DepartmentID')
					);
					$data['DisciplineID'] = $result[0]['Num'];
					if ($data['DisciplineID'] > 0)
						$data['success'] = true;
			}
			$this->response->body(json_encode($data));
		}
		
		// Изменения базовых параметров дисциплины
		public function action_ChangeDiscipline() {
			$data['success'] = false;
            $this->post -> rule('DisciplineID', 'not_empty')
                        -> rule('DisciplineID', 'digit')
						-> rule('Grade', 'not_empty')
                        -> rule('Grade', 'digit')
						-> rule('SubjectID', 'not_empty')
                        -> rule('SubjectID', 'digit')
						-> rule('ExamType', 'not_empty')
						-> rule('LectionCount', 'not_empty')
                        -> rule('LectionCount', 'digit')
						-> rule('PracticeCount', 'not_empty')
                        -> rule('PracticeCount', 'digit');
            if($this->post->check()) {
					$result = $this->model->ChangeDiscipline(
						$this->user['TeacherID'],
						$this->post->offsetGet('DisciplineID'),
						$this->post->offsetGet('ExamType'),
						$this->post->offsetGet('LectionCount'),
						$this->post->offsetGet('PracticeCount'),
						$this->post->offsetGet('Grade'),
						$this->post->offsetGet('SubjectID')
					);
					if ($result[0]['Num'] == 0)
						$data['success'] = true;
			}
			$this->response->body(json_encode($data));
		}
		
		// Добавить модуль и к модулю 1 мероприятие
		public function action_AddModule(){
			$data['success'] = false;
            $this->post -> rule('DisciplineID', 'not_empty')
                        -> rule('DisciplineID', 'digit')
						-> rule('OrderNum', 'not_empty')
                        -> rule('OrderNum', 'digit');
            if($this->post->check()) {
				// Добавление модуля
                $result = $this->model->AddModule(
					$this->user['TeacherID'],
					$this->post->offsetGet('DisciplineID'),
					$this->post->offsetGet('OrderNum'),
					'Наименование модуля'
				);
				$data['ModuleID'] = $result[0]['Num'];
				if ($data['ModuleID'] > 0) {
					// Добавление мероприятия
					// Т.к. модуль должен содержать хотя бы
					// 1 мероприятие
					$result = $this->model->AddSubmodule(
						$this->user['TeacherID'],
						$data['ModuleID'],
						'0', //MaxRate
						'1', //OrderNum
						'Наименование мероприятия',
						'', //Description
						'CurrentControl'
					);
					$data['SubmoduleID'] = $result[0]['Num'];
					if ($data['SubmoduleID'] > 0)
						$data['success'] = true;
				}
					
            }
			$this->response->body(json_encode($data));
		}
		
		// Добавление мероприятия
		public function action_AddSubmodule() {
			$data['success'] = false;
            $this->post -> rule('ModuleID', 'not_empty')
                        -> rule('ModuleID', 'digit')
						-> rule('OrderNum', 'not_empty')
                        -> rule('OrderNum', 'digit');
            if($this->post->check()) {
					$result = $this->model->AddSubmodule(
						$this->user['TeacherID'],
						$this->post->offsetGet('ModuleID'),
						'0', //MaxRate
						$this->post->offsetGet('OrderNum'),
						'Наименование мероприятия',
						'', //Description
						'CurrentControl'
					);
					$data['SubmoduleID'] = $result[0]['Num'];
					if ($data['SubmoduleID'] > 0)
						$data['success'] = true;
			}
			$this->response->body(json_encode($data));
		}
		
		// Поменять имя модуля
		public function action_ChangeModuleName() {
			$data['success'] = false;
            $this->post -> rule('ModuleID', 'not_empty')
                        -> rule('ModuleID', 'digit')
						-> rule('ModuleName', 'not_empty');
            if($this->post->check()) {
                $result = $this->model->ChangeModuleName($this->user['TeacherID'], $this->post->offsetGet('ModuleID'), $this->post->offsetGet('ModuleName'));
				if ($result[0]['Num'] == 0)
					$data['success'] = true;
			}
			$this->response->body(json_encode($data));
		}
		
		// Поменять имя мероприятия
		public function action_ChangeSubmoduleName() {
			$data['success'] = false;
            $this->post -> rule('SubmoduleID', 'not_empty')
                        -> rule('SubmoduleID', 'digit')
						-> rule('SubmoduleName', 'not_empty');
            if($this->post->check()) {
                $result = $this->model->ChangeSubmoduleName($this->user['TeacherID'], $this->post->offsetGet('SubmoduleID'), $this->post->offsetGet('SubmoduleName'));
				if ($result[0]['Num'] == 0)
					$data['success'] = true;
            }
			$this->response->body(json_encode($data));
		}
		
		// СВАП порядка двух модулей
		public function action_SwapModuleOrder() {
			$data['success'] = false;
            $this->post -> rule('ModuleID1', 'not_empty')
                        -> rule('ModuleID1', 'digit')
						-> rule('ModuleID2', 'not_empty')
						-> rule('ModuleID2', 'digit');
            if($this->post->check()) {
				$result = $this->model->SwapModuleOrder(
					$this->user['TeacherID'],
					$this->post->offsetGet('ModuleID1'),
					$this->post->offsetGet('ModuleID2')
				);
				if ($result[0]['Num'] == 0)
					$data['success'] = true;
			}
			$this->response->body(json_encode($data));
		}
		
		// Свап порядка двух мероприятий
		public function action_SwapSubmoduleOrder(){
			$data['success'] = false;
            $this->post -> rule('SubmoduleID1', 'not_empty')
                        -> rule('SubmoduleID1', 'digit')
						-> rule('SubmoduleID2', 'not_empty')
						-> rule('SubmoduleID2', 'digit');
            if($this->post->check()) {
				$result = $this->model->SwapSubmoduleOrder(
					$this->user['TeacherID'],
					$this->post->offsetGet('SubmoduleID1'),
					$this->post->offsetGet('SubmoduleID2')
				);
				if ($result[0]['Num'] == 0)
					$data['success'] = true;
            }
            $this->response->body(json_encode($data));
		}
		
		// Удалить модуль и его мероприятия
		public function action_DeleteModule() {
			$data['success'] = false;
            $this->post -> rule('ModuleID', 'not_empty')
                        -> rule('ModuleID', 'digit')
						-> rule('SubmodulesID', 'not_empty')
						-> rule('CurrentModuleOrder', 'not_empty')
                        -> rule('CurrentModuleOrder', 'digit');
            if($this->post->check()) {
				$ChangeOrderModulesID = json_decode($this->post->offsetGet('ChangeOrderModulesID'));
				$Submodules = json_decode($this->post->offsetGet('SubmodulesID'));
				foreach ($Submodules as &$SubmoduleID) {
					$this->privateDeleteSubmodule($SubmoduleID);
				}
                $result = $this->model->deleteModule(
					$this->user['TeacherID'],
					$this->post->offsetGet('ModuleID')
				);
				if ($result[0]['Num'] == 0) {
					if (count($ChangeOrderModulesID) > 0) {
						$NewOrder = $this->post->offsetGet('CurrentModuleOrder');
						foreach($ChangeOrderModulesID as $ModuleID) {
							$this->model->ChangeModuleOrder(
								$this->user['TeacherID'],
								$ModuleID,
								$NewOrder
							);
							$NewOrder++;
						}
					}
					$data['success'] = true;
				}
            }
            $this->response->body(json_encode($data));
        }
		
		// Удалить мероприятие
		public function action_DeleteSubmodule() {
			$data['success'] = false;
            $this->post -> rule('SubmoduleID', 'not_empty')
                        -> rule('SubmoduleID', 'digit')
						-> rule('CurrentSubmoduleOrder', 'not_empty')
                        -> rule('CurrentSubmoduleOrder', 'digit');
            if($this->post->check()) {
				$ChangeOrderSubmodulesID = json_decode($this->post->offsetGet('ChangeOrderSubmodulesID'));
                $result = $this->privateDeleteSubmodule($this->post->offsetGet('SubmoduleID'));
				if ($result == 0) {
					if (count($ChangeOrderSubmodulesID) > 0) {
						$NewOrder = $this->post->offsetGet('CurrentSubmoduleOrder');
						foreach($ChangeOrderSubmodulesID as $SubmoduleID) {
							$this->model->ChangeSubmoduleOrder(
								$this->user['TeacherID'],
								$SubmoduleID,
								$NewOrder
							);
							$NewOrder++;
						}
					}
					$data['success'] = true;
				}
			}
			$this->response->body(json_encode($data));
        }
		
		//  Изменение макс. балла подмодуля
		public function action_ChangeSubmoduleMaxRate() {
			$data['success'] = false;
            $this->post -> rule('SubmoduleID', 'not_empty')
                        -> rule('SubmoduleID', 'digit')
						-> rule('MaxRate', 'not_empty');
            if($this->post->check()) {
                 $result = $this->model->ChangeSubmoduleMaxRate(
					$this->user['TeacherID'],
					$this->post->offsetGet('SubmoduleID'), 
					$this->post->offsetGet('MaxRate')
				);
				if ($result[0]['Num'] == 0)
					$data['success'] = true;
            }
			$this->response->body(json_encode($data));
		}
		
		// Изменение типа подмодуля
		public function action_ChangeSubmoduleControlType() {
			$data['success'] = false;
            $this->post -> rule('SubmoduleID', 'not_empty')
                        -> rule('SubmoduleID', 'digit')
						-> rule('ControlType', 'not_empty');
            if($this->post->check()) {
                 $result = $this->model->ChangeSubmoduleControlType(
					$this->user['TeacherID'],
					$this->post->offsetGet('SubmoduleID'), 
					$this->post->offsetGet('ControlType')
				);
				if ($result[0]['Num'] == 0)
					$data['success'] = true;	
			}
			$this->response->body(json_encode($data));
		}
		
	// ------ Прикрипление студентов/групп/преподавателей --
	
		// Прикрепить группу
		public function action_BindGroup() {
			$data['success'] = false;
            $this->post -> rule('DisciplineID', 'not_empty')
                        -> rule('DisciplineID', 'digit')
						-> rule('StudyGroupID', 'not_empty')
						-> rule('StudyGroupID', 'digit');
            if($this->post->check()) {
                $result = $this->model->BindGroup($this->user['TeacherID'], $this->post->offsetGet('DisciplineID'), $this->post->offsetGet('StudyGroupID'));
				if ($result[0]['Num'] == 0)
					$data['success'] = true;
            }
			$this->response->body(json_encode($data));
		}
	
		// Отсоединить группу
		public function action_UnbindGroup() {
			$data['success'] = false;
            $this->post -> rule('DisciplineID', 'not_empty')
                        -> rule('DisciplineID', 'digit')
						-> rule('StudyGroupID', 'not_empty')
						-> rule('StudyGroupID', 'digit');
            if($this->post->check()) {
                $result = $this->model->UnbindGroup($this->user['TeacherID'], $this->post->offsetGet('DisciplineID'), $this->post->offsetGet('StudyGroupID'));
				if ($result[0]['Num'] == 0)
					$data['success'] = true;
            }
			$this->response->body(json_encode($data));
		}
	
		// Прикрепить студента
		public function action_BindStudent() {
			$data['success'] = false;
            $this->post -> rule('StudentID', 'not_empty')
                        -> rule('StudentID', 'digit')
						-> rule('DisciplineID', 'not_empty')
						-> rule('DisciplineID', 'digit');
            if($this->post->check()) {
                $result = $this->model->BindStudent($this->user['TeacherID'], $this->post->offsetGet('DisciplineID'), $this->post->offsetGet('StudentID'));
				if ($result[0]['Num'] == 0)
					$data['success'] = true;
            }
			$this->response->body(json_encode($data));
		}
		
		// Отсоединить студента 
		public function action_UnbindStudent() {
			$data['success'] = false;
            $this->post -> rule('StudentID', 'not_empty')
                        -> rule('StudentID', 'digit')
						-> rule('DisciplineID', 'not_empty')
						-> rule('DisciplineID', 'digit');
            if($this->post->check()) {
                $result = $this->model->UnbindStudent($this->user['TeacherID'], $this->post->offsetGet('DisciplineID'), $this->post->offsetGet('StudentID'));
				if ($result[0]['Num'] == 0)
					$data['success'] = true;
            }
			$this->response->body(json_encode($data));
		}
		
		
		public function action_SearchStudents() {
			$this->post -> rule('Grade', 'digit')
						-> rule('GroupN', 'digit')
						-> rule('FacultyID', 'digit');
			if($this->post->check()) {	
				$SeResult = $this->model->SearchStudents(
					$this->post->offsetGet('Grade'),
					$this->post->offsetGet('GroupN'),
					$this->post->offsetGet('FacultyID'),
					$this->post->offsetGet('Last'),
					$this->post->offsetGet('First'),
					$this->post->offsetGet('Second')
				); 
				$SearchResult = array();
				$i = 0;
				foreach($SeResult as $row){
					$i++;
					$SearchResult[$i]['StudentID'] = $row['StudentID'];
					$SearchResult[$i]['StudentLast'] = $row['StudentLast'];
					$SearchResult[$i]['StudentFirst'] = $row['StudentFirst'];
					$SearchResult[$i]['StudentSecond'] = $row['StudentSecond'];
					$SearchResult[$i]['GroupGrade'] = $row['GroupGrade'];
					$SearchResult[$i]['GroupNum'] = $row['GroupNum'];
				}
				$SearchResult['Count'] = $i;
			}
			$this->response->body(json_encode($SearchResult));
		}
		
		
		// Прикрепить преподавателя 
		public function action_BindTeacher() {
			$data['success'] = false;
            $this->post -> rule('BindingTeacher', 'not_empty')
                        -> rule('BindingTeacher', 'digit')
						-> rule('DisciplineID', 'not_empty')
						-> rule('DisciplineID', 'digit');
            if($this->post->check()) {
                $result = $this->model->BindTeacher($this->user['TeacherID'], $this->post->offsetGet('BindingTeacher'), $this->post->offsetGet('DisciplineID'));
				if ($result[0]['Num'] == 0)
					$data['success'] = true;
            }
			$this->response->body(json_encode($data));
		}
		
		// Отсоединить преподавателя 
		public function action_UnbindTeacher() {
			$data['success'] = false;
            $this->post -> rule('BindingTeacher', 'not_empty')
                        -> rule('BindingTeacher', 'digit')
						-> rule('DisciplineID', 'not_empty')
						-> rule('DisciplineID', 'digit');
            if($this->post->check()) {
                $result = $this->model->UnbindTeacher($this->user['TeacherID'], $this->post->offsetGet('BindingTeacher'), $this->post->offsetGet('DisciplineID'));
				if ($result[0]['Num'] == 0)
					$data['success'] = true;
            }
			$this->response->body(json_encode($data));
		}
		
		public function action_SearchTeachers() {
			$this->post -> rule('DepartmentID', 'digit');
			if($this->post->check()) {
				$SeResult = $this->model->SearchTeachers(
					$this->FacultyID,
					$this->post->offsetGet('DepartmentID'),
					$this->post->offsetGet('Last'),
					$this->post->offsetGet('First'),
					$this->post->offsetGet('Second')
				); 
				$SearchResult = array();
				$i = 0;
				foreach($SeResult as $row){
					$i++;
					$SearchResult[$i]['TeacherID'] = $row['TeacherID'];
					$SearchResult[$i]['TeacherLast'] = $row['TeacherLast'];
					$SearchResult[$i]['TeacherFirst'] = $row['TeacherFirst'];
					$SearchResult[$i]['TeacherSecond'] = $row['TeacherSecond'];
					$SearchResult[$i]['JobPositionName'] = $row['JobPositionName'];
					$SearchResult[$i]['DepID'] = $row['DepID'];
				}
				$SearchResult['Count'] = $i;
			}
			$this->response->body(json_encode($SearchResult));
		}
}