diff --git a/drupal/modules/epal/epal.module b/drupal/modules/epal/epal.module
index f52f5a26e4150ded3147ed8bf5c6b5df4bd39d54..4d30cae327caee577c8615433adbdf2ce7ba2bf4 100755
--- a/drupal/modules/epal/epal.module
+++ b/drupal/modules/epal/epal.module
@@ -46,10 +46,15 @@ function epal_mail($key, &$message, $params) {
         $message['subject'] = t('Σύστημα υποβολΞ�Ο‚ Ξ±ΞΉΟ„Ξ�σΡων ΡγγραφΞ�Ο‚ σΡ ΕΠΑΛ: ΕπιβΡβαίωση e-mail', $options);
         $message['body'][] = $params['message'];
         break;
-      case 'massive_mail':
+      case 'massive_mail_unallocated':
         $message['from'] = \Drupal::config('system.site')->get('mail');
         $message['subject'] = t('Μη ικανοποίηση ηλΡκτρονικΞ�Ο‚ αίτησης Ξ³ΞΉΞ± ΡγγραφΞ� σΡ ΕΠΑΛ', $options);
         $message['body'][] = $params['message'];
         break;
+      case 'massive_mail_located':
+        $message['from'] = \Drupal::config('system.site')->get('mail');
+        $message['subject'] = t('Ικανοποίηση ηλΡκτρονικΞ�Ο‚ αίτησης Ξ³ΞΉΞ± ΡγγραφΞ� σΡ ΕΠΑΛ', $options);
+        $message['body'][] = $params['message'];
+        break;
     }
 }
diff --git a/drupal/modules/epal/epal.routing.yml b/drupal/modules/epal/epal.routing.yml
index 394f39c81cdf6f058bd76dd0dfd0dba52df47c7f..2ffe9ae84b431efc7616ce486f594e2dd00bf036 100755
--- a/drupal/modules/epal/epal.routing.yml
+++ b/drupal/modules/epal/epal.routing.yml
@@ -151,7 +151,7 @@ epal.ministry.report-completeness:
   requirements:
     _user_is_logged_in: 'TRUE'
 epal.ministry.report-all-stat:
-  path: '/ministry/report-all-stat/{regionId}/{adminId}/{schId}/{classId}/{sectorId}/{courseId}'
+  path: '/ministry/report-all-stat/{regionId}/{adminId}/{schId}/{classId}/{sectorId}/{courseId}/{finalized}'
   options:
     _auth: [ 'basic_auth' ]
   defaults:
@@ -174,12 +174,20 @@ epal.ministry.retrieve-registry-id:
     _controller: '\Drupal\epal\Controller\ReportsCreator::retrieveUserRegistryNo'
   requirements:
     _user_is_logged_in: 'TRUE'
-epal.ministry.massive_mail:
-  path: '/ministry/send-massive-mail'
+epal.ministry.massive_mail_unallocated:
+  path: '/ministry/send-unallocated-massive-mail'
   options:
     _auth: [ 'basic_auth' ]
   defaults:
-    _controller: '\Drupal\epal\Controller\InformUnlocatedStudents::sendMailToStudents'
+    _controller: '\Drupal\epal\Controller\InformUnlocatedStudents::sendMailToUnallocatedStudents'
+  requirements:
+    _user_is_logged_in: 'TRUE'
+epal.ministry.massive_mail_located:
+  path: '/ministry/send-located-massive-mail'
+  options:
+    _auth: [ 'basic_auth' ]
+  defaults:
+    _controller: '\Drupal\epal\Controller\InformUnlocatedStudents::sendMailToLocatedStudents'
   requirements:
     _user_is_logged_in: 'TRUE'
 epal.ministry.retrievesettings:
@@ -203,7 +211,7 @@ epal.perfectureschools:
   options:
     _auth: [ 'basic_auth' ]
   defaults:
-    _controller: '\Drupal\epal\Controller\DirectorView::getSchoolsPerPerfecture'
+    _controller: '\Drupal\epal\Controller\DirectorView::getSchools'
   requirements:
     _user_is_logged_in: 'TRUE'
 epal.coursesperschools:
@@ -246,3 +254,11 @@ epal.gettypeofschool:
     _controller: '\Drupal\epal\Controller\DirectorView::gettypeofschool'
   requirements:
     _user_is_logged_in: 'TRUE'
+getlimitspercourse:
+  path: '/epal/getlimitsperCourse/{classid}'
+  options:
+    _auth: [ 'basic_auth' ]
+  defaults:
+    _controller: '\Drupal\epal\Controller\DirectorView::getlimitsperCourse'
+  requirements:
+    _user_is_logged_in: 'TRUE'
diff --git a/drupal/modules/epal/src/Controller/DirectorView.php b/drupal/modules/epal/src/Controller/DirectorView.php
index 865e3f43b879437d89fed4debc1bfc6a638a7eda..c4d1cb4c93e8424b842f0ec5758695a5a1964b1b 100755
--- a/drupal/modules/epal/src/Controller/DirectorView.php
+++ b/drupal/modules/epal/src/Controller/DirectorView.php
@@ -426,8 +426,7 @@ public function SaveCapacity(Request $request,$taxi,$tomeas,$specialit)
     }
 
 
