<?php
	class cStudentPage extends cUsersPage
	{ 
    function __construct( $smarty, $db, $action, $post, $get )
    {
      parent::__construct( $smarty, $db, $action, $post, $get );      
      $this->menuItem = $this->menu->GetItemByLabel("Študenti");            
      $this->menuItem->bSelected = true;
      $this->menuItem->bExpanded = true;
      $this->exchgManager = new cExchangeManager($this->db);
      
      if ( !empty($this->getParams["id"]) )
        $this->user = new cStudent($this->getParams["id"], $this->db);       
    }
    
    protected function VerifyUserValues(&$userValues, &$specID, &$year, &$error)
    {
      if ( parent::VerifyUserValues($userValues, $error) )
      {      
        if ( strlen($this->postParams["isic"]) != 10 )
        {
          $this->smarty->assign("error", "Musíte zadať správne číslo ISIC!" );
          return false;
        }
        if ( empty( $this->postParams["year"] ) )
        {
          $this->smarty->assign("error", "Musíte zadať rok štúdia!" );
          return false;
        }
        if ( $this->postParams["year"] <= 0 || $this->postParams["year"] > 8 )
        {
          $this->smarty->assign("error", "Rok štúdia môže byť iba hodnota od 1 do 8" );
          return false;        	
        }
          
        $tempStudent = new cStudent(0, $this->db);
        if ( $tempStudent->LoadByISIC($this->postParams["isic"], $error) &&
             !($this->user && $this->user->GetISIC() == $this->postParams["isic"]) )
        {
          $this->smarty->assign("error", "Študent rovnakým ISIC číslom už existuje!");
          return false;
        }
        $specID = $this->postParams["spec"];
        $year = $this->postParams["year"];
        return empty( $error );         
      }
      return false;
    }
    
    private function AddUser(&$error)
    {
      if ( $this->VerifyUserValues($userValues, $specID, $year, $error) )
      {
        $this->user = new cStudent(0, $this->db);        
        $userValues["password"] = substr( $userValues["ISIC"], 6, 4 );
        return $this->user->DBCreate( $userValues, $specID, $year, $error );
      }
      return false;
    }
    
    private function EditUser(&$error)
    {
      if ( $this->VerifyUserValues($userValues, $specID, $year, $error) )
        return $this->user->DBEdit($userValues, $specID, $year, $error);

      return false;
    }
    
    private function AddCourse($newCourseID, &$error)
    {
      if ( !$this->user )
        return false;
        
      $course = new cCourse( $newCourseID, $this->db );
      if ( $course && !$this->user->HasCourse($newCourseID, $error) )
        return $this->user->AddCourse($newCourseID, $error);
    }
    
    private function GetItemList( $userType, $order, $startIndex )
    {
      $userList = array();
      
      $firstChar = "";
      $numIndexes = 0; 
      $step = 100;
     
      $query = "SELECT u.id AS id FROM tUser as u, tStudents as t".
               " LEFT JOIN tSpecialization AS s ON s.id = t.id_specialization".
               " WHERE u.id=t.id AND (t.id_specialization=s.id OR t.id_specialization=0) AND t.bkp=0";
               
      if ( $order == "nameD" )
         $query .= " ORDER BY u.surname DESC, s.name, t.year"; 
      else if ( $order == "spec" )
         $query .= " ORDER BY s.name, t.year, u.surname"; 
      else if ( $order == "specD" )
         $query .= " ORDER BY s.name DESC, t.year, u.surname"; 
      else if ( $order == "year" )
         $query .= " ORDER BY t.year, s.name, u.surname"; 
      else if ( $order == "yearD" )
         $query .= " ORDER BY t.year DESC, s.name, u.surname"; 
      else
         $query .= " ORDER BY u.surname, s.name, t.year"; 
               
      $query .= " LIMIT ".$startIndex.", ".$step.";";


      $result = $this->db->QueryToArray($query);
      if ( $result != 0 )
      {
        foreach ( $result as $value )
        {
          $student = new cStudent($value["id"], $this->db);
          if ( $student->Loaded() )
          {
            $userList[$value["id"]] = $student->GetProperties();
            $spec = $student->GetSpecialization();
            if ( $spec )
              $userList[$value["id"]]["specialization"] = $spec->GetProperties(); 
          }            
        }
      }
      
      $query = "SELECT * FROM tStudents WHERE bkp=0";
      $result = $this->db->QueryToArray($query);
      $resultCount = count($result);
      $loopCount = (int)($resultCount/$step);
      if ( $resultCount % $step > 0 )
        $loopCount++;
      $this->smarty->assign("step", $step );
      $this->smarty->assign("order", $order );
      $this->smarty->assign("studentCount", $resultCount );
      $this->smarty->assign("loopCount", $loopCount );
      $this->smarty->assign("startIndex", $startIndex );
      $this->smarty->assign("userType", $userType );
      return $userList;      
    }
    
    protected function GetUserInfo(&$error)
    {
      if ( parent::GetUserInfo($error) )
      {
        $spec = $this->user->GetSpecialization();
        if ( $spec )
          $this->smarty->assign("specialization", $spec->GetProperties() );
        return true;
      }
      return false;
    }
    
    private function SearchResult(&$error)
    {
      $bCondEmpty = true;
      $c1 = "";
      $c2 = "";
      $c3 = "";
      $c4 = "";
       
      if ( !empty( $this->postParams["login"] ) )
      {
        $c1 .= "u.login LIKE '".$this->postParams["login"]."%'";
        $bCondEmpty = false;
      }
      if ( !empty($this->postParams["name"]) )
      {
        $c2 .= ($bCondEmpty ? "" : " AND")." u.name LIKE '".$this->postParams["name"]."%'";
        $bCondEmpty = false;
      } 
      if ( !empty($this->postParams["surname"]) )
      {
        $c3 .= ($bCondEmpty ? "" : " AND")." u.surname LIKE '".$this->postParams["surname"]."%'";
        $bCondEmpty = false;
      } 
      if ( !empty($this->postParams["isic"]) )
      {
        $c4 = ($bCondEmpty ? "" : " AND")." u.ISIC LIKE '".$this->postParams["isic"]."%'";
        $bCondEmpty = false;
      }
      if ( !empty($this->postParams["year"]) )
      {
        $c5 = ($bCondEmpty ? "" : " AND")." s.year=".$this->postParams["year"]."";
        $bCondEmpty = false;
      }
      if ( !empty($this->postParams["spec"]) )
      {
        $c6 = ($bCondEmpty ? "" : " AND")." s.id_specialization=".$this->postParams["spec"]."";
        $bCondEmpty = false;
      }
      if ( $bCondEmpty )
        return false;
        
      $query .= sprintf("SELECT u.id AS id FROM tUser AS u, tStudents AS s WHERE %s%s%s%s%s%s".
                        " AND s.id=u.id AND s.bkp=0;", $c1, $c2, $c3, $c4, $c5, $c6);                        
      
      $result = $this->db->QueryToArray($query);
      if ( $this->db->IsError() )
      {
        $error = $this->db->GetError();
        return false;
      }            
      
      $users = array();
      for ( $i = 0; $i < count( $result ); $i++ )
      {
        $user = new cStudent($result[$i]["id"], $this->db);
        if ( !empty( $error ) )
          return false;
          
        if ( $user->Loaded() )
        {
          $users[$i] = $user->GetProperties();
          $spec = $user->GetSpecialization();
          if ( $spec->IsLoaded() )
            $users[$i]["spec"] = $spec->GetProperties();
        }
      }
      $this->smarty->assign("userCount",count($users));      
      usort($users, "CmpUsers");
      $this->smarty->assign("users",  $users);
      return true;
    }
		
    function Process()
    {
      switch ( $this->action )
      {
        case "do_add":
          if ( $this->AddUser($this->error) )
          {
            if ( $this->GetUserInfo($this->error) )
            {
              $this->smarty->assign("actionInfo", "Užívateľ bol úspešne pridaný.");
              $this->bPageSet = true;
              break;
            }
            else if ( !empty($this->error) )
              return false;
          }
          else
          {
            if ( !empty( $this->error ) )
              return false;
            $this->action = "add";            
          }
        //fallthrough
        case "add":
          $specList = $this->GenerateSpecSelectList($this->postParams["spec"], $this->error);
          if ( !empty( $this->error ) )
            return false;
            
          $this->smarty->assign("specs", $specList);
          $this->smarty->assign("nPrefixV", $this->postParams["nPrefix"]);
          $this->smarty->assign("nameV", $this->postParams["name"]);
          $this->smarty->assign("surnameV", $this->postParams["surname"]);
          $this->smarty->assign("nSuffixV", $this->postParams["nSuffix"]);
          $this->smarty->assign("isicV", $this->postParams["isic"]);
          $this->smarty->assign("yearV", $this->postParams["year"]);
          $this->smarty->assign("formUrlSuffix", "&amp;action=do_add");
          $this->smarty->assign("buttonLabel","Pridať");
          $subMItem = $this->menuItem->GetItemByLabel("Pridať");
          $this->bPageSet = true;
        break;
        
        case "add_course":
          if ( isset($this->postParams["newCourse"]) && $this->AddCourse($this->postParams["newCourse"], $this->error) )
          {
            if ( empty($this->error) && $this->GetUserInfo($this->error) )
              $this->bPageSet = true;
          }
            
          if ( !empty($this->error) )
            return false;
        break;
        
        case "remove_course":
          if ( $this->RemoveCourse($this->error) )
          {
            if ( empty($this->error) && $this->GetUserInfo($this->error) )
              $this->bPageSet = true;
          }

          if ( !empty($this->error) )
            return false;
        break;
        
        case "do_edit":
          if ( !$this->user )
            break;
            
          if ( $this->EditUser($error) == false )
          {
            $this->action = "edit";
            $specList = $this->GenerateSpecSelectList($this->postParams["spec"], $this->error);
            if ( !empty( $this->error ) )
              return false;
              
            $this->smarty->assign("specs", $specList);
            $this->smarty->assign("nPrefixV", $this->postParams["nPrefix"]);
            $this->smarty->assign("nameV", $this->postParams["name"]);
            $this->smarty->assign("surnameV", $this->postParams["surname"]);
            $this->smarty->assign("nSuffixV", $this->postParams["nSuffix"]);
            $this->smarty->assign("isicV", $this->postParams["isic"]);
            $this->smarty->assign("yearV", $this->postParams["year"]);
            $this->smarty->assign("formUrlSuffix", "&action=do_edit&id=".$this->getParams["id"]);
            $this->smarty->assign("buttonLabel","Editovať");
            $this->smarty->assign("user", $this->user->GetProperties() );
          }
          else
          {
            $this->GetUserInfo($this->error);
            if ( !empty($this->error) )
              return false;
          }
          $this->bPageSet = true;
        break;
        
        case "edit":          
          if ( $this->user )
          {
            $userValues = $this->user->GetProperties();
            $specList = $this->GenerateSpecSelectList($userValues["specID"], $this->error);
            if ( !empty( $this->error ) )
              return false;
              
            $this->smarty->assign("specs", $specList);
            $this->smarty->assign("nPrefixV", $userValues["namePrefix"]);
            $this->smarty->assign("nameV", $userValues["name"]);
            $this->smarty->assign("surnameV", $userValues["surname"]);
            $this->smarty->assign("nSuffixV", $userValues["nameSuffix"]);
            $this->smarty->assign("isicV", $userValues["ISIC"]);
            $this->smarty->assign("yearV", $userValues["year"]);
            $this->smarty->assign("user", $this->user->GetProperties() );
            $this->smarty->assign("formUrlSuffix", "&action=do_edit&id=".$this->getParams["id"]);
            $this->smarty->assign("buttonLabel","Editovať");
            $this->bPageSet = true;
          }     
        break;
        
        case "do_delete":
          if ( !$this->user )
            break;
            
          if ( $this->user->DBDelete($error) )
            $this->smarty->assign("actionInfo", "Užívateľ bol vymazaný z databázy.");
          else
            $this->smarty->assign("actionInfo", "Chyba pri vymazávaní: ".$error);
            
          if( is_a($this->user, "cTeacher") )
            $this->getParams["show"] = "teacher";          
        break; 
        
        case "delete":
          if ( $this->user )
          {
            $this->smarty->assign("user", $this->user->GetProperties() );
            $this->bPageSet = true;          	
          }
        break;

        case "search_f":
          $subMItem = $this->menuItem->GetItemByLabel("Vyhľadať");
          $specList = $this->GenerateSpecSelectList(0, $this->error);
          if ( !empty( $this->error ) )
            return false;
              
          $this->smarty->assign("specs", $specList);
          $this->bPageSet = true;
        break;
        
        case "do_search":
          if ( $this->SearchResult($this->error) )
            $this->bPageSet = true;
          else if ( !empty( $this->error ) )
            return false;            
        break;
        
        case "change_p":
          if ( $this->user )
          {
            $this->smarty->assign("user", $this->user->GetProperties() );
            $this->bPageSet = true;
          }
        break;

        case "do_change_p":
          if ( $this->user )
          {
            if ( $this->ChangePassword($info, $this->error) && empty($this->error) )
              $this->smarty->assign("info", $info);
            else if ( !empty($this->error) )
              return false;
            else
              $this->smarty->assign("warning", $info);

            $this->smarty->assign("user", $this->user->GetProperties() );
            $this->bPageSet = true;
          }           
        break;
        
        case "info":
          if ( $this->GetUserInfo($this->error) )
            $this->bPageSet = true;
          else if ( !empty($this->error) )
            return false;          
        break;
      }
      
      if ( $this->bPageSet == false )
      {
          $subMItem = $this->menuItem->GetItemByLabel("Zoznam");
          $step = !empty( $this->getParams["step"] ) ? $this->getParams["step"] : 0;       
          $order = !empty( $this->getParams["order"] ) ? $this->getParams["order"] : "name";       
          $userList = $this->GetItemList( $this->getParams["show"], $order, $step);  
          $this->smarty->assign("users", $userList);           
      } 
      
      if ( $subMItem )
      {
        $this->menuItem->bSelected = false;
        $subMItem->bSelected = true;
      }
      return true;
    }
    
    function Draw()
    {
      //if page was not set, draw default page
      if ( $this->bPageSet == false )
      {
        $this->smarty->assign("content", "studentList.tpl");
        $this->smarty->assign( "title", "Zoznam študentov" );
      }
      else
      { 
        switch ( $this->action )
        {
          case "info":
          case "do_add":
          case "do_edit":
          case "add_course":
          case "remove_course":
            $this->smarty->assign("content", "studentDetails.tpl");
            $this->smarty->assign( "title", "Informácie o študentovi" );
          break;
          
          case "add":
            $this->smarty->assign( "title", "Pridávanie študenta" );
            $this->smarty->assign("content", "studentForm.tpl");
          break;
          
          case "edit":
            $this->smarty->assign( "title", "Editovanie študenta" );
            $this->smarty->assign("content", "studentForm.tpl");
          break;
          
          case "delete":
            $this->smarty->assign( "title", "Vymazanie študenta" );
            $this->smarty->assign("content", "studentDelete.tpl");
          break;
  
          case "search_f":
            $this->smarty->assign( "title", "Vyhľadávanie študentov" );
            $this->smarty->assign("content", "studentSearch.tpl");
          break;

          case "do_search":
            $this->smarty->assign( "title", "Výsledky vyhľadávania užívateľov" );
            $this->smarty->assign("content", "studentSearchResult.tpl");
          break;

          case "change_p":
          case "do_change_p":
            $this->smarty->assign( "title", "Zmena hesla študenta" );
            $this->smarty->assign("content", "studentChangeP.tpl");
          break;
        }
      }
      parent::Draw();
    }
	}
?>