-
-    public function getSchoolsPerPerfecture(Request $request)
+    public function getSchools(Request $request)
     {
 
         $authToken = $request->headers->get('PHP_AUTH_USER');
@@ -436,14 +435,32 @@ public function SaveCapacity(Request $request,$taxi,$tomeas,$specialit)
         $user = reset($users);
         if ($user)
             {
-                $perfectureId = $user ->  init -> value;
-                $schools = $this->entityTypeManager->getStorage('eepal_school')->loadByProperties(array('region_edu_admin_id'=> $perfectureId ));
+                $selectionId = $user ->  init -> value;
+                $userRoles = $user->getRoles();
+                $userRole = '';
+                foreach ($userRoles as $tmpRole) {
+                    if (($tmpRole === 'epal') || ($tmpRole === 'regioneduadmin') || ($tmpRole === 'eduadmin')) {
+                        $userRole = $tmpRole;
+                    }
+                }
+                if ($userRole === '') {
+                    return $this->respondWithStatus([
+                             'error_code' => 4003,
+                         ], Response::HTTP_FORBIDDEN);
+                }
+
+                else if ($userRole === 'regioneduadmin') {
+                    $schools = $this->entityTypeManager->getStorage('eepal_school')->loadByProperties(array('region_edu_admin_id'=> $selectionId ));
+                }
+                else if ($userRole === 'eduadmin') {
+                    $schools = $this->entityTypeManager->getStorage('eepal_school')->loadByProperties(array('edu_admin_id'=> $selectionId ));
+                }
                 if ($schools)
                 {
                     $list = array();
 
                     foreach ($schools as $object) {
-                             $status = $this->returnstatus(147);
+                             $status = $this->returnstatus($object -> id());
                              $list[] = array(
                                     'id' =>$object -> id(),
                                     'name' => $object -> name ->value,
@@ -595,10 +612,74 @@ public function SaveCapacity(Request $request,$taxi,$tomeas,$specialit)
 
 public function returnstatus($id)
 {
-    if ($id == 147)
-       return true ;
-    return false;
+                $schoolid = $id;
+                $SchoolCats = $this->entityTypeManager->getStorage('eepal_school')->loadByProperties(array('id'=> $schoolid ));
+                $SchoolCat = reset($SchoolCats);
+                if ($SchoolCat){
+                $categ = $SchoolCat-> metathesis_region -> value;
+                }
+                $CourseA = $this->entityTypeManager->getStorage('epal_student')->loadByProperties(array('id'=> $schoolid ));
 
+                if ($CourseA)
+                {
+                    $limit_down = $this->entityTypeManager->getStorage('epal_class_limits')->loadByProperties(array('name'=> 1, 'category' => $categ ));
+                    $limitdown = reset($limit_down);
+                    if ($limitdown)
+                    {
+                        $limit = $limitdown -> limit_down -> value;
+                    }
+                    $studentPerSchool = $this->entityTypeManager->getStorage('epal_student_class')->loadByProperties(array('currentepal'=> $schoolid, 'specialization_id' => -1, 'currentclass' => 1 ));
+
+                    //foreach ($CourseA as $object) {
+                            if (sizeof($studentPerSchool) < $limit){
+                                return false;
+//                                exit;
+                            }
+
+                }          //  }
+
+
+                $CourseB = $this->entityTypeManager->getStorage('eepal_sectors_in_epal')->loadByProperties(array('epal_id' => $schoolid ));
+                if ($CourseB)
+                {
+                    $limit_down = $this->entityTypeManager->getStorage('epal_class_limits')->loadByProperties(array('name'=> 2, 'category' => $categ ));
+                    $limitdown = reset($limit_down);
+                    if ($limitdown)
+                    {
+                        $limit = $limitdown -> limit_down -> value;
+                    }
+
+                    foreach ($CourseB as $object) {
+                    $sectorid = $object -> sector_id -> entity -> id();
+                    $studentPerSchool = $this->entityTypeManager->getStorage('epal_student_class')->loadByProperties(array('currentepal'=> $schoolid, 'specialization_id' => $sectorid, 'currentclass' => 2 ));
+                         if (sizeof($studentPerSchool) < $limit){
+                                return false;
+                                exit;
+                            }
+                    }
+                }
+                $CourseC = $this->entityTypeManager->getStorage('eepal_specialties_in_epal')->loadByProperties(array('epal_id' => $schoolid ));
+                if ($CourseC)
+                {
+                    $limit_down = $this->entityTypeManager->getStorage('epal_class_limits')->loadByProperties(array('name'=> 3, 'category' => $categ ));
+                    $limitdown = reset($limit_down);
+                    if ($limitdown)
+                    {
+                        $limit = $limitdown -> limit_down -> value;
+                    }
+
+                    foreach ($CourseC as $object) {
+                    $specialityid = $object -> specialty_id -> entity -> id() ;
+                    $studentPerSchool = $this->entityTypeManager->getStorage('epal_student_class')->loadByProperties(array('currentepal'=> $schoolid, 'specialization_id' => $specialityid, 'currentclass' => 3 ));
+
+                         if (sizeof($studentPerSchool) < $limit){
+                                return false;
+                                exit;
+                                }
+                    }
+                }
+                return true;
+//                exit;
 }
 
 
@@ -784,6 +865,115 @@ public function gettypeofschool(Request $request)
     }
 
 
+
+
+    public function getlimitsperCourse(Request $request, $classid)
+    {
+      $authToken = $request->headers->get('PHP_AUTH_USER');
+
+        $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
+        $user = reset($users);
+        if ($user)
+            {
+              $schoolid = $user ->  init -> value;
+               $list= array();
+
+                $SchoolCats = $this->entityTypeManager->getStorage('eepal_school')->loadByProperties(array('id'=> $schoolid ));
+                $SchoolCat = reset($SchoolCats);
+                if ($SchoolCat){
+                $categ = $SchoolCat-> metathesis_region -> value;
+
+                 $list = array();
+               if ($classid == 1)
+               {
+
+                    $limit_down = $this->entityTypeManager->getStorage('epal_class_limits')->loadByProperties(array('name'=> 1, 'category' => $categ ));
+                    $limitdown = reset($limit_down);
+                    if ($limitdown)
+                    {
+                        $limit = $limitdown -> limit_down -> value;
+                    }
+
+
+
+                             $list[] = array(
+                                    'id' => '1',
+                                    'name' => 'Ξ‘ ΛυκΡίου',
+                                    'categ' => $categ,
+                                    'classes' => 1,
+                                    'limitdown' => $limit,
+                                    );
+
+                }
+
+
+                if ($classid == 2){
+                    $limit_down = $this->entityTypeManager->getStorage('epal_class_limits')->loadByProperties(array('name'=> 2, 'category' => $categ ));
+                    $limitdown = reset($limit_down);
+                    if ($limitdown)
+                    {
+                        $limit = $limitdown -> limit_down -> value;
+                    }
+
+
+
+                         $list[] = array(
+
+                            'name' => 'Ξ’ ΛυκΡίου ',
+
+                            'categ' => $categ,
+                            'classes' => 2,
+                            'limitdown' => $limit,
+
+                          );
+                    }
+
+
+                if ($classid == 3){
+                    $limit_down = $this->entityTypeManager->getStorage('epal_class_limits')->loadByProperties(array('name'=> 3, 'category' => $categ ));
+                    $limitdown = reset($limit_down);
+                    if ($limitdown)
+                    {
+                        $limit = $limitdown -> limit_down -> value;
+                    }
+
+
+
+                         $list[] = array(
+
+
+                            'categ' => $categ,
+                            'classes' => 3,
+                            'limitdown' => $limit,
+
+                          );
+                    }
+
+
+
+                            return $this->respondWithStatus(
+                                     $list
+                                   , Response::HTTP_OK);
+                }
+                else
+                {
+                       return $this->respondWithStatus([
+                            'message' => t("Perfecture not found!"),
+                        ], Response::HTTP_FORBIDDEN);
+
+                }
+            }
+            else
+            {
+
+                   return $this->respondWithStatus([
+                            'message' => t("User not found!"),
+                        ], Response::HTTP_FORBIDDEN);
+            }
+    }
+
+
+
    private function respondWithStatus($arr, $s) {
         $res = new JsonResponse($arr);
         $res->setStatusCode($s);
diff --git a/drupal/modules/epal/src/Controller/Distribution.php b/drupal/modules/epal/src/Controller/Distribution.php
index 61b005daf89daabe7b98cb160649a237e2c3bf46..719c475204775255e48ab54c821cc500c438f630 100755
--- a/drupal/modules/epal/src/Controller/Distribution.php
+++ b/drupal/modules/epal/src/Controller/Distribution.php
@@ -4,6 +4,7 @@
  * Contains \Drupal\query_example\Controller\QueryExampleController.
  */
 
+
 namespace Drupal\epal\Controller;
 
 use Drupal\Core\Entity\Query\QueryFactory;
@@ -24,6 +25,12 @@ use Drupal\Core\TypedData\Plugin\DataType\TimeStamp;
 
 use Drupal\Core\Language\LanguageManagerInterface;
 
+define("SUCCESS", 0);
+define("ERROR_DB", -1);
+define("NO_CLASS_LIMIT_DOWN", -2);
+define("SMALL_CLASS", 1);
+define("NON_SMALL_CLASS", 2);
+
 class Distribution extends ControllerBase {
 
 	protected $entity_query;
@@ -68,9 +75,15 @@ class Distribution extends ControllerBase {
 
 	public function createDistribution(Request $request) {
 
+		//$this->findSmallClasses();
+		//return;
+
+
+
 		$numDistributions = 3;
 		$sizeOfBlock = 100000;
 
+
 		//POST method is checked
 		if (!$request->isMethod('POST')) {
 			return $this->respondWithStatus([
@@ -101,6 +114,7 @@ class Distribution extends ControllerBase {
 								'message' => t("User Invalid Role"),
 						], Response::HTTP_FORBIDDEN);
 		}
+		
 
 		 //check where distribution can be done now ($capacityDisabled / $directorViewDisabled settings)
 		$capacityDisabled = false;
@@ -188,9 +202,7 @@ class Distribution extends ControllerBase {
 				//checkCapacityAndArrange (school_id, class_id, sectorORcourse_id, limitUp, schoolCapacity)
 
 				$sCon = $this->connection->select('eepal_school_field_data', 'eSchool')
-																	->fields('eSchool', array('id', 'capacity_class_a'));
-																	//->condition('eSchool.id', 151, '>=')
-																	//->condition('eSchool.id', 153, '<=');	//προσαρμοσμένο Ξ³ΞΉΞ± τα demo data --> Ξ½Ξ± αλλάξΡι
+																	->fields('eSchool', array('id', 'capacity_class_a', 'operation_shift'));
 				$eepalSchools = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
 
 				foreach ($eepalSchools as $eepalSchool)	{
@@ -212,7 +224,9 @@ class Distribution extends ControllerBase {
 						foreach ($eepalSpecialtiesInEpal as $eepalSpecialInEp)	{
 							$this->checkCapacityAndArrange($eepalSchool->id, "3", $eepalSpecialInEp->specialty_id, $limitUp_class, $eepalSpecialInEp->capacity_class_specialty);
 							//Ξ”' ΛυκΡίου
-							$this->checkCapacityAndArrange($eepalSchool->id, "4", $eepalSpecialInEp->specialty_id, $limitUp_class, $eepalSpecialInEp->capacity_class_specialty);
+							if ($eepalSchool->operation_shift === "Ξ•Ξ£Ξ Ξ•Ξ‘Ξ™ΞΞŸ")	{
+								$this->checkCapacityAndArrange($eepalSchool->id, "4", $eepalSpecialInEp->specialty_id, $limitUp_class, $eepalSpecialInEp->capacity_class_specialty);
+							}
 						}
 
 					} //end for each school/department
@@ -221,6 +235,7 @@ class Distribution extends ControllerBase {
 
 	  	} //end while
 
+			$this->findSmallClasses();
 
 		}	//end try
 
@@ -232,14 +247,6 @@ class Distribution extends ControllerBase {
 				], Response::HTTP_INTERNAL_SERVER_ERROR);
 		}
 
-		//return new RedirectResponse($this->redirectUrl . '?auth_token=' . $epalToken.'&auth_role=director', 302, []);
-		//return new RedirectResponse("../eepal/dist/#/minister/minister-view");
-
-		/*
-		return $this->respondWithStatus([
-					"message" => t("Distribution has made successfully")
-				], Response::HTTP_OK);
-		*/
 		$postData = null;
 		if ($content = $request->getContent()) {
 				$postData = json_decode($content);
@@ -305,7 +312,6 @@ class Distribution extends ControllerBase {
 						$specialization_id = -1;
 
 
-				 //$currentTime = \Drupal\Core\TypedData\Plugin\DataType\TimeStamp::getDateTime();
 					$timestamp = strtotime(date("Y-m-d"));
 					$this->connection->insert('epal_student_class')->fields(
 						array('id' => $this->globalCounterId++,
@@ -319,6 +325,7 @@ class Distribution extends ControllerBase {
 							'specialization_id' => $specialization_id,
 							'points' => $epalStudent->points,
 							'distribution_id' => $choice_id,
+							'finalized' => 1,
 							'status' => 1,
 							'created' => $timestamp,
 							'changed' => $timestamp,)
@@ -367,7 +374,14 @@ class Distribution extends ControllerBase {
 	return $row->limit_up;
  }
 
-	public function checkCapacityAndArrange($epalId, $classId, $secCourId, $limitup, $capacity)	{
+
+public function checkCapacityAndArrange($epalId, $classId, $secCourId, $limitup, $capacity)	{
+
+		if (!isset($capacity))	{
+			//print_r("<br> ΞœΞ Ξ—ΞšΞ‘!!! ");
+			//print_r("<br> Ξ£Ξ§ΞŸΞ›Ξ•Ξ™ΞŸ: " .  $epalId . " Ξ€Ξ‘ΞžΞ—: "  . $classId . " Ξ€ΞŸΞœΞ•Ξ‘Ξ£/Ξ•Ξ™Ξ”Ξ™ΞšΞŸΞ€Ξ—Ξ€Ξ‘: " . $secCourId .  " Ξ§Ξ©Ξ‘Ξ—Ξ€Ξ™ΞšΞŸΞ€Ξ—Ξ€Ξ‘: " . $capacity);
+		 	$capacity = 0;
+		}
 
 		$transaction = $this->connection->startTransaction();
 
@@ -451,11 +465,10 @@ class Distribution extends ControllerBase {
 		//$this->pendingStudents = array_diff($this->pendingStudents, array($val));
 	}
 
-	public function makeSelectionOfStudents(&$students, $limit)	{
+	public function makeSelectionOfStudents_VERSION_WITH_POINTS(&$students, $limit)	{
 		//συνάρτηση ΡπιλογΞ�Ο‚ ΞΌΞ±ΞΈΞ·Ο„ΟŽΞ½ σΡ πΡρίπτωση υπΡρχΡίλισης
 		// (1) έχουν Ξ±Ο€ΟŒΞ»Ο…Ο„Ξ· Ο€ΟΞΏΟ„Ξ΅ΟΞ±ΞΉΟŒΟ„Ξ·Ο„Ξ± ΟŒΟƒΞΏΞΉ Ξ�δη φοιτούσαν στο σχολΡίο (σΡ πΡρίπτωση που φοιτούσαν Ο€Ξ΅ΟΞΉΟƒΟƒΟŒΟ„Ξ΅ΟΞΏΞΉ Ξ±Ο€ΟŒ την Ο‡Ο‰ΟΞ·Ο„ΞΉΞΊΟŒΟ„Ξ·Ο„Ξ±, τους Ξ΄Ξ΅Ο‡ΟŒΞΌΞ±ΟƒΟ„Ξ΅ ΟŒΞ»ΞΏΟ…Ο‚)
 		// (2) Ξ±Ξ½ απομένουν κΡνές θέσΡις, ΡπέλΡξΡ Ξ±Ο€ΟŒ τους ΡναπομΡίναντΡς μαθητές αυτούς ΞΌΞ΅ τα Ο€Ξ΅ΟΞΉΟƒΟƒΟŒΟ„Ξ΅ΟΞ± μόρια. ΣΡ πΡρίπτωση ισοβαθμίας Ξ΄Ξ΅Ο‡ΟŒΞΌΞ±ΟƒΟ„Ξ΅ ΟŒΞ»ΞΏΟ…Ο‚ ΟŒΟƒΞΏΟ…Ο‚ ισοβαθμούν.
-		//αυτοδίκαια έχουν Ο€ΟΞΏΟ„Ξ΅ΟΞ±ΞΉΟŒΟ„Ξ·Ο„Ξ± ΟŒΟƒΞΏΞΉ Ξ�δη φοιτούσαν στο σχολΡίο
 
 		foreach($students as $student)	{
 			$student->student_id;
@@ -525,6 +538,66 @@ class Distribution extends ControllerBase {
 			], Response::HTTP_OK);
 	}
 
+
+
+	public function makeSelectionOfStudents(&$students, $limit)	{
+		//συνάρτηση ΡπιλογΞ�Ο‚ ΞΌΞ±ΞΈΞ·Ο„ΟŽΞ½ σΡ πΡρίπτωση υπΡρχΡίλισης
+		// (1) έχουν Ξ±Ο€ΟŒΞ»Ο…Ο„Ξ· Ο€ΟΞΏΟ„Ξ΅ΟΞ±ΞΉΟŒΟ„Ξ·Ο„Ξ± ΟŒΟƒΞΏΞΉ Ξ�δη φοιτούσαν στο σχολΡίο (σΡ πΡρίπτωση που φοιτούσαν Ο€Ξ΅ΟΞΉΟƒΟƒΟŒΟ„Ξ΅ΟΞΏΞΉ Ξ±Ο€ΟŒ την Ο‡Ο‰ΟΞ·Ο„ΞΉΞΊΟŒΟ„Ξ·Ο„Ξ±, τους Ξ΄Ξ΅Ο‡ΟŒΞΌΞ±ΟƒΟ„Ξ΅ ΟŒΞ»ΞΏΟ…Ο‚)
+		// (2) Ξ±Ξ½ απομένουν κΡνές θέσΡις,...τοποθέτησΡ ΞΊΞ±ΞΉ ΟŒΞ»ΞΏΟ…Ο‚ τους άλλους!!.
+
+		//ΡύρΡση αριθμού ΞΌΞ±ΞΈΞ·Ο„ΟŽΞ½ που Ξ�δη φοιτούσαν στο σχολΡίο
+		$cnt = 0;
+		foreach($students as $student)	{
+			if ($student->currentepal === $student->epal_id) {
+				$cnt++;
+				if ($this->choice_id !== 1)
+					//διέγραψΡ τον ΞΌΞ±ΞΈΞ·Ο„Ξ� Ξ±Ο€ΟŒ τον πίνακα ΡκκρΡμοτΞ�των (Ξ±Ξ½ βρίσκΡται ΡκΡί)
+					//ΞšΞ¬Ο„ΞΉ τέτοιο δΡν Ρίναι Ξ΄Ο…Ξ½Ξ±Ο„ΟŒ πια! (έκδοση χωρίς μόρια..)
+					$this->removeFromPendingStudents($student->student_id);
+			}
+		}
+		//print_r("<br>#ΕΓΓΑΑΦΩΝ ΠΟΞ₯ ΞŸΞ™ ΞœΞ‘Ξ˜Ξ—Ξ€Ξ•Ξ£ Ξ¦ΞŸΞ™Ξ€ΞŸΞ₯ΣΑΝ ΗΔΗ:" . $cnt);
+
+		$newlimit = $limit - $cnt;
+		//print_r("<br>Ξ‘ΞΞ©Ξ€Ξ‘Ξ€ΞŸ ΞŸΞ‘Ξ™ΞŸ ΞœΞ‘Ξ˜Ξ—Ξ€Ξ©Ξ:" . $limit);
+
+		$transaction = $this->connection->startTransaction();
+
+		//Αν δΡν απέμΡιναν θέσΡις (δηλαδΞ� Ξ±Ξ½ Ξ· Ο‡Ο‰ΟΞ·Ο„ΞΉΞΊΟŒΟ„Ξ·Ο„Ξ± Ρίναι ΞΌΞΉΞΊΟΟŒΟ„Ξ΅ΟΞ· Ξ� ίση Ξ±Ο€ΟŒ το πλΞ�ΞΈΞΏΟ‚ ΞΌΞ±ΞΈΞ·Ο„ΟŽΞ½ που Ξ�δη φοιτούν στο σχολΡίο)
+		//Ο„ΟŒΟ„Ξ΅ διέγραψέ τους Ξ±Ο€ΟŒ τον Ο€ΟΞΏΟƒΟ‰ΟΞΉΞ½ΟŒ πίνακα αποτΡλΡσμάτων ΞΊΞ±ΞΉ βάλΡ τους στον στον πίνακα ΡκκρΡμοτΞ�των
+		if ($newlimit <= 0) {
+			foreach($students as $student)	{
+				if ($student->currentepal !== $student->epal_id)	{
+						//print_r("<br>ΣΕ Ξ•ΞšΞšΞ‘Ξ•ΞœΞŸΞ€Ξ—Ξ€Ξ‘ - ΔΙΑΓΑΑΦΗ: " . $student->student_id);
+						array_push($this->pendingStudents, $student->student_id);
+						try {
+							$this->connection->delete('epal_student_class')
+														->condition('student_id', $student->student_id)
+														->execute();
+						}
+						catch (\Exception $e) {
+							$this->logger->warning($e->getMessage());
+							$transaction->rollback();
+							return $this->respondWithStatus([
+										"message" => t("An unexpected problem occured during DELETE proccess in makeSelectionOfStudents Method of Distribution")
+									], Response::HTTP_INTERNAL_SERVER_ERROR);
+						}
+					} //end if currentepal
+			 }	//end foreach
+		}	//endif newlimit
+
+		return $this->respondWithStatus([
+				"message" => t("makeSelectionOfStudents Method of Distribution has made successfully")
+			], Response::HTTP_OK);
+
+	}	//end function
+
+
+
+
+
+
+
 	public function calculatePoints()	{
 
 			return rand(0,20);
@@ -537,7 +610,7 @@ class Distribution extends ControllerBase {
 				return $res;
 		}
 
-		private function initializeResults() {
+	private function initializeResults() {
 
 			//initialize/empty epal_student_class if there are already data in it!
 			try  {
@@ -549,11 +622,169 @@ class Distribution extends ControllerBase {
 							"message" => t("An unexpected problem occured during initializeResults Method of Distribution")
 						], Response::HTTP_INTERNAL_SERVER_ERROR);
 			}
+		}
+
+
+
+	private function findSmallClasses()	{
 
+		//Για κάθΡ σχολΡίο βρΡς τα ολιγομΡλΞ� τμΞ�ματα
+		$sCon = $this->connection->select('eepal_school_field_data', 'eSchool')
+															->fields('eSchool', array('id', 'metathesis_region','operation_shift'));
+		$eepalSchools = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
 
+		foreach ($eepalSchools as $eepalSchool)	{
 
+				//isSmallClass (school_id, class_id, sectorORcourse_id, school_category_metathesis)
+
+				// Ξ‘' τάξη
+				if ($this->isSmallClass($eepalSchool->id, "1", "-1", $eepalSchool->metathesis_region) === SMALL_CLASS)	{
+					//print_r("<br> ΞšΞ›Ξ—Ξ£Ξ— markStudentsInSmallClass: SCHOOL_ID: " . $eepalSchool->id . " CLASSID: " . "1 " . "SECTOR/COURSE ID: " . "-1 ");
+					if ($this->markStudentsInSmallClass($eepalSchool->id, "1", "-1") === ERROR_DB )
+						return ERROR_DB;
+				}
+
+				//print_r("<br>");
+
+
+				// Ξ’' τάξη
+				$sCon = $this->connection->select('eepal_sectors_in_epal_field_data', 'eSchool')
+																	->fields('eSchool', array('epal_id', 'sector_id'))
+																	->condition('eSchool.epal_id', $eepalSchool->id, '=');
+				$eepalSectorsInEpal = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
+				foreach ($eepalSectorsInEpal as $eepalSecInEp)	{
+					if ($this->isSmallClass($eepalSchool->id, "2", $eepalSecInEp->sector_id, $eepalSchool->metathesis_region) === SMALL_CLASS)	{
+						//print_r("<br> ΞšΞ›Ξ—Ξ£Ξ— markStudentsInSmallClass: SCHOOL_ID: " . $eepalSchool->id . " CLASSID: " . "2 " . "SECTOR/COURSE ID: " . $eepalSecInEp->sector_id);
+						if ($this->markStudentsInSmallClass($eepalSchool->id, "2", $eepalSecInEp->sector_id) === ERROR_DB )
+							return ERROR_DB;
+					}
+					//print_r("<br>");
+				}
+
+				// Ξ“' τάξη
+				$sCon = $this->connection->select('eepal_specialties_in_epal_field_data', 'eSchool')
+																	->fields('eSchool', array('epal_id', 'specialty_id'))
+																	->condition('eSchool.epal_id', $eepalSchool->id, '=');
+				$eepalSpecialtiesInEpal = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
+				foreach ($eepalSpecialtiesInEpal as $eepalSpecialInEp)	{
+					if ($this->isSmallClass($eepalSchool->id, "3", $eepalSpecialInEp->specialty_id, $eepalSchool->metathesis_region) === SMALL_CLASS)	{
+						//print_r("<br> ΞšΞ›Ξ—Ξ£Ξ— markStudentsInSmallClass: SCHOOL_ID: " . $eepalSchool->id . " CLASSID: " . "3 " . "SECTOR/COURSE ID: " . $eepalSpecialInEp->specialty_id);
+						if ($this->markStudentsInSmallClass($eepalSchool->id, "3", $eepalSpecialInEp->specialty_id) === ERROR_DB )
+							return ERROR_DB;
+					}
+					//print_r("<br>");
+				}
+
+				// Ξ”' τάξη
+				if ($eepalSchool->operation_shift === "Ξ•Ξ£Ξ Ξ•Ξ‘Ξ™ΞΞŸ")	{
+					$sCon = $this->connection->select('eepal_specialties_in_epal_field_data', 'eSchool')
+																		->fields('eSchool', array('epal_id', 'specialty_id'))
+																		->condition('eSchool.epal_id', $eepalSchool->id, '=');
+					$eepalSpecialtiesInEpal = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
+					foreach ($eepalSpecialtiesInEpal as $eepalSpecialInEp)	{
+						if ($this->isSmallClass($eepalSchool->id, "4", $eepalSpecialInEp->specialty_id, $eepalSchool->metathesis_region) === SMALL_CLASS)	{
+							//print_r("<br> ΞšΞ›Ξ—Ξ£Ξ— markStudentsInSmallClass: SCHOOL_ID: " . $eepalSchool->id . " CLASSID: " . "4 " . "SECTOR/COURSE ID: " . $eepalSpecialInEp->specialty_id);
+							if ($this->markStudentsInSmallClass($eepalSchool->id, "4", $eepalSpecialInEp->specialty_id) === ERROR_DB )
+								return ERROR_DB;
+						}
+						//print_r("<br>");
+					}
+				}	//end if Ξ•Ξ£Ξ Ξ•Ξ‘Ξ™ΞΞŸ
+
+
+
+			} //end for each school/department
+
+	}	//end function
+
+
+	private function isSmallClass($schoolId, $classId, $sectorOrcourseId, $regionId)	{
+
+		//print_r("<br> ΞšΞ›Ξ—Ξ£Ξ— isSmallClass: SCHOOL_ID: " . $schoolId . " CLASSID: " . $classId . "SECTOR/COURSE ID: " . $sectorOrcourseId . "Ξ Ξ•Ξ‘Ξ™ΞŸΞ§Ξ— ΞœΞ•Ξ€Ξ‘Ξ˜Ξ•Ξ£Ξ—Ξ£: " . $regionId);
+
+		$limitDown = $this->retrieveLimitDown($classId, $regionId);
+		//print_r("<br> ΞšΞ‘Ξ€Ξ©Ξ€Ξ‘Ξ€ΞŸ ΞŸΞ‘Ξ™ΞŸ ΞœΞ‘Ξ˜Ξ—Ξ€Ξ©Ξ: " . $limitDown);
+
+		if ($limitDown === NO_CLASS_LIMIT_DOWN)
+			return NO_CLASS_LIMIT_DOWN;
+		else if ($limitDown === ERROR_DB)
+			return ERROR_DB;
+
+		$numStudents = $this->countStudents($schoolId, $classId, $sectorOrcourseId);
+		//print_r("<br> Ξ‘Ξ‘Ξ™Ξ˜ΞœΞŸΞ£ ΞœΞ‘Ξ˜Ξ—Ξ€Ξ©Ξ: " . $numStudents);
+
+		if ($numStudents === ERROR_DB)
+			return ERROR_DB;
+
+		//Αν $numStudents == 0, γύρισΡ fasle, ΟŽΟƒΟ„Ξ΅ Ξ½Ξ± ΞΌΞ· γίνΡι πΡριττΞ� ΞΊΞ»Ξ�ση στην markStudentsInSmallClass
+		if ( ($numStudents < $limitDown) && ($numStudents > 0) )
+			return SMALL_CLASS;
+		else
+			return NON_SMALL_CLASS;
+
+	}
+
+	private function retrieveLimitDown($classId, $regionId)	{
+
+		try {
+			$sCon = $this->connection->select('epal_class_limits', 'eClassLimit')
+																->fields('eClassLimit', array('limit_down'))
+																->condition('eClassLimit.name', $classId, '=')
+																->condition('eClassLimit.category', $regionId, '=');
+			$classLimits = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
+			if (sizeof($classLimits) === 1)	{
+				$classLimit = reset($classLimits);
+				return $classLimit->limit_down;
+			}
+			else {
+				return NO_CLASS_LIMIT_DOWN;
+			}
+		}	//end try
+		catch (\Exception $e) {
+			$this->logger->warning($e->getMessage());
+			return ERROR_DB;
+		}
+
+	}	//end function
+
+	private function countStudents($schoolId, $classId, $sectorOrcourseId)	{
+
+		try {
+			$sCon = $this->connection->select('epal_student_class', 'eStudent')
+																->fields('eStudent', array('id'))
+																->condition('eStudent.epal_id', $schoolId , '=')
+																->condition('eStudent.currentclass', $classId , '=')
+																->condition('eStudent.specialization_id', $sectorOrcourseId , '=');
+			return $sCon->countQuery()->execute()->fetchField();
+		}
+		catch (\Exception $e) {
+			$this->logger->warning($e->getMessage());
+			return ERROR_DB;
 		}
 
+	}
+
+	private function markStudentsInSmallClass($schoolId, $classId, $sectorOrcourseId)	{
+
+		try  {
+			$query = $this->connection->update('epal_student_class');
+			$query->fields([
+				'finalized' => 0,
+			]);
+			$query->condition('epal_id', $schoolId);
+			$query->condition('currentclass', $classId);
+			if ($sectorOrcourseId !== "-1")
+				$query->condition('specialization_id', $sectorOrcourseId);
+			$query->execute();
+		}
+		catch (\Exception $e) {
+			$this->logger->warning($e->getMessage());
+			return ERROR_DB;
+		}
+		return SUCCESS;
+
+	}
+
 
 
 
diff --git a/drupal/modules/epal/src/Controller/InformUnlocatedStudents.php b/drupal/modules/epal/src/Controller/InformUnlocatedStudents.php
index 720255e261973ae3a50facc73d01c824ed81656c..effcc1bde91a20936644765ee2cb42361f9eb862 100644
--- a/drupal/modules/epal/src/Controller/InformUnlocatedStudents.php
+++ b/drupal/modules/epal/src/Controller/InformUnlocatedStudents.php
@@ -56,7 +56,7 @@ class InformUnlocatedStudents extends ControllerBase {
     }
 
 
-	public function sendMailToStudents(Request $request) {
+	public function sendMailToUnallocatedStudents(Request $request) {
 
 		 try {
 				if (!$request->isMethod('GET')) {
@@ -89,21 +89,26 @@ class InformUnlocatedStudents extends ControllerBase {
 								], Response::HTTP_FORBIDDEN);
 				}
 
+				$cnt_success = 0;
+				$cnt_fail = 0;
+
 				// ΡύρΡση ΞΌΞ±ΞΈΞ·Ο„ΟŽΞ½ που Ξ· αίτησΞ� τους ΔΕΝ ικανοποιΞ�ΞΈΞ·ΞΊΞ΅
 				$sCon = $this->connection->select('epal_student_class', 'eStudent')
 																	->fields('eStudent', array('student_id'));
 				$epalStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
 				$studentIds = array();
+
+				//array_push($studentIds,-1);
+
 				foreach ($epalStudents as $epalStudent)
 					array_push($studentIds, $epalStudent->student_id);
+
 				$sCon = $this->connection->select('epal_student', 'eStudent')
 																	->fields('eStudent', array('id', 'user_id', 'created'))
 																	->condition('eStudent.id', $studentIds, 'NOT IN');
 				//$numNoAllocated = $sCon->countQuery()->execute()->fetchField();
 				$epalNonLocatedStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
 
-				$cnt_success = 0;
-				$cnt_fail = 0;
 				foreach ($epalNonLocatedStudents as $epalNonLocatedStudent)	{
 					$epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('user_id' => $epalNonLocatedStudent->user_id));
 					$epalUser = reset($epalUsers);
@@ -114,7 +119,7 @@ class InformUnlocatedStudents extends ControllerBase {
 							//$user = reset($users);
 	            if ($user) {
 											$langcode = $user->getPreferredLangcode();
-											if ($this->sendEmail($user->getEmail(), $epalNonLocatedStudent->id, $epalNonLocatedStudent->created, $langcode))
+											if ($this->sendEmailToUnallocated($user->getEmail(), $epalNonLocatedStudent->id, $epalNonLocatedStudent->created, $langcode))
 												$cnt_success++;
 	             }
 	            else {
@@ -124,15 +129,10 @@ class InformUnlocatedStudents extends ControllerBase {
 	            }
 
 	        } else {
-						/*
-	            return $this->respondWithStatus([
-	                    'message' => t("EPAL user not found"),
-	                ], Response::HTTP_FORBIDDEN);
-						*/
+
 						$cnt_fail++;
 	        }
 
-
 				} //end foreach
 
 				return $this->respondWithStatus([
@@ -155,17 +155,16 @@ class InformUnlocatedStudents extends ControllerBase {
 		}
 
 		//sendEmail(e-mail address, A/A, application Date, lang)
-		private function sendEmail($email, $appId, $appDate, $langcode) {
+		private function sendEmailToUnallocated($email, $appId, $appDate, $langcode) {
 				$mailManager = \Drupal::service('plugin.manager.mail');
 
 				$module = 'epal';
-				$key = 'massive_mail';	//to be checked..
+				$key = 'massive_mail_unallocated';	//to be checked..
 				$to = $email;
 
-				$params['message'] = t('Σας Ξ΅Ξ½Ξ·ΞΌΞ΅ΟΟŽΞ½ΞΏΟ…ΞΌΞ΅ ΟŒΟ„ΞΉ Ξ· αίτησΞ� σας ΞΌΞ΅ Ξ‘/Ξ‘: ') . t($appId) . t(' - ') . t(date('d/m/Y', $epalNonLocatedStudent->created))
-														.t(' δΡν ικανοποιΞ�ΞΈΞ·ΞΊΞ΅. Παρακαλώ ΡπικοινωνΞ�στΡ άμΡσα τηλΡφωνικά ΞΌΞ΅ τη ΔιΡύθυνση ΔΡυτΡροβάθμιας ΕκπαίδΡυσης / ΀μΞ�ΞΌΞ± ΕπαγγΡλματικΞ�Ο‚ ΕκπαίδΡυσης,')
-														.t(' στην οποία Ξ±Ξ½Ξ�κΡτΡ, ΟŽΟƒΟ„Ξ΅ Ξ½Ξ± διΡρΡυνηθΡί Ξ· Ξ΄Ο…Ξ½Ξ±Ο„ΟŒΟ„Ξ·Ο„Ξ± ΡγγραφΞ�Ο‚ σας σΡ αντίστοιχο ΕΠΑΛ. ')
-														.t('\r\n΀Ρστ1\n΀Ρστ2') ;//e-mail body
+				$params['message'] = "Σας Ξ΅Ξ½Ξ·ΞΌΞ΅ΟΟŽΞ½ΞΏΟ…ΞΌΞ΅ ΟŒΟ„ΞΉ Ξ· αίτησΞ� σας ΞΌΞ΅ Ξ‘/Ξ‘: " . $appId . " - " . date('d-m-y H:i:s', $appDate)
+														. " δΡν ικανοποιΞ�ΞΈΞ·ΞΊΞ΅. Παρακαλώ ΡπικοινωνΞ�στΡ άμΡσα τηλΡφωνικά ΞΌΞ΅ τη ΔιΡύθυνση ΔΡυτΡροβάθμιας ΕκπαίδΡυσης / ΀μΞ�ΞΌΞ± ΕπαγγΡλματικΞ�Ο‚ ΕκπαίδΡυσης,"
+ 														. "\r\n΀Ρστ1\n΀Ρστ2" ;//e-mail body
 																//add new lines with SENDER name  - check it
 				//$params['subject'] = t('Μη ικανοποίηση ηλΡκτρονικΞ�Ο‚ αίτησης Ξ³ΞΉΞ± ΡγγραφΞ� σΡ ΕΠΑΛ');
 
@@ -178,12 +177,177 @@ class InformUnlocatedStudents extends ControllerBase {
 				//$mail_sent = 1;
 
 				if ($mail_sent) {
-						$this->logger->info("΀ο mail στάλθηκΡ ΞΌΞ΅ Ρπιτυχία");
+						//$this->logger->info("΀ο mail στάλθηκΡ ΞΌΞ΅ Ρπιτυχία");
 						return 1;
 				}
 				else {
-						$this->logger->info("Αποτυχία αποστολΞ�Ο‚ mail.");
+						//$this->logger->info("Αποτυχία αποστολΞ�Ο‚ mail.");
+						return 0;
+				}
+		}
+
+		public function sendMailToLocatedStudents(Request $request) {
+
+			//$msg = "test";
+
+			try {
+				 if (!$request->isMethod('GET')) {
+						return $this->respondWithStatus([
+							 "message" => t("Method Not Allowed")
+								], Response::HTTP_METHOD_NOT_ALLOWED);
+				 }
+
+				 //user validation
+				 $authToken = $request->headers->get('PHP_AUTH_USER');
+				 $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
+				 $user = reset($users);
+				 if (!$user) {
+						 return $this->respondWithStatus([
+										 'message' => t("User not found"),
+								 ], Response::HTTP_FORBIDDEN);
+				 }
+
+				 //user role validation
+				 $roles = $user->getRoles();
+				 $validRole = false;
+				 foreach ($roles as $role)
+					 if ($role === "ministry") {
+						 $validRole = true;
+						 break;
+					 }
+				 if (!$validRole) {
+						 return $this->respondWithStatus([
+										 'message' => t("User Invalid Role"),
+								 ], Response::HTTP_FORBIDDEN);
+				 }
+
+				 // ΡύρΡση ΞΌΞ±ΞΈΞ·Ο„ΟŽΞ½ που Ξ· αίτησΞ� τους Ξ™ΞšΞ‘ΞΞŸΞ ΞŸΞ™Ξ—Ξ˜Ξ—ΞšΞ•
+
+ 				$sCon = $this->connection->select('epal_student_class', 'eStudent')
+ 																	->fields('eStudent', array('student_id', 'epal_id'));
+ 				$epalStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
+ 				$studentIds = array();
+
+				//if sizeof(studentIds = 0..distribution has not been made!)
+				//array_push($studentIds, -1);
+
+ 				foreach ($epalStudents as $epalStudent)
+ 					array_push($studentIds, $epalStudent->student_id);
+ 				$sCon = $this->connection->select('epal_student', 'eStudent')
+ 																	->fields('eStudent', array('id', 'user_id', 'created'))
+ 																	->condition('eStudent.id', $studentIds, 'IN');
+
+ 				$epalLocatedStudents = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
+
+ 				$cnt_success = 0;
+ 				$cnt_fail = 0;
+ 				foreach ($epalLocatedStudents as $epalLocatedStudent)	{
+
+					//test purpose
+				  //$epalLocatedStudent = reset($epalLocatedStudents);
+
+ 					$epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('user_id' => $epalLocatedStudent->user_id));
+ 					$epalUser = reset($epalUsers);
+
+ 					if ($epalUser) {
+ 	            $user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
+
+ 	            if ($user) {
+ 											$langcode = $user->getPreferredLangcode();
+
+											//ΡύρΡση ΞΏΞ½ΟŒΞΌΞ±Ο„ΞΏΟ‚ σχολΡίου
+											$sCon = $this->connection->select('eepal_school_field_data', 'eSchool')
+											                         ->fields('eSchool', array('id', 'name','street_address','phone_number'))
+											                         ->condition('eSchool.id', $epalStudent->epal_id, '=');;
+											$epalSchools = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
+											$epalSchool = reset($epalSchools);
+
+											//$msg = $this->sendEmailToLocated($user->getEmail(), $epalLocatedStudent->id, $epalSchool->name, $epalSchool->street_address, $epalSchool->phone_number, $epalLocatedStudent->created, $langcode);
+											if ($this->sendEmailToLocated($user->getEmail(), $epalLocatedStudent->id, $epalSchool->name, $epalSchool->street_address, $epalSchool->phone_number, $epalLocatedStudent->created, $langcode))
+											  $cnt_success++;
+
+												/*
+											//test purposes
+											return $this->respondWithStatus([
+													//'message' => $epalLocatedStudent->id . ", " . $epalSchool->name . ", " . $epalSchool->street_address . ", " . $epalSchool->phone_number . ", " .  $epalLocatedStudent->created,
+													'message' => $msg,
+													'num_success_mail' => $cnt_success,
+													'num_fail_mail' => $cnt_fail,
+											], Response::HTTP_OK);
+											//end test
+											*/
+
+ 	             }
+ 	            else {
+ 	                return $this->respondWithStatus([
+ 	                    'message' => t("user not found"),
+ 	                ], Response::HTTP_INTERNAL_SERVER_ERROR);
+ 	            }
+
+ 	        } else {
+
+ 						$cnt_fail++;
+ 	        }
+
+
+ 				} //end foreach
+
+
+
+				 return $this->respondWithStatus([
+						 'message' => t("post successful"),
+						 //'message' => t($msg),
+						 'num_success_mail' => $cnt_success,
+						 'num_fail_mail' => $cnt_fail,
+				 ], Response::HTTP_OK);
+
+
+
+
+
+			 }	 //end try
+
+			 catch (\Exception $e) {
+				 $this->logger->warning($e->getMessage());
+				 return $this->respondWithStatus([
+							 "message" => t("An unexpected problem occured during  sendMailToStudents Method ")
+						 ], Response::HTTP_INTERNAL_SERVER_ERROR);
+			 }
+
+		}
+
+		//sendEmail(e-mail address, A/A, application Date, lang)
+		private function sendEmailToLocated($email, $appId, $schName, $schStreet, $schTel, $appDate, $langcode) {
+				//$this->logger->warning("test");
+
+				$mailManager = \Drupal::service('plugin.manager.mail');
+
+				$module = 'epal';
+				$key = 'massive_mail_located';
+				$to = $email;
+
+				$params['message'] = "Σας Ξ΅Ξ½Ξ·ΞΌΞ΅ΟΟŽΞ½ΞΏΟ…ΞΌΞ΅ ΟŒΟ„ΞΉ Ξ· αίτησΞ� σας ΞΌΞ΅ Ξ‘/Ξ‘: " . $appId . " - " . date('d-m-y H:i:s', $appDate)
+														. " Ξ™ΞšΞ‘ΞΞŸΞ ΞŸΞ™Ξ—Ξ˜Ξ—ΞšΞ•. ΞˆΟ‡Ξ΅Ο„Ξ΅ ΡπιλΡγΡί Ξ½Ξ± γίνΡι Ξ· ΡγγραφΞ� σας στο "  . $schName .", που βρίσκΡται στη διΡύθυνση: "   . $schStreet
+														. ". Παρακαλώ ΡπικοινωνΞ�στΡ άμΡσα ΞΌΞ΅ τη ΣχολικΞ� Μονάδα τοποθέτησΞ�Ο‚ σας"
+														. ", ΟŽΟƒΟ„Ξ΅ Ξ½Ξ± ΡνημΡρωθΡίτΡ Ξ³ΞΉΞ± τη διαδικασία που πρέπΡι Ξ½Ξ± ακολουθΞ�σΡτΡ Ξ³ΞΉΞ± την ΡγγραφΞ� σας στο σχολΡίο. "
+														. "΀ηλέφωνο Ρπικοινωνίας σχολΡίου: " . $schTel
+														. "\r\n΀Ρστ1\n΀Ρστ2" ;//e-mail body
+
+				//$this->logger->info($params['message']);
+
+				$send = true;
+
+				$mail_sent = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
+
+				if ($mail_sent) {
+
+						return 1;
+						//return $params['message'];
+				}
+				else {
+
 						return 0;
+						//return $params['message'];
 				}
 		}
 
diff --git a/drupal/modules/epal/src/Controller/MinisterSettings.php b/drupal/modules/epal/src/Controller/MinisterSettings.php
index 435cd0a052b01a5d101834b624299da96a052260..525c094544ebf7923fff1daa307044d0bf1ef648 100644
--- a/drupal/modules/epal/src/Controller/MinisterSettings.php
+++ b/drupal/modules/epal/src/Controller/MinisterSettings.php
@@ -87,7 +87,7 @@ class MinisterSettings extends ControllerBase {
 
 			 //minister settings retrieve
 			 $config_storage = $this->entityTypeManager->getStorage('epal_config');
-	 		 $epalConfigs = $config_storage->loadByProperties(array('id' => 1));
+	 		 $epalConfigs = $config_storage->loadByProperties(array('name' => 'epal_config'));
 	 		 $epalConfig = reset($epalConfigs);
 	 		 if (!$epalConfig) {
 	 				return $this->respondWithStatus([
@@ -157,7 +157,7 @@ public function storeSettings(Request $request, $capacityDisabled, $directorView
 		 }
 
 		 $config_storage = $this->entityTypeManager->getStorage('epal_config');
- 		 $epalConfigs = $config_storage->loadByProperties(array('id' => 1));
+ 		 $epalConfigs = $config_storage->loadByProperties(array('name' => 'epal_config'));
  		 $epalConfig = reset($epalConfigs);
  		 if (!$epalConfig) {
  				return $this->respondWithStatus([
diff --git a/drupal/modules/epal/src/Controller/ReportsCreator.php b/drupal/modules/epal/src/Controller/ReportsCreator.php
index 51021470a8f73f2c263ad050553ea4ff6aa216d2..1d477b8e48b1f9deb52493d5412dfc799379c8d6 100644
--- a/drupal/modules/epal/src/Controller/ReportsCreator.php
+++ b/drupal/modules/epal/src/Controller/ReportsCreator.php
@@ -99,7 +99,8 @@ class ReportsCreator extends ControllerBase {
 				for ($i=0; $i < 3; $i++)	{
 					$sCon = $this->connection->select('epal_student_class', 'eStudent')
 																		->fields('eStudent', array('id', 'distribution_id'))
-																		->condition('eStudent.distribution_id', $i+1, '=');
+																		->condition('eStudent.distribution_id', $i+1, '=')
+																		->condition('eStudent.finalized', 1 , '=');
 					array_push($numData, $sCon->countQuery()->execute()->fetchField());
 				}
 
@@ -116,6 +117,14 @@ class ReportsCreator extends ControllerBase {
 																	->condition('eStudent.id', $studentIds, 'NOT IN');
 				$numNoAllocated = $sCon->countQuery()->execute()->fetchField();
 
+				//Ο…Ο€ΞΏΞ»ΞΏΞ³ΞΉΟƒΞΌΟŒΟ‚ αριθμού Ξ±ΞΉΟ„Ξ�σΡων που τοποθΡτΞ�ΞΈΞ·ΞΊΞ±Ξ½ προσωρινά σΡ ολιγομΡλΞ� τμΞ�ματα
+				$numInSmallClasses = 0;
+				$sCon = $this->connection->select('epal_student_class', 'eStudent')
+																		->fields('eStudent', array('id'))
+																		->condition('eStudent.finalized', 0 , '=');
+				$numInSmallClasses = $sCon->countQuery()->execute()->fetchField();
+
+
 				 $list = array();
 
 				 array_push($list,(object) array('name' => "Ξ‘ΟΞΉΞΈΞΌΟŒΟ‚ ΑιτΞ�σΡων", 'numStudents' => $numTotal));
@@ -123,6 +132,7 @@ class ReportsCreator extends ControllerBase {
 				 array_push($list,(object) array('name' => "Ξ‘ΟΞΉΞΈΞΌΟŒΟ‚ ΞΌΞ±ΞΈΞ·Ο„ΟŽΞ½ που τοποθΡτΞ�ΞΈΞ·ΞΊΞ±Ξ½ στην δΡύτΡρΞ� τους προτίμηση", 'numStudents' => $numData[1]));
 				 array_push($list,(object) array('name' => "Ξ‘ΟΞΉΞΈΞΌΟŒΟ‚ ΞΌΞ±ΞΈΞ·Ο„ΟŽΞ½ που τοποθΡτΞ�ΞΈΞ·ΞΊΞ±Ξ½ στην τρίτη τους προτίμηση", 'numStudents' => $numData[2]));
 				 array_push($list,(object) array('name' => "Ξ‘ΟΞΉΞΈΞΌΟŒΟ‚ ΞΌΞ±ΞΈΞ·Ο„ΟŽΞ½ που δΡν τοποθΡτΞ�ΞΈΞ·ΞΊΞ±Ξ½ σΡ ΞΊΞ±ΞΌΞΌΞ―Ξ± τους προτίμηση", 'numStudents' => $numNoAllocated));
+				 array_push($list,(object) array('name' => "Ξ‘ΟΞΉΞΈΞΌΟŒΟ‚ ΞΌΞ±ΞΈΞ·Ο„ΟŽΞ½ που τοποθΡτΞ�ΞΈΞ·ΞΊΞ±Ξ½ προσωρινά σΡ ολιγομΡλΞ� τμΞ�ματα", 'numStudents' => $numInSmallClasses));
 
 				 return $this->respondWithStatus(
 								 $list
@@ -223,19 +233,15 @@ class ReportsCreator extends ControllerBase {
 						$numClassSectors += $sectorsInEpal->capacity_class_sector;
 					array_push($capacity,  $numClassSectors * $limitUp);
 					//Ο‡Ο‰ΟΞ·Ο„ΞΉΞΊΟŒΟ„Ξ·Ο„Ξ± Ξ³ΞΉΞ± Ξ“' τάξη
-					//ΑΛΛΑΓΗ -> Ξ Ξ‘ΞŸΞ£Ξ˜Ξ—ΞšΞ— ΞΞ•ΞŸΞ₯ Ξ Ξ•Ξ”Ξ™ΞŸΞ₯ ΓΙΑ CAPACITY Σ΀Η Ξ”';
 					$sCon = $this->connection->select('eepal_specialties_in_epal_field_data', 'eSchool')
 																		->fields('eSchool', array('id',  'capacity_class_specialty'))
 																		->condition('eSchool.epal_id', $epalSchool->id , '=');
 					$specialtiesInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
 					$numClassSpecialties = 0;
-					//$numClassSpecialtiesNight = 0;
 					foreach ($specialtiesInEpals as $specialtiesInEpal)	{
 						$numClassSpecialties += $specialtiesInEpal->capacity_class_specialty;
-						//$numClassSpecialtiesNight += $specialtiesInEpal->capacity_class_specialty;
 					}
 					array_push($capacity,  $numClassSpecialties * $limitUp);
-					//array_push($capacity,  $numClassSpecialtiesNight * $limitUp);
 
 					//Ο‡Ο‰ΟΞ·Ο„ΞΉΞΊΟŒΟ„Ξ·Ο„Ξ± Ξ³ΞΉΞ± Ξ”' τάξη
 					if ($epalSchool->operation_shift === "Ξ•Ξ£Ξ Ξ•Ξ‘Ξ™ΞΞŸ")	{
@@ -262,7 +268,8 @@ class ReportsCreator extends ControllerBase {
 						$sCon = $this->connection->select('epal_student_class', 'eStudent')
 																			->fields('eStudent', array('id', 'epal_id', 'currentclass'))
 																			->condition('eStudent.epal_id', $epalSchool->id , '=')
-																			->condition('eStudent.currentclass', $classId , '=');
+																			->condition('eStudent.currentclass', $classId , '=')
+																			->condition('eStudent.finalized', 1 , '=');
 						array_push( $num, $sCon->countQuery()->execute()->fetchField() );
 						//βρΡς ποσοστά συμπλΞ�ρωσης
 						array_push( $perc, number_format($num[$classId-1] / $capacity[$classId-1] * 100, 2));
@@ -300,7 +307,7 @@ class ReportsCreator extends ControllerBase {
 
 
 
-		public function makeReportAllStat(Request $request, $regionId, $adminId, $schId, $classId, $sectorId, $courseId)	{
+		public function makeReportAllStat(Request $request, $regionId, $adminId, $schId, $classId, $sectorId, $courseId, $finalized)	{
 
 			try  {
 
@@ -408,7 +415,10 @@ class ReportsCreator extends ControllerBase {
 																									->fields('eStudent', array('id'))
 																									->condition('eStudent.epal_id', $epalSchool->id , '=')
 																									->condition('eStudent.currentclass', 3 , '=')
-																									->condition('eStudent.specialization_id', $specialtiesInEpal->specialty_id , '=');
+																									->condition('eStudent.specialization_id', $specialtiesInEpal->specialty_id , '=')
+																									->condition('eStudent.finalized', $finalized , '=');
+												//if ($finalized === 1)
+												//	$sCon->condition('eStudent.finalized', 1 , '=');
 												$numStud = $sCon->countQuery()->execute()->fetchField();
 												array_push( $numColumn, $numStud );
 												array_push($capacityColumn, $specialtiesInEpal->capacity_class_specialty * $limitup);
@@ -454,7 +464,10 @@ class ReportsCreator extends ControllerBase {
 																									->fields('eStudent', array('id'))
 																									->condition('eStudent.epal_id', $epalSchool->id , '=')
 																									->condition('eStudent.currentclass', 4 , '=')
-																									->condition('eStudent.specialization_id', $specialtiesInEpal->specialty_id , '=');
+																									->condition('eStudent.specialization_id', $specialtiesInEpal->specialty_id , '=')
+																									->condition('eStudent.finalized', $finalized , '=');
+												//if ($finalized === 1)
+												//	$sCon->condition('eStudent.finalized', 1 , '=');
 												$numStud = $sCon->countQuery()->execute()->fetchField();
 												array_push( $numColumn, $numStud );
 												array_push($capacityColumn, $specialtiesInEpal->capacity_class_specialty_d * $limitup);
@@ -494,7 +507,10 @@ class ReportsCreator extends ControllerBase {
 																				->fields('eStudent', array('id'))
 																				->condition('eStudent.epal_id', $epalSchool->id , '=')
 																				->condition('eStudent.currentclass', 2 , '=')
-																				->condition('eStudent.specialization_id', $sectorsInEpal->sector_id , '=');
+																				->condition('eStudent.specialization_id', $sectorsInEpal->sector_id , '=')
+																				->condition('eStudent.finalized', $finalized , '=');
+							//if ($finalized === 1)
+							//	$sCon->condition('eStudent.finalized', 1 , '=');
 							$numStud = $sCon->countQuery()->execute()->fetchField();
 							array_push( $numColumn, $numStud );
 							array_push($capacityColumn, $sectorsInEpal->capacity_class_sector * $limitup);
@@ -518,6 +534,9 @@ class ReportsCreator extends ControllerBase {
 
 					$clidstart = 1;
 					$clidend = 4;
+					//Για ολιγομΡλΞ� τμΞ�ματα, ΞΌΞ·Ξ½ Ρμφανί΢Ρις συνολικά τις Ξ’', Ξ“', Ξ”' τάξΡις ???
+					//if ($finalized === "0")
+					//	$clidend = 1;
 
 					if ($classId !== "0")	{
 						$clidstart = $classId;
@@ -542,8 +561,10 @@ class ReportsCreator extends ControllerBase {
 						$sCon = $this->connection->select('epal_student_class', 'eStudent')
 																			->fields('eStudent', array('id', 'epal_id', 'currentclass'))
 																			->condition('eStudent.epal_id', $epalSchool->id , '=')
-																			->condition('eStudent.currentclass', $clId , '=');
-
+																			->condition('eStudent.currentclass', $clId , '=')
+																			->condition('eStudent.finalized', $finalized , '=');
+						//if ($finalized === 1)
+						//		$sCon->condition('eStudent.finalized', 1 , '=');
 						$numStud =  $sCon->countQuery()->execute()->fetchField();
 						array_push($schoolNameColumn, $epalSchool->name);
 						array_push($regionColumn, $epalRegion->name);
@@ -717,7 +738,8 @@ class ReportsCreator extends ControllerBase {
 
 
 					//ΡύρΡση αριθμού τμημάτων (Ο‡Ο‰ΟΞ·Ο„ΞΉΞΊΟŒΟ„Ξ·Ο„Ξ±) Ξ³ΞΉΞ± κάθΡ τμΞ�ΞΌΞ± της Ξ‘' τάξης
-					if ( ($capacityEnabled === "0" && ($epalSchool->capacity_class_a === "0" || !isset($epalSchool->capacity_class_a)) )  ||  ($capacityEnabled === "1")  )	{
+					//$epalSchool->capacity_class_a === "0" ||
+					if ( ($capacityEnabled === '0' && ( !isset($epalSchool->capacity_class_a)) )  ||  ($capacityEnabled === "1")  )	{
 							array_push($regionColumn, $epalRegion->name);
 							array_push($adminColumn, $epalAdmin->name);
 							array_push($schoolNameColumn, $epalSchool->name);
@@ -726,7 +748,7 @@ class ReportsCreator extends ControllerBase {
 					}
 
 					//ΡύρΡση αριθμού τμημάτων (Ο‡Ο‰ΟΞ·Ο„ΞΉΞΊΟŒΟ„Ξ·Ο„Ξ±) Ξ³ΞΉΞ± κάθΡ τομέα της Ξ’' τάξης
-					//Ξ Ξ‘ΞŸΞ£ΞŸΞ§Ξ—: Ο‡Ξ΅ΞΉΟΞΉΟƒΞΌΞ„ΟŒΟ‚ Ο„ΞΉΞΌΟŽΞ½: 0 ΞΊΞ±ΞΉ null
+					//Ξ Ξ‘ΞŸΞ£ΞŸΞ§Ξ—: Ο‡Ξ΅ΞΉΟΞΉΟƒΞΌΞ„ΟŒΟ‚ Ο„ΞΉΞΌΟŽΞ½: 0 (ΞŸΞ§Ξ™??) ΞΊΞ±ΞΉ null
 
 					$sCon = $this->connection->select('eepal_sectors_in_epal_field_data', 'eSchool')
 																		->fields('eSchool', array('sector_id','capacity_class_sector'))
@@ -737,7 +759,7 @@ class ReportsCreator extends ControllerBase {
 					//$sCon->condition($db_or) ;
 					if ($capacityEnabled === "0")	{
 						$sCon->condition( db_or()
-															->condition('eSchool.capacity_class_sector', 0, '=')
+															//->condition('eSchool.capacity_class_sector', 0, '=')
 															->condition('eSchool.capacity_class_sector', null, 'is')  ) ;
 					}
 					$sectorsInEpals = $sCon->execute()->fetchAll(\PDO::FETCH_OBJ);
@@ -766,7 +788,7 @@ class ReportsCreator extends ControllerBase {
 
 					if ($capacityEnabled === "0")	{
 							$sCon->condition( db_or()
-																->condition('eSchool.capacity_class_specialty', 0, '=')
+																//->condition('eSchool.capacity_class_specialty', 0, '=')
 																->condition('eSchool.capacity_class_specialty', null, 'is')  ) ;
 						}
 
@@ -798,7 +820,7 @@ class ReportsCreator extends ControllerBase {
 
 					if ($capacityEnabled === "0")	{
 							$sCon->condition( db_or()
-																->condition('eSchool.capacity_class_specialty_d', 0, '=')
+																//->condition('eSchool.capacity_class_specialty_d', 0, '=')
 																->condition('eSchool.capacity_class_specialty_d', null, 'is')  ) ;
 						}
 
diff --git a/drupal/modules/oauthost/src/Controller/CBController.php b/drupal/modules/oauthost/src/Controller/CBController.php
index 733a2131dcbc9551de37edc16c4661beed441334..ff2f9d450adda1c49196c640fee27139408a4824 100755
--- a/drupal/modules/oauthost/src/Controller/CBController.php
+++ b/drupal/modules/oauthost/src/Controller/CBController.php
@@ -128,116 +128,111 @@ class CBController extends ControllerBase
 
     public function authenticatePhase2($request, $authToken, $authVerifier)
     {
-    $taxis_userid = null;
-    $trx = $this->connection->startTransaction();
-    try {
-        $oauth = new OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_PLAINTEXT, OAUTH_AUTH_TYPE_URI);
-        $oauth->enableDebug();
-        $oauth->setToken($authToken, $this->requestTokenSecret);
-        $accessToken = $oauth->getAccessToken($this->access_token_url, '', $authVerifier);
-        $oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
-        $oauth->fetch($this->api_url);
-
-        $this->logger->warning($oauth->getLastResponse());
-        $taxis_userid = $this->xmlParse($oauth->getLastResponse(), 'messageText');
-
-        $currentTime = time();
-        $epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('taxis_userid' => $taxis_userid));
-        $epalUser = reset($epalUsers);
-
-        $epalToken = md5(uniqid(mt_rand(), true));
-        if ($epalUser) {
-            $user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
-            if ($user) {
-//                $user->setPassword('harispass');
-//                $user->setUsername('harisp');
-                $user->setPassword($epalToken);
-                $user->setUsername($epalToken);
-                $user->save();
-                $epalUser->set('authtoken', $epalToken);
-                $epalUser->set('accesstoken', $accessToken['oauth_token']);
-                $epalUser->set('accesstoken_secret', $accessToken['oauth_token_secret']);
-                $epalUser->set('requesttoken',$this->requestToken);
-                $epalUser->set('requesttoken_secret', $this->requestTokenSecret);
-                $epalUser->set('timelogin', $currentTime);
-                $epalUser->set('userip', $request->getClientIp());
-
-                $epalUser->save();
+        $taxis_userid = null;
+        $trx = $this->connection->startTransaction();
+        try {
+            $oauth = new OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_PLAINTEXT, OAUTH_AUTH_TYPE_URI);
+            $oauth->enableDebug();
+            $oauth->setToken($authToken, $this->requestTokenSecret);
+            $accessToken = $oauth->getAccessToken($this->access_token_url, '', $authVerifier);
+            $oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
+            $oauth->fetch($this->api_url);
+
+            $this->logger->warning($oauth->getLastResponse());
+            $taxis_userid = $this->xmlParse($oauth->getLastResponse(), 'messageText');
+
+            $currentTime = time();
+            $epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('taxis_userid' => $taxis_userid));
+            $epalUser = reset($epalUsers);
+
+            $epalToken = md5(uniqid(mt_rand(), true));
+            if ($epalUser) {
+                $user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
+                if ($user) {
+                    $user->setPassword($epalToken);
+                    $user->setUsername($epalToken);
+                    $user->save();
+                    $epalUser->set('authtoken', $epalToken);
+                    $epalUser->set('accesstoken', $accessToken['oauth_token']);
+                    $epalUser->set('accesstoken_secret', $accessToken['oauth_token_secret']);
+                    $epalUser->set('requesttoken',$this->requestToken);
+                    $epalUser->set('requesttoken_secret', $this->requestTokenSecret);
+                    $epalUser->set('timelogin', $currentTime);
+                    $epalUser->set('userip', $request->getClientIp());
+
+                    $epalUser->save();
+                }
             }
-        }
 
-        if ($epalUser === null || !$epalUser) {
-
-            //Create a User
-            $user = User::create();
-            //Mandatory settings
-            $unique_id = uniqid('####');
-            $user->setPassword($epalToken);
-            $user->enforceIsNew();
-            $user->setEmail($unique_id);
-            $user->setUsername($epalToken); //This username must be unique and accept only a-Z,0-9, - _ @ .
-            $user->activate();
-            $user->set('init', $unique_id);
-
-            //Set Language
-            $language_interface = \Drupal::languageManager()->getCurrentLanguage();
-            $user->set('langcode', $language_interface->getId());
-            $user->set('preferred_langcode', $language_interface->getId());
-            $user->set('preferred_admin_langcode', $language_interface->getId());
-
-            //Adding default user role
-            $user->addRole('applicant');
-            $user->save();
-
-
-            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('mail' => $unique_id));
-            $user = reset($users);
-            if ($user) {
-                $this->logger->warning('userid 190='.$user->id().'*** name='.$user->name->value);
-
-                $epalUser = $this->entityTypeManager()->getStorage('epal_users')->create(array(
-            //    'langcode' => $language_interface->getId(),
-                'langcode' => 'el',
-                'user_id' => $user->id(),
-                'drupaluser_id' => $user->id(),
-                'taxis_userid' => $taxis_userid,
-                'taxis_taxid' => $unique_id,
-                'name' => $unique_id,
-                'surname' => $unique_id,
-                'fathername' => $unique_id,
-                'mothername' => $unique_id,
-                'accesstoken' => $accessToken['oauth_token'],
-                'accesstoken_secret' => $accessToken['oauth_token_secret'],
-                'authtoken' => $epalToken,
-                'requesttoken' => $this->requestToken,
-                'requesttoken_secret' => $this->requestTokenSecret,
-                'timelogin' => $currentTime,
-                'timeregistration' => $currentTime,
-                'timetokeninvalid' => 0,
-                'userip' => $request->getClientIp(),
-                'status' => 1
-            ));
-            $epalUser->save();
-            } else {
-                return false;
-            }
+            if ($epalUser === null || !$epalUser) {
 
-        }
-        $this->oauthostSession->set('authtoken', $epalToken);
-        $this->oauthostSession->save();
-//        $this->oauthostSession->delete();
+                //Create a User
+                $user = User::create();
+                //Mandatory settings
+                $unique_id = uniqid('####');
+                $user->setPassword($epalToken);
+                $user->enforceIsNew();
+                $user->setEmail($unique_id);
+                $user->setUsername($epalToken); //This username must be unique and accept only a-Z,0-9, - _ @ .
+                $user->activate();
+                $user->set('init', $unique_id);
+
+                //Set Language
+                $language_interface = \Drupal::languageManager()->getCurrentLanguage();
+                $user->set('langcode', $language_interface->getId());
+                $user->set('preferred_langcode', $language_interface->getId());
+                $user->set('preferred_admin_langcode', $language_interface->getId());
+
+                //Adding default user role
+                $user->addRole('applicant');
+                $user->save();
 
+                $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('mail' => $unique_id));
+                $user = reset($users);
+                if ($user) {
+                    $this->logger->warning('userid 190='.$user->id().'*** name='.$user->name->value);
+
+                    $epalUser = $this->entityTypeManager()->getStorage('epal_users')->create(array(
+                        'langcode' => 'el',
+                        'user_id' => $user->id(),
+                        'drupaluser_id' => $user->id(),
+                        'taxis_userid' => $taxis_userid,
+                        'taxis_taxid' => $unique_id,
+                        'name' => $unique_id,
+                        'surname' => $unique_id,
+                        'fathername' => $unique_id,
+                        'mothername' => $unique_id,
+                        'accesstoken' => $accessToken['oauth_token'],
+                        'accesstoken_secret' => $accessToken['oauth_token_secret'],
+                        'authtoken' => $epalToken,
+                        'requesttoken' => $this->requestToken,
+                        'requesttoken_secret' => $this->requestTokenSecret,
+                        'timelogin' => $currentTime,
+                        'timeregistration' => $currentTime,
+                        'timetokeninvalid' => 0,
+                        'userip' => $request->getClientIp(),
+                        'status' => 1
+                    ));
+                    $epalUser->save();
+                } else {
+                    return false;
+                }
 
-        return $epalToken;
-    } catch (OAuthException $e) {
-        $this->logger->warning($e->getMessage());
-        $trx->rollback();
-        return false;
-    } catch (\Exception $ee) {
-        $this->logger->warning($ee->getMessage());
-        $trx->rollback();
-        return false;
-    }
+            }
+            $this->oauthostSession->set('authtoken', $epalToken);
+            $this->oauthostSession->save();
+            // $this->oauthostSession->delete();
+
+            return $epalToken;
+        } catch (OAuthException $e) {
+            $this->logger->warning($e->getMessage());
+            $trx->rollback();
+            return false;
+        } catch (\Exception $ee) {
+            $this->logger->warning($ee->getMessage());
+            $trx->rollback();
+            return false;
+        }
 
         return false;
     }
diff --git a/drupal/modules/oauthost/src/Controller/OAuthLogout.php b/drupal/modules/oauthost/src/Controller/OAuthLogout.php
index 6569cadce57a56d5ba01c3694afbf530e4b538f9..b72949e790bbc08f342ee1a8c9166c58e8db992a 100755
--- a/drupal/modules/oauthost/src/Controller/OAuthLogout.php
+++ b/drupal/modules/oauthost/src/Controller/OAuthLogout.php
@@ -1,6 +1,4 @@
-<?php
-
-namespace Drupal\oauthost\Controller;
+<?php namespace Drupal\oauthost\Controller;
 
 use Drupal\Core\Entity\Query\QueryFactory;
 use Drupal\Core\Entity\EntityTypeManagerInterface;
@@ -16,11 +14,11 @@ use Symfony\Component\HttpFoundation\RedirectResponse;
 
 class OAuthLogout extends ControllerBase
 {
+
     protected $entity_query;
     protected $entityTypeManager;
     protected $logger;
     protected $connection;
-
     protected $consumer_key = '';
     protected $consumer_secret = '';
     protected $request_token_url;
@@ -33,10 +31,7 @@ class OAuthLogout extends ControllerBase
     protected $redirect_url;
 
     public function __construct(
-    EntityTypeManagerInterface $entityTypeManager,
-    QueryFactory $entity_query,
-    Connection $connection,
-    LoggerChannelFactoryInterface $loggerChannel)
+    EntityTypeManagerInterface $entityTypeManager, QueryFactory $entity_query, Connection $connection, LoggerChannelFactoryInterface $loggerChannel)
     {
         $this->entityTypeManager = $entityTypeManager;
         $this->entity_query = $entity_query;
@@ -47,17 +42,14 @@ class OAuthLogout extends ControllerBase
     public static function create(ContainerInterface $container)
     {
         return new static(
-          $container->get('entity.manager'),
-          $container->get('entity.query'),
-          $container->get('database'),
-          $container->get('logger.factory')
-      );
+            $container->get('entity.manager'), $container->get('entity.query'), $container->get('database'), $container->get('logger.factory')
+        );
     }
 
     public function logoutGo(Request $request)
     {
-
         $trx = $this->connection->startTransaction();
+
         try {
             $user = null;
             $username = $request->headers->get('PHP_AUTH_USER');
@@ -67,85 +59,98 @@ class OAuthLogout extends ControllerBase
             if ($this->oauthostSession) {
                 $configRowName = $this->oauthostSession->configrowname->value;
             } else {
+                $trx->rollback();
+                $this->logger->warning("oauthostSession for [{$username}] not set");
                 $response = new Response();
                 $response->setContent('forbidden');
                 $response->setStatusCode(Response::HTTP_FORBIDDEN);
                 $response->headers->set('Content-Type', 'application/json');
                 return $response;
             }
-            $ostauthConfigs = $this->entityTypeManager->getStorage('oauthost_config')->loadByProperties(array('name' => $configRowName));
-        $ostauthConfig = reset($ostauthConfigs);
-        if ($ostauthConfig) {
-            $this->consumer_key = $ostauthConfig->consumer_key->value;
-            $this->consumer_secret = $ostauthConfig->consumer_secret->value;
-            $this->request_token_url = $ostauthConfig->request_token_url->value;
-            $this->user_authorization_url = $ostauthConfig->user_authorization_url->value;
-            $this->access_token_url = $ostauthConfig->access_token_url->value;
-            $this->signature_method = $ostauthConfig->signature_method->value;
-            $this->api_url = $ostauthConfig->api_url->value;
-            $this->callback_url = $ostauthConfig->callback_url->value;
-            $this->logout_url = $ostauthConfig->logout_url->value;
-            $this->redirect_url = $ostauthConfig->redirect_url->value;
-        } else {
-            $response = new Response();
-            $response->setContent('forbidden');
-            $response->setStatusCode(Response::HTTP_FORBIDDEN);
-            $response->headers->set('Content-Type', 'application/json');
-            return $response;
-        }
-
-
-        $epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('authtoken' => $username));
-        $epalUser = reset($epalUsers);
-        $foundUser = true;
 
-        if ($epalUser) {
-            $user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
-            if ($user) {
-
-                $res = \Drupal::httpClient()->get($this->logout_url . $username, array('headers' => array('Accept' => 'text/plain')));
-/*                $resData = (string) $res->getBody();
-                if (empty($resData)) {
-                    return FALSE;
-                } */
-
-//                if ($res->getStatusCode() === "200")
+            $ostauthConfigs = $this->entityTypeManager->getStorage('oauthost_config')->loadByProperties(array('name' => $configRowName));
+            $ostauthConfig = reset($ostauthConfigs);
+            if ($ostauthConfig) {
+                $this->consumer_key = $ostauthConfig->consumer_key->value;
+                $this->consumer_secret = $ostauthConfig->consumer_secret->value;
+                $this->request_token_url = $ostauthConfig->request_token_url->value;
+                $this->user_authorization_url = $ostauthConfig->user_authorization_url->value;
+                $this->access_token_url = $ostauthConfig->access_token_url->value;
+                $this->signature_method = $ostauthConfig->signature_method->value;
+                $this->api_url = $ostauthConfig->api_url->value;
+                $this->callback_url = $ostauthConfig->callback_url->value;
+                $this->logout_url = $ostauthConfig->logout_url->value;
+                $this->redirect_url = $ostauthConfig->redirect_url->value;
+            } else {
+                $trx->rollback();
+                $this->logger->warning("ostauthConfig [{$configRowName}]not found");
+                $response = new Response();
+                $response->setContent('forbidden');
+                $response->setStatusCode(Response::HTTP_FORBIDDEN);
+                $response->headers->set('Content-Type', 'application/json');
+                return $response;
+            }
 
-                $user->setPassword(uniqid('pw'));
-                $user->save();
-                $epalUser->set('accesstoken', '-');
-                $epalUser->set('accesstoken_secret', '-');
-                $epalUser->set('authtoken','-');
-                $epalUser->set('requesttoken','-');
-                $epalUser->set('requesttoken_secret', '-');
-                $epalUser->save();
+            $epalUsers = $this->entityTypeManager
+                ->getStorage('epal_users')
+                ->loadByProperties(array('authtoken' => $username));
+            $epalUser = reset($epalUsers);
+            $foundUser = false;
+            if ($epalUser) {
+                $user = $this->entityTypeManager
+                    ->getStorage('user')
+                    ->load($epalUser->user_id->target_id);
+                $logout_token = $epalUser->getRequesttoken();
+                if ($user) {
+                    $res = \Drupal::httpClient()->get($this->logout_url . $username, array('headers' => array('Accept' => 'text/plain')));
+                    $user->setPassword(uniqid('pw'));
+                    $user->save();
+                    $epalUser->set('accesstoken', '-');
+                    $epalUser->set('accesstoken_secret', '-');
+                    $epalUser->set('authtoken', '-');
+                    $epalUser->set('requesttoken', '-');
+                    $epalUser->set('requesttoken_secret', '-');
+                    $epalUser->save();
+                    $foundUser = true;
+                }
+            }
+            if (!$foundUser) {
+                $trx->rollback();
+                $this->logger->warning("user not found");
+                $response = new Response();
+                $response->setContent('forbidden');
+                $response->setStatusCode(Response::HTTP_FORBIDDEN);
+                $response->headers->set('Content-Type', 'application/json');
+                return $response;
+            }
 
+            // logout from remote host
+            $logout_call_url = "{$this->logout_url}{$logout_token}";
+            if (($ch = curl_init()) !== false) {
+                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+                curl_setopt($ch, CURLOPT_URL, $logout_call_url);
+                $remote_logout_result = curl_exec($ch);
+                if ($remote_logout_result === false) {
+                    // record failure
+                    $this->logger->warning("OAUTH remote logout call to [{$logout_call_url}] fail: " . curl_error($ch));
+                }
+                curl_close($ch);
             } else {
-                $foundUser = false;
+                $this->logger->warning("OAUTH remote logout to [{$logout_call_url}] not called");
             }
-        } else {
-            $foundUser = false;
-        }
-        if (!$foundUser) {
-            $this->logger->warning("user not found");
+
+            session_unset();
+            session_destroy();
+            \Drupal::service('page_cache_kill_switch')->trigger();
+            $this->oauthostSession->delete();
+            $this->logger->info("OAUTH remote logout success for [{$username}]");
+
             $response = new Response();
-            $response->setContent('forbidden');
-            $response->setStatusCode(Response::HTTP_FORBIDDEN);
+            $response->setContent("{\"message\": \"Server logout successful\",\"next\": \"{$this->redirect_url}\"}");
+            $response->setStatusCode(Response::HTTP_OK);
             $response->headers->set('Content-Type', 'application/json');
-            return $response;
-        }
-        session_unset();
-        session_destroy();
-        \Drupal::service('page_cache_kill_switch')->trigger();
-        $response = new Response();
-        $response->setContent('logout successful');
-        $response->setStatusCode(Response::HTTP_OK);
-        $response->headers->set('Content-Type', 'application/json');
-        $this->oauthostSession->delete();
-        return $response;
-//        return new RedirectResponse($this->redirect_url . '&auth_role=', 302, []);
-
 
+            return $response;
         } catch (Exception $e) {
             $this->logger->warning($e->getMessage());
             $response = new Response();
@@ -156,5 +161,4 @@ class OAuthLogout extends ControllerBase
             return $response;
         }
     }
-
 }
diff --git a/drupal/modules/oauthost/src/Entity/OAuthOSTConfig.php b/drupal/modules/oauthost/src/Entity/OAuthOSTConfig.php
index 958f2e4182dac72f8246ee2b9df4e183e5efda6c..ad862c0f8d5bb762fc7ac52b246d08cb04758e0a 100755
--- a/drupal/modules/oauthost/src/Entity/OAuthOSTConfig.php
+++ b/drupal/modules/oauthost/src/Entity/OAuthOSTConfig.php
@@ -1,6 +1,4 @@
-<?php
-
-namespace Drupal\oauthost\Entity;
+<?php namespace Drupal\oauthost\Entity;
 
 use Drupal\Core\Entity\EntityStorageInterface;
 use Drupal\Core\Field\BaseFieldDefinition;
@@ -55,374 +53,375 @@ use Drupal\user\UserInterface;
  */
 class OAuthOSTConfig extends ContentEntityBase implements OAuthOSTConfigInterface
 {
+
     use EntityChangedTrait;
 
-  /**
-   * {@inheritdoc}
-   */
-  public static function preCreate(EntityStorageInterface $storage_controller, array &$values)
-  {
-      parent::preCreate($storage_controller, $values);
-      $values += array(
-      'user_id' => \Drupal::currentUser()->id(),
-    );
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public function getName()
-  {
-      return $this->get('name')->value;
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public function setName($name)
-  {
-      $this->set('name', $name);
-
-      return $this;
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public function getCreatedTime()
-  {
-      return $this->get('created')->value;
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public function setCreatedTime($timestamp)
-  {
-      $this->set('created', $timestamp);
-
-      return $this;
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public function getOwner()
-  {
-      return $this->get('user_id')->entity;
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public function getOwnerId()
-  {
-      return $this->get('user_id')->target_id;
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public function setOwnerId($uid)
-  {
-      $this->set('user_id', $uid);
-
-      return $this;
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public function setOwner(UserInterface $account)
-  {
-      $this->set('user_id', $account->id());
-
-      return $this;
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public function isPublished()
-  {
-      return (bool) $this->getEntityKey('status');
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public function setPublished($published)
-  {
-      $this->set('status', $published ? true : false);
-
-      return $this;
-  }
-
-  /**
-   * {@inheritdoc}
-   */
-  public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
-  {
-      $fields = parent::baseFieldDefinitions($entity_type);
-
-      $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
-      ->setLabel(t('Authored by'))
-      ->setDescription(t('The user ID of author of the OAuthOST Config entity.'))
-      ->setRevisionable(true)
-      ->setSetting('target_type', 'user')
-      ->setSetting('handler', 'default')
-      ->setTranslatable(true)
-      ->setDisplayOptions('view', array(
-        'label' => 'hidden',
-        'type' => 'author',
-        'weight' => 0,
-      ))
-      ->setDisplayOptions('form', array(
-        'type' => 'entity_reference_autocomplete',
-        'weight' => 5,
-        'settings' => array(
-          'match_operator' => 'CONTAINS',
-          'size' => '60',
-          'autocomplete_type' => 'tags',
-          'placeholder' => '',
-        ),
-      ))
-      ->setDisplayConfigurable('form', true)
-      ->setDisplayConfigurable('view', true);
-
-      $fields['name'] = BaseFieldDefinition::create('string')
-      ->setLabel(t('Name'))
-      ->setDescription(t('The name of the OAuthOST Config entity.'))
-      ->setSettings(array(
-        'max_length' => 50,
-        'text_processing' => 0,
-      ))
-      ->setDefaultValue('oauthost_taxisnet_config')
-      ->setDisplayOptions('view', array(
-        'label' => 'above',
-        'type' => 'string',
-        'weight' => -4,
-      ))
-      ->setDisplayOptions('form', array(
-        'type' => 'string_textfield',
-        'weight' => -4,
-      ))
-      ->setDisplayConfigurable('form', true)
-      ->setDisplayConfigurable('view', true);
-
-      $fields['consumer_key'] = BaseFieldDefinition::create('string')
-        ->setLabel(t('Consumer Key'))
-        ->setDescription(t('The Consumer Key'))
-        ->setSettings(array(
-          'max_length' => 200,
-          'text_processing' => 0,
-        ))
-        ->setDefaultValue('')
-        ->setDisplayOptions('view', array(
-          'label' => 'above',
-          'type' => 'string',
-          'weight' => -4,
-        ))
-        ->setDisplayOptions('form', array(
-          'type' => 'string_textfield',
-          'weight' => -4,
-        ))
-        ->setDisplayConfigurable('form', true)
-        ->setDisplayConfigurable('view', true);
-
-      $fields['consumer_secret'] = BaseFieldDefinition::create('string')
+    /**
+     * {@inheritdoc}
+     */
+    public static function preCreate(EntityStorageInterface $storage_controller, array &$values)
+    {
+        parent::preCreate($storage_controller, $values);
+        $values += array(
+            'user_id' => \Drupal::currentUser()->id(),
+        );
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function getName()
+    {
+        return $this->get('name')->value;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function setName($name)
+    {
+        $this->set('name', $name);
+
+        return $this;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function getCreatedTime()
+    {
+        return $this->get('created')->value;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function setCreatedTime($timestamp)
+    {
+        $this->set('created', $timestamp);
+
+        return $this;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function getOwner()
+    {
+        return $this->get('user_id')->entity;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function getOwnerId()
+    {
+        return $this->get('user_id')->target_id;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function setOwnerId($uid)
+    {
+        $this->set('user_id', $uid);
+
+        return $this;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function setOwner(UserInterface $account)
+    {
+        $this->set('user_id', $account->id());
+
+        return $this;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function isPublished()
+    {
+        return (bool) $this->getEntityKey('status');
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function setPublished($published)
+    {
+        $this->set('status', $published ? true : false);
+
+        return $this;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
+    {
+        $fields = parent::baseFieldDefinitions($entity_type);
+
+        $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
+            ->setLabel(t('Authored by'))
+            ->setDescription(t('The user ID of author of the OAuthOST Config entity.'))
+            ->setRevisionable(true)
+            ->setSetting('target_type', 'user')
+            ->setSetting('handler', 'default')
+            ->setTranslatable(true)
+            ->setDisplayOptions('view', array(
+                'label' => 'hidden',
+                'type' => 'author',
+                'weight' => 0,
+            ))
+            ->setDisplayOptions('form', array(
+                'type' => 'entity_reference_autocomplete',
+                'weight' => 5,
+                'settings' => array(
+                    'match_operator' => 'CONTAINS',
+                    'size' => '60',
+                    'autocomplete_type' => 'tags',
+                    'placeholder' => '',
+                ),
+            ))
+            ->setDisplayConfigurable('form', true)
+            ->setDisplayConfigurable('view', true);
+
+        $fields['name'] = BaseFieldDefinition::create('string')
+            ->setLabel(t('Name'))
+            ->setDescription(t('The name of the OAuthOST Config entity.'))
+            ->setSettings(array(
+                'max_length' => 50,
+                'text_processing' => 0,
+            ))
+            ->setDefaultValue('oauthost_taxisnet_config')
+            ->setDisplayOptions('view', array(
+                'label' => 'above',
+                'type' => 'string',
+                'weight' => -4,
+            ))
+            ->setDisplayOptions('form', array(
+                'type' => 'string_textfield',
+                'weight' => -4,
+            ))
+            ->setDisplayConfigurable('form', true)
+            ->setDisplayConfigurable('view', true);
+
+        $fields['consumer_key'] = BaseFieldDefinition::create('string')
+            ->setLabel(t('Consumer Key'))
+            ->setDescription(t('The Consumer Key'))
+            ->setSettings(array(
+                'max_length' => 200,
+                'text_processing' => 0,
+            ))
+            ->setDefaultValue('')
+            ->setDisplayOptions('view', array(
+                'label' => 'above',
+                'type' => 'string',
+                'weight' => -4,
+            ))
+            ->setDisplayOptions('form', array(
+                'type' => 'string_textfield',
+                'weight' => -4,
+            ))
+            ->setDisplayConfigurable('form', true)
+            ->setDisplayConfigurable('view', true);
+
+        $fields['consumer_secret'] = BaseFieldDefinition::create('string')
             ->setLabel(t('Consumer Secret'))
             ->setDescription(t('The Consumer Secret'))
             ->setSettings(array(
-              'max_length' => 200,
-              'text_processing' => 0,
+                'max_length' => 200,
+                'text_processing' => 0,
             ))
             ->setDefaultValue('')
             ->setDisplayOptions('view', array(
-              'label' => 'above',
-              'type' => 'string',
-              'weight' => -4,
+                'label' => 'above',
+                'type' => 'string',
+                'weight' => -4,
             ))
             ->setDisplayOptions('form', array(
-              'type' => 'string_textfield',
-              'weight' => -4,
+                'type' => 'string_textfield',
+                'weight' => -4,
             ))
             ->setDisplayConfigurable('form', true)
             ->setDisplayConfigurable('view', true);
 
-      $fields['request_token_url'] = BaseFieldDefinition::create('string')
+        $fields['request_token_url'] = BaseFieldDefinition::create('string')
             ->setLabel(t('Request Token Url'))
             ->setDescription(t('The Request Token Url'))
             ->setSettings(array(
-              'max_length' => 500,
-              'text_processing' => 0,
+                'max_length' => 500,
+                'text_processing' => 0,
             ))
             ->setDefaultValue('https://www1.gsis.gr/gsisapps/gsisdemo/oauth/request_token')
             ->setDisplayOptions('view', array(
-              'label' => 'above',
-              'type' => 'string',
-              'weight' => -4,
+                'label' => 'above',
+                'type' => 'string',
+                'weight' => -4,
+            ))
+            ->setDisplayOptions('form', array(
+                'type' => 'string_textfield',
+                'weight' => -4,
+            ))
+            ->setDisplayConfigurable('form', true)
+            ->setDisplayConfigurable('view', true);
+
+        $fields['user_authorization_url'] = BaseFieldDefinition::create('string')
+            ->setLabel(t('User Authorization Url'))
+            ->setDescription(t('The User Authorization Url'))
+            ->setSettings(array(
+                'max_length' => 500,
+                'text_processing' => 0,
+            ))
+            ->setDefaultValue('https://www1.gsis.gr/gsisapps/gsisdemo/oauth/confirm_access')
+            ->setDisplayOptions('view', array(
+                'label' => 'above',
+                'type' => 'string',
+                'weight' => -4,
+            ))
+            ->setDisplayOptions('form', array(
+                'type' => 'string_textfield',
+                'weight' => -4,
+            ))
+            ->setDisplayConfigurable('form', true)
+            ->setDisplayConfigurable('view', true);
+
+        $fields['access_token_url'] = BaseFieldDefinition::create('string')
+            ->setLabel(t('Access Token Url'))
+            ->setDescription(t('The Access Token Url'))
+            ->setSettings(array(
+                'max_length' => 500,
+                'text_processing' => 0,
+            ))
+            ->setDefaultValue('https://www1.gsis.gr/gsisapps/gsisdemo/oauth/access_token')
+            ->setDisplayOptions('view', array(
+                'label' => 'above',
+                'type' => 'string',
+                'weight' => -4,
+            ))
+            ->setDisplayOptions('form', array(
+                'type' => 'string_textfield',
+                'weight' => -4,
+            ))
+            ->setDisplayConfigurable('form', true)
+            ->setDisplayConfigurable('view', true);
+
+        $fields['signature_method'] = BaseFieldDefinition::create('string')
+            ->setLabel(t('Signature Method'))
+            ->setDescription(t('The Signature Method'))
+            ->setSettings(array(
+                'max_length' => 100,
+                'text_processing' => 0,
+            ))
+            ->setDefaultValue('PLAINTEXT')
+            ->setDisplayOptions('view', array(
+                'label' => 'above',
+                'type' => 'string',
+                'weight' => -4,
+            ))
+            ->setDisplayOptions('form', array(
+                'type' => 'string_textfield',
+                'weight' => -4,
+            ))
+            ->setDisplayConfigurable('form', true)
+            ->setDisplayConfigurable('view', true);
+
+        $fields['api_url'] = BaseFieldDefinition::create('string')
+            ->setLabel(t('API Url'))
+            ->setDescription(t('The API Url'))
+            ->setSettings(array(
+                'max_length' => 500,
+                'text_processing' => 0,
+            ))
+            ->setDefaultValue('https://www1.gsis.gr/gsisapps/gsisdemo/gsisdemoservice/resource_one')
+            ->setDisplayOptions('view', array(
+                'label' => 'above',
+                'type' => 'string',
+                'weight' => -4,
             ))
             ->setDisplayOptions('form', array(
-              'type' => 'string_textfield',
-              'weight' => -4,
+                'type' => 'string_textfield',
+                'weight' => -4,
             ))
             ->setDisplayConfigurable('form', true)
             ->setDisplayConfigurable('view', true);
 
-      $fields['user_authorization_url'] = BaseFieldDefinition::create('string')
-             ->setLabel(t('User Authorization Url'))
-             ->setDescription(t('The User Authorization Url'))
-             ->setSettings(array(
-               'max_length' => 500,
-               'text_processing' => 0,
-             ))
-             ->setDefaultValue('https://www1.gsis.gr/gsisapps/gsisdemo/oauth/confirm_access')
-             ->setDisplayOptions('view', array(
-               'label' => 'above',
-               'type' => 'string',
-               'weight' => -4,
-             ))
-             ->setDisplayOptions('form', array(
-               'type' => 'string_textfield',
-               'weight' => -4,
-             ))
-             ->setDisplayConfigurable('form', true)
-             ->setDisplayConfigurable('view', true);
-
-       $fields['access_token_url'] = BaseFieldDefinition::create('string')
-                    ->setLabel(t('Access Token Url'))
-                    ->setDescription(t('The Access Token Url'))
-                    ->setSettings(array(
-                      'max_length' => 500,
-                      'text_processing' => 0,
-                    ))
-                    ->setDefaultValue('https://www1.gsis.gr/gsisapps/gsisdemo/oauth/access_token')
-                    ->setDisplayOptions('view', array(
-                      'label' => 'above',
-                      'type' => 'string',
-                      'weight' => -4,
-                    ))
-                    ->setDisplayOptions('form', array(
-                      'type' => 'string_textfield',
-                      'weight' => -4,
-                    ))
-                    ->setDisplayConfigurable('form', true)
-                    ->setDisplayConfigurable('view', true);
-
-                    $fields['signature_method'] = BaseFieldDefinition::create('string')
-                                 ->setLabel(t('Signature Method'))
-                                 ->setDescription(t('The Signature Method'))
-                                 ->setSettings(array(
-                                   'max_length' => 100,
-                                   'text_processing' => 0,
-                                 ))
-                                 ->setDefaultValue('PLAINTEXT')
-                                 ->setDisplayOptions('view', array(
-                                   'label' => 'above',
-                                   'type' => 'string',
-                                   'weight' => -4,
-                                 ))
-                                 ->setDisplayOptions('form', array(
-                                   'type' => 'string_textfield',
-                                   'weight' => -4,
-                                 ))
-                                 ->setDisplayConfigurable('form', true)
-                                 ->setDisplayConfigurable('view', true);
-
-                                 $fields['api_url'] = BaseFieldDefinition::create('string')
-                                              ->setLabel(t('API Url'))
-                                              ->setDescription(t('The API Url'))
-                                              ->setSettings(array(
-                                                'max_length' => 500,
-                                                'text_processing' => 0,
-                                              ))
-                                              ->setDefaultValue('https://www1.gsis.gr/gsisapps/gsisdemo/gsisdemoservice/resource_one')
-                                              ->setDisplayOptions('view', array(
-                                                'label' => 'above',
-                                                'type' => 'string',
-                                                'weight' => -4,
-                                              ))
-                                              ->setDisplayOptions('form', array(
-                                                'type' => 'string_textfield',
-                                                'weight' => -4,
-                                              ))
-                                              ->setDisplayConfigurable('form', true)
-                                              ->setDisplayConfigurable('view', true);
-
-                                              $fields['callback_url'] = BaseFieldDefinition::create('string')
-                                                           ->setLabel(t('Callback Url'))
-                                                           ->setDescription(t('The Callback Url'))
-                                                           ->setSettings(array(
-                                                             'max_length' => 500,
-                                                             'text_processing' => 0,
-                                                           ))
-                                                           ->setDefaultValue('http://eepal.dev/drupal/oauth/cb')
-                                                           ->setDisplayOptions('view', array(
-                                                             'label' => 'above',
-                                                             'type' => 'string',
-                                                             'weight' => -4,
-                                                           ))
-                                                           ->setDisplayOptions('form', array(
-                                                             'type' => 'string_textfield',
-                                                             'weight' => -4,
-                                                           ))
-                                                           ->setDisplayConfigurable('form', true)
-                                                           ->setDisplayConfigurable('view', true);
-
-                                                           $fields['logout_url'] = BaseFieldDefinition::create('string')
-                                                                        ->setLabel(t('Logout_Url'))
-                                                                        ->setDescription(t('The Logout_Url'))
-                                                                        ->setSettings(array(
-                                                                          'max_length' => 500,
-                                                                          'text_processing' => 0,
-                                                                        ))
-                                                                        ->setDefaultValue('https://www1.gsis.gr/gsisapps/gsisdemo/logout.htm?logout_token=')
-                                                                        ->setDisplayOptions('view', array(
-                                                                          'label' => 'above',
-                                                                          'type' => 'string',
-                                                                          'weight' => -4,
-                                                                        ))
-                                                                        ->setDisplayOptions('form', array(
-                                                                          'type' => 'string_textfield',
-                                                                          'weight' => -4,
-                                                                        ))
-                                                                        ->setDisplayConfigurable('form', true)
-                                                                        ->setDisplayConfigurable('view', true);
-
-                                                                        $fields['redirect_url'] = BaseFieldDefinition::create('string')
-                                                                                     ->setLabel(t('Redirect_Url'))
-                                                                                     ->setDescription(t('The Redirect_Url'))
-                                                                                     ->setSettings(array(
-                                                                                       'max_length' => 500,
-                                                                                       'text_processing' => 0,
-                                                                                     ))
-                                                                                     ->setDefaultValue('/dist/#/?auth_token=')
-                                                                                     ->setDisplayOptions('view', array(
-                                                                                       'label' => 'above',
-                                                                                       'type' => 'string',
-                                                                                       'weight' => -4,
-                                                                                     ))
-                                                                                     ->setDisplayOptions('form', array(
-                                                                                       'type' => 'string_textfield',
-                                                                                       'weight' => -4,
-                                                                                     ))
-                                                                                     ->setDisplayConfigurable('form', true)
-                                                                                     ->setDisplayConfigurable('view', true);
-
-      $fields['status'] = BaseFieldDefinition::create('boolean')
-      ->setLabel(t('Publishing status'))
-      ->setDescription(t('A boolean indicating whether the OAuthOST Config is published.'))
-      ->setDefaultValue(true);
-
-      $fields['created'] = BaseFieldDefinition::create('created')
-      ->setLabel(t('Created'))
-      ->setDescription(t('The time that the entity was created.'));
-
-      $fields['changed'] = BaseFieldDefinition::create('changed')
-      ->setLabel(t('Changed'))
-      ->setDescription(t('The time that the entity was last edited.'));
-
-      return $fields;
-  }
+        $fields['callback_url'] = BaseFieldDefinition::create('string')
+            ->setLabel(t('Callback Url'))
+            ->setDescription(t('The Callback Url'))
+            ->setSettings(array(
+                'max_length' => 500,
+                'text_processing' => 0,
+            ))
+            ->setDefaultValue('http://eepal.dev/drupal/oauth/cb')
+            ->setDisplayOptions('view', array(
+                'label' => 'above',
+                'type' => 'string',
+                'weight' => -4,
+            ))
+            ->setDisplayOptions('form', array(
+                'type' => 'string_textfield',
+                'weight' => -4,
+            ))
+            ->setDisplayConfigurable('form', true)
+            ->setDisplayConfigurable('view', true);
+
+        $fields['logout_url'] = BaseFieldDefinition::create('string')
+            ->setLabel(t('Logout_Url'))
+            ->setDescription(t('The Logout_Url'))
+            ->setSettings(array(
+                'max_length' => 500,
+                'text_processing' => 0,
+            ))
+            ->setDefaultValue('https://www1.gsis.gr/gsisapps/gsisdemo/logout.htm?logout_token=')
+            ->setDisplayOptions('view', array(
+                'label' => 'above',
+                'type' => 'string',
+                'weight' => -4,
+            ))
+            ->setDisplayOptions('form', array(
+                'type' => 'string_textfield',
+                'weight' => -4,
+            ))
+            ->setDisplayConfigurable('form', true)
+            ->setDisplayConfigurable('view', true);
+
+        $fields['redirect_url'] = BaseFieldDefinition::create('string')
+            ->setLabel(t('Redirect_Url'))
+            ->setDescription(t('The Redirect_Url'))
+            ->setSettings(array(
+                'max_length' => 500,
+                'text_processing' => 0,
+            ))
+            ->setDefaultValue('/dist/#/?auth_token=')
+            ->setDisplayOptions('view', array(
+                'label' => 'above',
+                'type' => 'string',
+                'weight' => -4,
+            ))
+            ->setDisplayOptions('form', array(
+                'type' => 'string_textfield',
+                'weight' => -4,
+            ))
+            ->setDisplayConfigurable('form', true)
+            ->setDisplayConfigurable('view', true);
+
+        $fields['status'] = BaseFieldDefinition::create('boolean')
+            ->setLabel(t('Publishing status'))
+            ->setDescription(t('A boolean indicating whether the OAuthOST Config is published.'))
+            ->setDefaultValue(true);
+
+        $fields['created'] = BaseFieldDefinition::create('created')
+            ->setLabel(t('Created'))
+            ->setDescription(t('The time that the entity was created.'));
+
+        $fields['changed'] = BaseFieldDefinition::create('changed')
+            ->setLabel(t('Changed'))
+            ->setDescription(t('The time that the entity was last edited.'));
+
+        return $fields;
+    }
 }
diff --git a/source/components/director/director-classcapacity.ts b/source/components/director/director-classcapacity.ts
index cded953de108236fde36830001e289137414588f..59ca8aa4e9084ad400051b7c01abdb4703552fff 100644
--- a/source/components/director/director-classcapacity.ts
+++ b/source/components/director/director-classcapacity.ts
@@ -56,6 +56,27 @@ import {
        </form>
        </div>
 
+    <div id="checksaved" (onHidden)="onHidden('#checksaved')" 
+    class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
+      <div class="modal-dialog modal-lg">
+        <div class="modal-content">
+          <div class="modal-header modal-header-danger">
+            <h3 class="modal-title pull-left"><i class="fa fa-check-square-o"></i>&nbsp;&nbsp;ΠρέπΡι Ξ½Ξ± ΟƒΟ…Ο€Ξ»Ξ·ΟΟŽΟƒΞ΅Ο„Ξ΅ όλα τα πΡδία</h3>
+            <button type="button" class="close pull-right" aria-label="Close" (click)="hideModal('#checksaved')">
+              <span aria-hidden="true"><i class="fa fa-times"></i></span>
+            </button>
+          </div>
+          <div class="modal-body">
+            <p>Ξ— αποθΞ�κΡυση δΡ μπορΡί Ξ½Ξ± γίνΡι Ξ±Ξ½ δΡν ΟƒΟ…ΞΌΟ€Ξ»Ξ·ΟΟŽΟƒΞ΅Ο„Ξ΅ όλα τα στοιχΡία της Ο†ΟŒΟΞΌΞ±Ο‚!</p>
+          </div>
+          <div class="modal-footer">
+            <button type="button" class="btn btn-default pull-left" data-dismiss="modal">ΞšΞ»Ξ΅Ξ―ΟƒΞΉΞΌΞΏ</button>
+          </div>
+        </div>
+      </div>
+    </div>
+
+
     <div id="capacitysaved" (onHidden)="onHidden('#capacitysaved')" 
     class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
       <div class="modal-dialog modal-lg">
@@ -77,6 +98,9 @@ import {
     </div>
 
 
+    
+
+
    `
 })
 
@@ -98,10 +122,13 @@ import {
     private classCapacity$: BehaviorSubject<any>;
     private classCapacitySub: Subscription;
     private retrievedStudent: BehaviorSubject<boolean>;
+    private modalTitle: BehaviorSubject<string>;
+    private modalText: BehaviorSubject<string>;
+    private modalHeader: BehaviorSubject<string>;
     
 
 
-
+ 
     constructor(private fb: FormBuilder,
         private _hds: HelperDataService,
         private activatedRoute: ActivatedRoute,
@@ -114,6 +141,9 @@ import {
         this.selectionCClass = new BehaviorSubject(false);
         this.retrievedStudent = new BehaviorSubject(false);
         this.School$ = new BehaviorSubject([{}]);
+        this.modalTitle =  new BehaviorSubject("");
+        this.modalText =  new BehaviorSubject("");
+        this.modalHeader =  new BehaviorSubject("");
         this.formGroup = this.fb.group({
             tomeas: ['', []],
             taxi: ['', []],
@@ -155,6 +185,7 @@ import {
 
     ngOnInit() {
         (<any>$('#capacitysaved')).appendTo("body");
+        (<any>$('#checksaved')).appendTo("body");
         this.retrievedStudent.next(false);
 
             this.SchoolSub = this._hds.gettypeofschool().subscribe(x => {
@@ -298,11 +329,20 @@ import {
 
     saveCapacity() {
 
+        var taxi = +this.formGroup.value.taxi;
         var tomeas = +this.formGroup.value.tomeas;
         var specialit = +this.formGroup.value.specialit;
+        var capc = +this.formGroup.value.capacity;
+        
+
+         if ((taxi === 2 && tomeas === 0) || (taxi === 3  && tomeas === 0 ) || (taxi ===3  && specialit === 0 ) 
+             || (taxi === 4  && tomeas === 0 ) || (taxi ===4  && specialit === 0 ) || (taxi = 0) || (capc ===0))
+          {
+              this.showModal("#checksaved");
+          } else 
+        {
         
          this.saveCapacitySub = this._hds.saveCapacity(this.formGroup.value.taxi, tomeas, specialit, this.formGroup.value.capacity).subscribe(data => {
-                
                  },
                 error => {
                     
@@ -312,9 +352,11 @@ import {
                  console.log("Saved Capacity");
                  this.showModal("#capacitysaved");
                  });
+         }
                  
 
     }
 
+ 
 
 }
diff --git a/source/components/director/director-view.ts b/source/components/director/director-view.ts
index 2088249d87acd3b5dcd90325afa99e7482b65d37..12e11e655fd56a63804291a443c253532f06c539 100644
--- a/source/components/director/director-view.ts
+++ b/source/components/director/director-view.ts
@@ -146,6 +146,7 @@ import {
 
             </nav>
             </div>
+
             </form>
             </div>
 
@@ -175,14 +176,18 @@ import {
     private selectionBClass: BehaviorSubject<boolean>;
     private selectiontype: BehaviorSubject<boolean>;
     private selectionCClass: BehaviorSubject<boolean>;
+    private limitsSub: Subscription;
+    private limits$: BehaviorSubject<any>;
     private SchoolId ;
     private currentclass: Number;
     private saved: Array<number> = new Array();
     private limitdown = 0;
     private limitup = 5;
     private pageno = 1;
+    public totallimit;
     private userActive = <number>-1;
     private type: Number;
+    public tot_pages: number;
 
 
     @ViewChild('fileInput') fileInput: ElementRef;
@@ -198,9 +203,11 @@ import {
         this.StudentsSize$ = new BehaviorSubject({});
         this.SavedStudents$ = new BehaviorSubject({});
         this.SubmitedDetails$ = new BehaviorSubject([{}]);
+        this.limits$ = new BehaviorSubject([{}]);
         this.retrievedStudent = new BehaviorSubject(false);
         this.selectionBClass = new BehaviorSubject(false);
         this.selectionCClass = new BehaviorSubject(false);
+        //this.outoflimits = new BehaviorSubject(false);
         this.School$ = new BehaviorSubject([{}]);
         this.selectiontype = new BehaviorSubject(true);
 
@@ -215,6 +222,7 @@ import {
 
     }
 
+
     ngOnDestroy() {
         if (this.StudentSelectedSub)
             this.StudentSelectedSub.unsubscribe();
@@ -231,6 +239,7 @@ import {
 
     }
 
+
     ngOnInit() {
 
 
@@ -328,57 +337,96 @@ import {
 
     findstudent(txop, pageno) {
 
-        var tot_pages: number;
+       
         var sectorint = +this.formGroup.value.tomeas;
-        if (txop.value === "1") {
-            this.currentclass = 1;
-        }
-        else if (txop.value === "2") {
-            this.currentclass = 2;
-        }
-        else if (txop.value === "3") {
-            this.currentclass = 3;
-        }
-
-        else if (txop.value === "4") {
-            this.currentclass = 4;
-        }
+        this.currentclass = +txop.value;
+        
         this.formGroup.get('pageno').setValue(this.pageno);
         if (this.pageno == 1) {
-            console.log(this.SchoolId, sectorint, this.currentclass, "testaaaaaa");
+
+            console.log("mphkepage = 1");
             this.StudentsSizeSub = this._hds.getStudentPerSchool(sectorint, this.currentclass, 0, 0).subscribe(x => {
                 this.StudentsSize$.next(x);
-                tot_pages = x.id / 5;
+                this.totallimit = x.id;
+
+            this.limitsSub = this._hds.getlimitsofcourse(this.currentclass).subscribe(data => {
+            this.limits$.next(data);
+            console.log(this.totallimit, data[0].limitdown, "oria");
+             this.tot_pages = x.id / 5;
                 if (x.id % 5 > 0) {
-                    tot_pages = (x.id - (x.id % 5)) / 5 + 1;
+                    this.tot_pages = (x.id - (x.id % 5)) / 5 + 1;
                 }
-                console.log(tot_pages,"totpages")
-                if (isNaN(tot_pages)){
+                console.log(this.tot_pages,"totpages")
+                if (isNaN(this.tot_pages)){
                   this.retrievedStudent.next(false);
-                  tot_pages = 0;
+                  this.tot_pages = 0;
                 }
-                this.formGroup.get('maxpage').setValue(tot_pages);
+            if ( (x.id < data[0].limitdown) || (isNaN(this.tot_pages)))
+            {
+              console.log("mphkeprwto!")
+                  this.retrievedStudent.next(false);
+                  this.tot_pages = 0;
+                  this.formGroup.get('maxpage').setValue(this.tot_pages);
+                  //this.outoflimits.next(true);
+            }
+            else
+            {
+               // this.outoflimits.next(false);
+                
+                this.formGroup.get('maxpage').setValue(this.tot_pages);
+                console.log(this.tot_pages,"mazeuw mathites");
+                this.StudentInfoSub = this._hds.getStudentPerSchool(sectorint, this.currentclass, this.limitdown, this.limitup).subscribe(data => {
+                this.StudentInfo$.next(data);
+            
+                console.log("tot.pages", this.formGroup.value.maxpage, "max1", this.tot_pages);
+                this.retrievedStudent.next(true);
+              
+            },
+            error => {
+                this.StudentInfo$.next([{}]);
+                console.log("Error Getting Students");
+            },
+            () => console.log("Getting Students"));
+
+
+
+            }
+            
+              },
+            error => {
+                this.limits$.next([{}]);
+                console.log("Error Getting limits");
+            },
+            () => console.log("Getting limits"));
+               
             });
 
         }
-        console.log(this.limitdown, this.limitup,"mits");
-        this.StudentInfoSub = this._hds.getStudentPerSchool(sectorint, this.currentclass, this.limitdown, this.limitup).subscribe(data => {
-            this.StudentInfo$.next(data);
-            if (tot_pages === 0){
-                  console.log("tot.pages", this.formGroup.value.maxpage);
+        else{
+              console.log("eisai edw", this.tot_pages);
+     
+       
+              if (this.tot_pages == 0 ){
+                  console.log("mphke1", this.formGroup.value.maxpage, this.tot_pages);
                   this.retrievedStudent.next(false);
                 }
              else
               {
-                console.log("tot.pages", this.formGroup.value.maxpage, "max", tot_pages);
+                console.log(this.tot_pages,"mazeuw mathites");
+                this.StudentInfoSub = this._hds.getStudentPerSchool(sectorint, this.currentclass, this.limitdown, this.limitup).subscribe(data => {
+                this.StudentInfo$.next(data);
+            
+                console.log("tot.pages", this.formGroup.value.maxpage, "max1", this.tot_pages);
                 this.retrievedStudent.next(true);
-              }
-        },
+              
+            },
             error => {
                 this.StudentInfo$.next([{}]);
                 console.log("Error Getting Students");
             },
             () => console.log("Getting Students"));
+          }
+        }
 
     }
 
diff --git a/source/components/infoviews/eduadmin-view.ts b/source/components/infoviews/eduadmin-view.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d0f4a68356509824a3ce649e37e736390371778f
--- /dev/null
+++ b/source/components/infoviews/eduadmin-view.ts
@@ -0,0 +1,146 @@
+import { Component, OnInit, OnDestroy, ElementRef, ViewChild, Injectable} from "@angular/core";
+import { AppSettings } from '../../app.settings';
+import { HelperDataService } from '../../services/helper-data-service';
+import {Observable} from "rxjs/Observable";
+import {Http, Headers, RequestOptions} from '@angular/http';
+import { NgRedux, select } from 'ng2-redux';
+import { IAppState } from '../../store/store';
+import {Router, ActivatedRoute, Params} from '@angular/router';
+import { BehaviorSubject, Subscription } from 'rxjs/Rx';
+import { ILoginInfo } from '../../store/logininfo/logininfo.types';
+
+import {
+    FormBuilder,
+    FormGroup,
+    FormControl,
+    FormArray,
+    Validators,
+} from '@angular/forms';
+@Component({
+    selector: 'eduadmin-view',
+    template: `
+            <h3> Ξ‘ΟΞΉΞΈΞΌΟŒΟ‚ ΞœΞ±ΞΈΞ·Ο„ΟŽΞ½ Ξ±Ξ½Ξ± τμΞ�ΞΌΞ± σχολΡίου </h3>
+
+            <ul class="list-group main-view">
+              <div *ngFor="let SchoolNames$  of SchoolsPerPerf$  | async; let i=index; let isOdd=odd; let isEven=even"  >
+                  <li class="list-group-item isclickable" (click)="setActiveRegion(SchoolNames$.id)" [class.changelistcolor]= "SchoolNames$.status === false" [class.oddout]="isOdd" [class.evenout]="isEven" [class.selectedout]="regionActive === SchoolNames$.id" >
+                     <h5> {{SchoolNames$.name}}</h5>
+                  </li>
+                 <div *ngFor="let CoursesNames$  of CoursesPerPerf$  | async; let j=index; let isOdd2=odd; let isEven2=even" [class.oddin]="isOdd2" [class.evenin]="isEven2" [class.changecolor]="calccolor(CoursesNames$.size,CoursesNames$.limitdown)" [hidden]="SchoolNames$.id !== regionActive" >
+                    <div> {{CoursesNames$.name}}</div> <div class= "aastyle"><strong>Ξ‘ΟΞΉΞΈΞΌΟŒΟ‚ ΞœΞ±ΞΈΞ·Ο„ΟŽΞ½:</strong>{{CoursesNames$.size}} </div>
+
+                 </div>
+             </div>
+
+             </ul>
+
+             <div class="col-md-6">
+                <button type="button" class="btn-primary btn-lg pull-right" (click)="navigateToApplication()" >
+                <i class="fa fa-forward"></i>
+                </button>
+            </div>
+
+
+   `
+})
+
+@Injectable() export default class EduadminView implements OnInit, OnDestroy {
+
+    public formGroup: FormGroup;
+    private SchoolsPerPerf$: BehaviorSubject<any>;
+    private SchoolPerPerfSub: Subscription;
+    private LimitPerCateg$: BehaviorSubject<any>;
+    private LimitPerCategSub: Subscription;
+    private CoursesPerPerf$: BehaviorSubject<any>;
+    private CoursesPerPerfSub: Subscription;
+    private StudentsSize$: BehaviorSubject<any>;
+    private StudentsSizeSub: Subscription;
+    public perfecture ;
+    private regionActive = <number>-1;
+    private School$: BehaviorSubject<any>;
+    private SchoolSub: Subscription;
+
+
+
+    constructor(private fb: FormBuilder,
+      private router: Router,
+      private _hds: HelperDataService,
+      ) {
+        this.SchoolsPerPerf$ = new BehaviorSubject([{}]);
+        this.LimitPerCateg$ = new BehaviorSubject([{}]);
+        this.CoursesPerPerf$ = new BehaviorSubject([{}]);
+        this.StudentsSize$ = new BehaviorSubject({});
+        this.School$ = new BehaviorSubject([{}]);
+        this.formGroup = this.fb.group({
+        });
+
+    }
+
+    ngOnDestroy() {
+      }
+
+    ngOnInit() {
+
+      this.SchoolSub = this._hds.getSchoolId().subscribe(x => {
+                  this.School$.next(x);
+                  console.log(x[0].id, "perfectureID");
+                   this.perfecture = x[0].id;
+                   this.SchoolPerPerfSub = this._hds.getSchools().subscribe(data => {
+                       this.SchoolsPerPerf$.next(data);
+                   },
+                       error => {
+                           this.SchoolsPerPerf$.next([{}]);
+                           console.log("Error Getting Schools");
+                       },
+                       () => console.log("Getting Schools"));
+
+                  },
+                  error => {
+                      this.School$.next([{}]);
+                      console.log("Error Getting School");
+                  },
+                  () => console.log("Getting School "));
+
+
+
+    }
+
+
+     setActiveRegion(ind) {
+
+      if (ind === this.regionActive)
+        ind = -1;
+
+      this.regionActive = ind;
+      this.CoursesPerPerfSub = this._hds.getCoursePerPerfecture(this.regionActive).subscribe(data => {
+            this.CoursesPerPerf$.next(data);
+        },
+            error => {
+                this.CoursesPerPerf$.next([{}]);
+                console.log("Error Getting Courses");
+            },
+            () => console.log("Getting Courses Per Perf"));
+
+
+
+    }
+
+
+    navigateToApplication()
+    {
+
+     var id: string= String(this.regionActive);
+     this.router.navigate(['', {ids:id}]);
+
+    }
+
+    calccolor(size, limit)
+    {
+
+      if (size < limit)
+        return true;
+      else
+        return false;
+    }
+
+}
diff --git a/source/components/infoviews/perfecture-view.ts b/source/components/infoviews/perfecture-view.ts
index b0639d45b0c876d21436d089e9b76c770cd1355c..b86175e70a0451a3de5965d9b90b63215094dbe7 100644
--- a/source/components/infoviews/perfecture-view.ts
+++ b/source/components/infoviews/perfecture-view.ts
@@ -23,7 +23,7 @@ import {
 
             <ul class="list-group main-view">
               <div *ngFor="let SchoolNames$  of SchoolsPerPerf$  | async; let i=index; let isOdd=odd; let isEven=even"  >
-                  <li class="list-group-item isclickable" (click)="setActiveRegion(SchoolNames$.id)" [class.changelistcolor]= "SchoolNames$.status === true" [class.oddout]="isOdd" [class.evenout]="isEven" [class.selectedout]="regionActive === SchoolNames$.id" >
+                  <li class="list-group-item isclickable" (click)="setActiveRegion(SchoolNames$.id)" [class.changelistcolor]= "SchoolNames$.status === false" [class.oddout]="isOdd" [class.evenout]="isEven" [class.selectedout]="regionActive === SchoolNames$.id" >
                      <h5> {{SchoolNames$.name}}</h5>
                   </li>
                  <div *ngFor="let CoursesNames$  of CoursesPerPerf$  | async; let j=index; let isOdd2=odd; let isEven2=even" [class.oddin]="isOdd2" [class.evenin]="isEven2" [class.changecolor]="calccolor(CoursesNames$.size,CoursesNames$.limitdown)" [hidden]="SchoolNames$.id !== regionActive" >
@@ -85,7 +85,7 @@ import {
                   this.School$.next(x);
                   console.log(x[0].id, "perfectureID");
                    this.perfecture = x[0].id;
-                   this.SchoolPerPerfSub = this._hds.getSchoolPerPerfecture().subscribe(data => {
+                   this.SchoolPerPerfSub = this._hds.getSchools().subscribe(data => {
                        this.SchoolsPerPerf$.next(data);
                    },
                        error => {
diff --git a/source/components/minister/minister-informstudents.ts b/source/components/minister/minister-informstudents.ts
index 090f42ff34a7806407e5d14856d6e5dcea7e2ce3..3760960977ef3af30f5c005b22f93b423aeaf9f6 100644
--- a/source/components/minister/minister-informstudents.ts
+++ b/source/components/minister/minister-informstudents.ts
@@ -42,8 +42,14 @@ import { API_ENDPOINT } from '../../app.settings';
     <h5> >ΑποστολΞ� ΡιδοποιΞ�σΡων <br></h5>
     <br><br>
     <div class="col-md-12">
-      <button type="submit" class="btn btn-lg btn-block"  *ngIf="(loginInfo$ | async).size !== 0"  (click)="informUnlocatedStudents()" >
-          Μα΢ικΞ� αποστολΞ� e-mail στους μαθητές που δΡν τοποθΡτΞ�ΞΈΞ·ΞΊΞ±Ξ½<span class="glyphicon glyphicon-menu-right"></span>
+      <button type="submit" class="btn btn-lg btn-block"  *ngIf="(loginInfo$ | async).size !== 0"  (click)="informUnlocatedStudents(true)" >
+          Μα΢ικΞ� αποστολΞ� e-mail στους μαθητές που ΔΕΝ τοποθΡτΞ�ΞΈΞ·ΞΊΞ±Ξ½<span class="glyphicon glyphicon-menu-right"></span>
+      </button>
+    </div>
+    <br>
+    <div class="col-md-12">
+      <button type="submit" class="btn btn-lg btn-block"  *ngIf="(loginInfo$ | async).size !== 0"  (click)="informUnlocatedStudents(false)" >
+          Μα΢ικΞ� αποστολΞ� e-mail στους μαθητές που τοποθΡτΞ�ΞΈΞ·ΞΊΞ±Ξ½<span class="glyphicon glyphicon-menu-right"></span>
       </button>
     </div>
 
@@ -126,13 +132,13 @@ import { API_ENDPOINT } from '../../app.settings';
         //this.isModalShown.next(false);
     }
 
-    informUnlocatedStudents() {
+    informUnlocatedStudents(unallocated) {
 
       this.successSending = -2;
       this.numSuccessMails = 0;
       this.numFailMails = 0;
 
-      this._hds.informUnlocatedStudents(this.minedu_userName, this.minedu_userPassword).subscribe(data => {
+      this._hds.informUnlocatedStudents(this.minedu_userName, this.minedu_userPassword, unallocated).subscribe(data => {
           this.numSuccessMails = data.num_success_mail;
           this.numFailMails = data.num_fail_mail;
           //console.log("HERE!");
@@ -144,20 +150,17 @@ import { API_ENDPOINT } from '../../app.settings';
 
           this.modalTitle.next("ΞšΞ±Ο„Ξ±Ξ½ΞΏΞΌΞ� ΞœΞ±ΞΈΞ·Ο„ΟŽΞ½");
           this.modalText.next("Αποτυχία αποστολΞ�Ο‚ e-mails!");
-          //this.modalHeader = "modal-header-warning";
           this.modalHeader.next("modal-header-warning");
           this.showModal();
         },
         () => {
-          console.log("Success");
+          console.log("ΕπιτυχΞ�Ο‚ αποστολΞ� e-mails!");
           this.successSending = 1;
 
-          //this.modalHeader = "modal-header-success";
           this.modalHeader.next("modal-header-success");
           this.modalTitle.next("ΞšΞ±Ο„Ξ±Ξ½ΞΏΞΌΞ� ΞœΞ±ΞΈΞ·Ο„ΟŽΞ½");
           let txtModal = "ΈγινΡ αποστολΞ� " + this.numSuccessMails + " e-mails! ";
           if (this.numFailMails != 0) {
-            //this.modalHeader = "modal-header-warning";
             this.modalHeader.next("modal-header-warning");
             txtModal += "ΞšΞ¬Ο€ΞΏΞΉΞ± e-mail δΡν έχουν σταλΡί. ΔΡν Ξ�ταν δυνατΞ� Ξ· αποστολΞ� " + this.numFailMails + " e-mails!";
           }
diff --git a/source/components/minister/minister-reports.ts b/source/components/minister/minister-reports.ts
index 1fa87329d1cd486648f9b89c523f83264855dcd5..282e0619692ea87b62e3a190e7866aac61e20918 100644
--- a/source/components/minister/minister-reports.ts
+++ b/source/components/minister/minister-reports.ts
@@ -47,11 +47,16 @@ import { API_ENDPOINT } from '../../app.settings';
               Ξ‘ΟΞΉΞΈΞΌΟŒΟ‚ ΞœΞ±ΞΈΞ·Ο„ΟŽΞ½ ΞΊΞ±ΞΉ Ξ Ξ»Ξ·ΟΟŒΟ„Ξ·Ο„Ξ± ΟƒΟ‡ΞΏΞ»ΞΉΞΊΟŽΞ½ μονάδων ΕΠΑΛ
           </button>
           <br><br>
-          <button type="button" class="btn btn-alert"  (click)="nav_to_reportpath(4)" [hidden]="minedu_userName == ''" >
+          <button type="button" class="btn btn-alert"  (click)="nav_to_reportpath(4)" [hidden]="minedu_userName == '' || userRole == 'pde' || userRole == 'dide' " >
           <i class="fa fa-file-text"></i>
               Σχολικές μονάδΡς που δΡν έχουν Ξ΄Ξ·Ξ»ΟŽΟƒΞ΅ΞΉ Ξ§Ο‰ΟΞ·Ο„ΞΉΞΊΟŒΟ„Ξ·Ο„Ξ± τμημάτων
           </button>
           <br><br>
+          <button type="button" class="btn btn-alert"  (click)="nav_to_reportpath(5)" [hidden]="minedu_userName == '' " >
+          <i class="fa fa-file-text"></i>
+              ΟλιγομΡλΞ� τμΞ�ματα (Προσωρινά τοποθΡτημένοι μαθητές)
+          </button>
+          <br><br>
         </div>
 
     </div>
@@ -124,7 +129,7 @@ import { API_ENDPOINT } from '../../app.settings';
 
       if (repId == 1)
         this.router.navigate(['/ministry/report-general', repId]);
-      else if (repId == 2 || repId == 3)
+      else if (repId == 2 || repId == 3 || repId == 5)
         this.router.navigate(['/ministry/report-all-stat', repId]);
       else if (repId == 4)
         this.router.navigate(['/ministry/report-no-capacity', repId]);
diff --git a/source/components/minister/report-all-stat.ts b/source/components/minister/report-all-stat.ts
index 89d4d478e00bf565a907144ba71e19f30cc1bc66..218cdb066f0adf44a386849232f4a714f08f1d1e 100644
--- a/source/components/minister/report-all-stat.ts
+++ b/source/components/minister/report-all-stat.ts
@@ -67,7 +67,7 @@ import { API_ENDPOINT } from '../../app.settings';
                 </select>
           </div>
 
-          <button type="button" class="btn-link" (click)="toggleCourseFilter()" *ngIf = "reportId == 3" >
+          <button type="button" class="btn-link" (click)="toggleCourseFilter()" *ngIf = "reportId == 3 || reportId == 5" >
               > Φίλτρο ΕπιλογΞ�Ο‚ ΀ομέα / Ξ•ΞΉΞ΄ΞΉΞΊΟŒΟ„Ξ·Ο„Ξ±Ο‚
           </button>
           <br>
@@ -170,6 +170,7 @@ import { API_ENDPOINT } from '../../app.settings';
     private classSelected: number;
     private sectorSelected: number;
     private courseSelected: number;
+    private distribFinalized: number;
     private enableRegionFilter: boolean;
     private enableCourseFilter: boolean;
     private userLoggedIn: string;
@@ -358,6 +359,12 @@ createReport(regionSel) {
   }
   else if (this.reportId === 3)  {
     route = "/ministry/report-all-stat/";
+    this.distribFinalized = 1;
+    this.settings = this.reportSchema.reportAllStatSchema;
+  }
+  else if (this.reportId === 5)  {
+    route = "/ministry/report-all-stat/";
+    this.distribFinalized = 0;
     this.settings = this.reportSchema.reportAllStatSchema;
   }
 
@@ -385,7 +392,7 @@ createReport(regionSel) {
  else if (this.userLoggedIn == DIDE_ROLE)
     admSel = this.adminAreaSelected;
 
-  this.generalReportSub = this._hds.makeReport(this.minedu_userName, this.minedu_userPassword, route, regSel, admSel, schSel, clSel, secSel, courSel).subscribe(data => {
+  this.generalReportSub = this._hds.makeReport(this.minedu_userName, this.minedu_userPassword, route, regSel, admSel, schSel, clSel, secSel, courSel, this.distribFinalized).subscribe(data => {
       this.generalReport$.next(data);
       this.data = data;
 
diff --git a/source/components/minister/report-general.ts b/source/components/minister/report-general.ts
index b340adb6d6e366f4f33a4398263215e1464ae88b..f41ff7206e38e1a829c554605046b562b411d52f 100644
--- a/source/components/minister/report-general.ts
+++ b/source/components/minister/report-general.ts
@@ -178,7 +178,7 @@ createReport(regionSel) {
 
  let regSel = 0;
 
- this.generalReportSub = this._hds.makeReport(this.minedu_userName, this.minedu_userPassword, route, 0, 0, 0, 0, 0,0).subscribe(data => {
+ this.generalReportSub = this._hds.makeReport(this.minedu_userName, this.minedu_userPassword, route, 0, 0, 0, 0, 0,0, 0).subscribe(data => {
       this.generalReport$.next(data);
       this.data = data;
   },
@@ -242,7 +242,8 @@ generateGraphData() {
      labelsX.push("2Ξ· Προτίμηση");
      labelsX.push("3Ξ· Προτίμηση");
      labelsX.push("Μη τοποθΡτημένοι");
-     for (let i = 1; i <=  4; i++) {
+     labelsX.push("Προσωρινά τοποθΡτημένοι σΡ ολιγομΡλΞ�");
+     for (let i = 1; i <=  5; i++) {
        this.d3data.push([
          labelsX[i-1],
          this.data[i].numStudents /   this.data[0].numStudents,
diff --git a/source/components/minister/report-no-capacity.ts b/source/components/minister/report-no-capacity.ts
index c4d75596fe018e5b06c3845e1e3b85b3da97fc1b..80e43c90306848bcf92521b6a25a97a69921478a 100644
--- a/source/components/minister/report-no-capacity.ts
+++ b/source/components/minister/report-no-capacity.ts
@@ -172,7 +172,7 @@ createReport() {
     return;
   }
 
- this.generalReportSub = this._hds.makeReport(this.minedu_userName, this.minedu_userPassword, route, this.enableCapacityFilter, 0, 0, 0, 0,0).subscribe(data => {
+ this.generalReportSub = this._hds.makeReport(this.minedu_userName, this.minedu_userPassword, route, this.enableCapacityFilter, 0, 0, 0, 0, 0, 0).subscribe(data => {
       this.generalReport$.next(data);
       this.data = data;
   },
diff --git a/source/components/school.home.ts b/source/components/school.home.ts
index ab3412558e1a8145d74610ba9ecac92fbc33a57e..6f515f857b5c725b8203e4e7d10eae9f38a10da9 100644
--- a/source/components/school.home.ts
+++ b/source/components/school.home.ts
@@ -90,6 +90,9 @@ export default class SchoolHome implements OnInit, OnDestroy {
                         }
                         else if (this.authRole === 'pde')
                             this.router.navigate(['/school/perfecture-view']);
+                        else if (this.authRole === 'dide')
+                            this.router.navigate(['/school/eduadmin-view']);
+                        
                     }
                     return loginInfoToken;
                 }, {});
diff --git a/source/containers/main.routes.ts b/source/containers/main.routes.ts
index d3d91722db1e55faabb7b99b6e57764ef0982165..2c480c8dfd5e66dfe8ee49b00aac2fcc8ed9a9fd 100644
--- a/source/containers/main.routes.ts
+++ b/source/containers/main.routes.ts
@@ -26,6 +26,7 @@ import AfterSubmit from '../components/student-application-form/after.submit';
 import DirectorView from '../components/director/director-view';
 import DirectorButtons from '../components/director/director.buttons';
 import PerfectureView from '../components/infoviews/perfecture-view';
+import EduadminView from '../components/infoviews/eduadmin-view';
 import DirectorClassCapacity from '../components/director/director-classcapacity';
 import MinisterView from '../components/minister/minister-view';
 import MinisterReports from '../components/minister/minister-reports';
@@ -37,6 +38,8 @@ import MinisterSettings from '../components/minister/minister-settings';
 import SchoolAuthGuard from '../guards/school.auth.guard';
 import StudentAuthGuard from '../guards/student.auth.guard';
 import RegionEduAuthGuard from '../guards/regionedu.auth.guard';
+import  EduAdminAuthGuard from  '../guards/eduadmin.auth.guard';
+
 import MinistryAuthGuard from '../guards/ministry.auth.guard';
 import Breadcrumbs from '../components/main/breadcrumbs';
 
@@ -67,13 +70,14 @@ export const MainRoutes: Routes = [
   { path: 'school/director-buttons', component: DirectorButtons, canActivate: [SchoolAuthGuard]  },
   { path: 'school/director-classcapacity', component: DirectorClassCapacity, canActivate: [SchoolAuthGuard] },
   { path: 'ministry/minister-view', component: MinisterView, canActivate: [MinistryAuthGuard]  },
-  { path: 'ministry/minister-reports', component: MinisterReports, canActivate: [MinistryAuthGuard]  },
-  { path: 'ministry/report-all-stat/:reportId', component: ReportAllStat, canActivate: [MinistryAuthGuard]  },
+  { path: 'ministry/minister-reports', component: MinisterReports },
+  { path: 'ministry/report-all-stat/:reportId', component: ReportAllStat  },
   { path: 'ministry/report-general/:reportId', component: ReportGeneral, canActivate: [MinistryAuthGuard]  },
   { path: 'ministry/report-no-capacity/:reportId', component: ReportNoCapacity, canActivate: [MinistryAuthGuard]  },
   { path: 'ministry/minister-informstudents', component: InformStudents, canActivate: [MinistryAuthGuard]  },
   { path: 'ministry/minister-settings', component: MinisterSettings, canActivate: [MinistryAuthGuard] },
   { path: 'school/perfecture-view', component: PerfectureView, canActivate: [RegionEduAuthGuard] },
+  { path: 'school/eduadmin-view', component: EduadminView, canActivate: [EduAdminAuthGuard] },
 ];
 
 export const MainDeclarations = [
@@ -108,5 +112,6 @@ export const MainDeclarations = [
   MinisterSettings,
   PerfectureView,
   Breadcrumbs,
-  DirectorButtons
+  DirectorButtons,
+  EduadminView,
 ];
diff --git a/source/guards/ministry.auth.guard.ts b/source/guards/ministry.auth.guard.ts
index 13b33dbf7a4b7a8cd763c0853487dd2331545a96..374370f5e0ea8434dd4638b89da7a6dc3796d890 100644
--- a/source/guards/ministry.auth.guard.ts
+++ b/source/guards/ministry.auth.guard.ts
@@ -12,7 +12,9 @@ export default class MinistryAuthGuard implements CanActivate {
   canActivate() {
     return this.authService.isLoggedIn(MINISTRY_ROLE).then(loggedIn => {
         if (!loggedIn) {
+            console.log("I am IN!");
             this.router.navigate(['/ministry/logout']);
+            //this.router.navigate(['/ministy/minister-settings']);
         }
         return loggedIn;
     }).catch(err => {
diff --git a/source/services/helper-data-service.ts b/source/services/helper-data-service.ts
index 27a4519c05cedfd4b3cdf2d55f31f0d59a0c3267..02253214dc268b7be6a8321ac3682e9988041f36 100644
--- a/source/services/helper-data-service.ts
+++ b/source/services/helper-data-service.ts
@@ -609,7 +609,7 @@ export class HelperDataService implements OnInit, OnDestroy {
     }
 
 
-    makeReport(username, userpassword, routepath, regionsel, adminsel, schsel, clsel, secsel, coursel) {
+    makeReport(username, userpassword, routepath, regionsel, adminsel, schsel, clsel, secsel, coursel, distribfinal) {
 
         let headers = new Headers({
             "Content-Type": "application/json",
@@ -628,7 +628,7 @@ export class HelperDataService implements OnInit, OnDestroy {
         }
         else if (routepath == "/ministry/report-all-stat/"){
             return this.http.get(`${AppSettings.API_ENDPOINT}` + routepath + regionsel + "/" + adminsel + "/"  + schsel + "/"  +
-                                  clsel + "/"  + secsel + "/"  + coursel , options)
+                                  clsel + "/"  + secsel + "/"  + coursel + "/" + distribfinal , options)
                 .map(response => response.json());
           }
           else if (routepath == "/ministry/report-no-capacity/"){
@@ -641,19 +641,26 @@ export class HelperDataService implements OnInit, OnDestroy {
 
     }
 
-    informUnlocatedStudents(username, userpassword) {
+    informUnlocatedStudents(username, userpassword, unallocated) {
 
       let headers = new Headers({
           "Content-Type": "application/json",
       });
       this.createMinistryAuthorizationHeader(headers, username, userpassword );
       let options = new RequestOptions({ headers: headers });
-      return this.http.get(`${AppSettings.API_ENDPOINT}/ministry/send-massive-mail` , options)
+
+      let route="";
+      if (unallocated == true)
+        route = "ministry/send-unallocated-massive-mail";
+      else
+        route = "ministry/send-located-massive-mail";
+
+      return this.http.get(`${AppSettings.API_ENDPOINT}/` + route , options)
           .map(response => response.json());
     }
 
 
-    getSchoolPerPerfecture() {
+    getSchools() {
 
         this.loginInfo$.getValue().forEach(loginInfoToken => {
             this.authToken = loginInfoToken.auth_token;
@@ -875,5 +882,21 @@ gettypeofschool(){
 
 }
 
+getlimitsofcourse(classid){
+
+    this.loginInfo$.getValue().forEach(loginInfoToken => {
+            this.authToken = loginInfoToken.auth_token;
+            this.authRole = loginInfoToken.auth_role;
+        });
+        let headers = new Headers({
+            "Content-Type": "application/json",
+        });
+        this.createAuthorizationHeader(headers);
+        let options = new RequestOptions({ headers: headers });
+        return this.http.get(`${AppSettings.API_ENDPOINT}/epal/getlimitsperCourse/`+ classid , options)
+            .map(response => response.json());
+
+}
+
 
 }