<?php
  
  class cUser
  {
    private $bIsLoaded;
    protected $db;
  
    protected $id;
    protected $namePrefix;
    protected $name;
    protected $surname;
    protected $nameSuffix;    
    protected $isic;
    protected $passPrefix;
    protected $login;
    
    function __construct( $id, $db )
    {
      $this->bIsLoaded = false;
      $this->db = $db;
      $this->id = $id;
      
      if ( $this->id > 0 )
      {
        $query = "SELECT * FROM tUser WHERE id=".$this->id.";";
        $result = $this->db->QueryToRow($query);
        
        if ( $result != 0 )
        {
          $this->namePrefix = $result["namePrefix"];
          $this->name = $result["name"];
          $this->surname = $result["surname"];
          $this->nameSuffix = $result["nameSuffix"];
          $this->isic = $result["ISIC"];
          $this->passPrefix = $result["passPrefix"];
          $this->login = $result["login"];
          $this->bIsLoaded = true;
        }
      }      
    }
    
    function Loaded()
    {
      return $this->bIsLoaded;
    }
    
    function LoadByISIC( $isic, &$error )
    {
      $this->id = 0;
      $this->namePrefix = "";
      $this->name = "";
      $this->surname = "";
      $this->nameSuffix = "";
      $this->isic = "";
      $this->passPrefix = "";
      $this->login = "";
      $this->bIsLoaded = false;

      $query = "SELECT * FROM tUser WHERE ISIC=".$isic.";";
      $result = $this->db->QueryToRow($query);
      if ( $this->db->IsError() )
      {
        $error = $this->db->GetError();
        return false;
      }
           
      if ( $result != 0 )
      {
        $this->id = $result["id"];
        $this->namePrefix = $result["namePrefix"];
        $this->name = $result["name"];
        $this->surname = $result["surname"];
        $this->nameSuffix = $result["nameSuffix"];
        $this->isic = $result["ISIC"];
        $this->passPrefix = $result["passPrefix"];
        $this->login = $result["login"];
        $this->bIsLoaded = true;
      }
      return $this->bIsLoaded;
    }
    
    //returns error message or "" if no errors
    protected function DBCreate( $values, &$error )
    {
      $passPrefix = $this->GenerateRandomString(6);
      $password = md5( $passPrefix.$values["password"] );
      $login = $this->CreateLogin( explode(" ",$values["surname"]." ".$values["name"] ) );
      
      $query = "SELECT id FROM tUser WHERE login LIKE '".$login."%';";
      $result = $this->db->QueryToArray($query);
      if ( $this->db->IsError() )
      {
        $error = $this->db->GetError();
        return false;
      }
      $loginCount = count($result);
      if ( $loginCount > 0 )
        $login .= ($loginCount+1);
        
      $query = "INSERT INTO tUser VALUES (0, '".$values["namePrefix"]."', '".$values["name"].
              "', '".$values["surname"]."', '".$values["nameSuffix"]."','".$login.
              "', '".$password."', '".$passPrefix."', '".$values["ISIC"]."', 1);";
              
      $result = $this->db->Query($query);
      if ( $result == false )
      {
        if ( $this->db->IsError() )
          $error = $this->db->GetError();
        else
          $error = "Chyba pri vytváraní užívateľa!";
        return false;
      }
      
      $this->id = $this->db->InsertID();
      $this->namePrefix = $values["namePrefix"];
      $this->name = $values["name"];
      $this->surname = $values["surname"];
      $this->nameSuffix = $values["nameSuffix"];
      $this->isic = $values["ISIC"];
      $this->login = $login;
      $error = "";
      return true;        
    }
    
    //$values - associative array with fields that have to be edited
    protected function DBEdit( $values, &$error )
    {
      $i = 0;
        
      $query = "UPDATE tUser SET ";
      
      foreach ( $values as $key => $value )
      {
        $query .= $key."='".$value."'";
        if ( ++$i < count($values) )
          $query .= ", ";
      }        
      $query .= " WHERE id=".$this->id.";";
      
      $result = $this->db->Query($query);
      
      if ( $result == false )
      {
        if ( $this->db->IsError() )
          $error = $this->db->GetError();
        else
          $error = "Chyba pri editovaní užívateľa!";
        return false;       
      }

      $this->namePrefix = $values["namePrefix"];      
      $this->name = $values["name"];      
      $this->surname = $values["surname"];      
      $this->nameSuffix = $values["nameSuffix"];      
      $this->isic = $values["ISIC"];      
      $error = "";
      return true;
    }
    
    protected function DBDelete( &$error )
    {
      $query = "DELETE FROM tUser WHERE id=".$this->id.";";
      $result = $this->db->Query($query);
      
      if ( !$result )
      {
        if ( $this->db->IsError() )
          $error = $this->db->GetError();
        else
          $error = "Chyba pri vymazávaní užívateľa!";
        return false;       
      }
      $this->bIsLoaded = false;
      $this->id = 0;
      $this->namePrefix = "";
      $this->name = "";
      $this->surname = "";
      $this->nameSuffix = "";
      $this->isic = "";
      $error = "";
      return true;
    }
    
    function GetProperties()
    {
      $result = array();
      $result["id"] = $this->id;
      $result["namePrefix"] = $this->namePrefix;
      $result["name"] = $this->name;
      $result["surname"] = $this->surname;
      $result["nameSuffix"] = $this->nameSuffix;
      $result["ISIC"] = $this->isic;
      $result["login"] = $this->login;
      return $result;
    }
    
    function SetProperties( $id, $nPrefix, $name, $surname, $nSuffix, $ISIC, $login )
    {
      $this->id = $id;
      $this->namePrefix = $nPrefix;
      $this->name = $name;
      $this->surname = $surname;
      $this->nameSuffix = $nameSuffix;
      $this->isic = $ISIC;
      $this->login = $login;
    }
    
    function GetID()
    {
      return $this->id;
    }
    
    function GetPassPrefix()
    {
      return $this->passPrefix;
    }
    
    function GetISIC()
    {
      return $this->isic;
    }

    function GetCourses(&$error)
    {
      $courses = array();
      
      $query = "SELECT id_course FROM tCourseToUser WHERE id_user=".$this->id.";";
      $result = $this->db->QueryToArray($query);
      if ( $this->db->IsError() )
      {
        $error = $this->db->GetError();
        return NULL;
      }            
      
      for ( $i = 0; $i < count($result); $i++ )
      	$courses[$i] = new cCourse( $result[$i]["id_course"], $this->db );
      	
      return $courses;
    }
    
    function HasCourse($id, &$error)
    {
      $query = "SELECT * FROM tCourseToUser WHERE id_user=".$this->id." AND id_course=".$id.";";
      $result = $this->db->QueryToArray($query);

      $error = $this->db->GetError();
      return count($result) > 0 && empty( $error );
    }
    
    function AddCourse($id, &$error)
    {
      $query = "INSERT INTO tCourseToUser VALUES (".$id.", ".$this->id.");";
      $result = $this->db->Query($query);
      $error = $this->db->GetError();
      
      return $result;
    }
    
    function RemoveCourse($id, &$error)
    {
      if ( $this->id > 0 )
      {
        $query = "DELETE FROM tCourseToUser WHERE id_course=".$id." AND id_user=".$this->id.";";
        $result = $this->db->Query($query);
      
        $error = $this->db->GetError();
      }
      return $result;
    }
    
		private function GenerateRandomString( $length )
		{
      $values = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                 			'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                 			'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                   		'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                   		'1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
          
      for($i = 0; $i <= $length-1; $i++)
      {
        $r = rand(0, count($values)-1);
        $key[$i] = $values[$r];
      }      
      return join("", $key);
		}
    
    private function GetSimpleChar( $string )
    {
      if ( ord( $string[0] ) < 0x80 )
        return $string;
        
      $substChar = array( 195 => array( 161 => "a", 
                                        164 => "a",
                                        169 => "e",
                                        173 => "i",
                                        179 => "o",
                                        180 => "o",
                                        186 => "u",
                                        189 => "y" ),
                          196 => array( 141 => "c",
                                        143 => "d",
                                        155 => "e",
                                        186 => "l",
                                        190 => "l"),
                          197 => array( 136 => "n",
                                        149 => "r",
                                        153 => "r",
                                        161 => "s",
                                        165 => "t",
                                        190 => "z") );
      
      return $substChar[ord($string[0])][ord($string[1])];
    }

    private function CreateLogin( $names )
    {
      $result = "";
      $totalLen = 0;
      
      for ( $i = 0; $i < count($names); $i++ )
      {
        $nameLen = mb_strlen($names[$i]);
        $lowName = mb_strtolower($names[$i]);
  
        for ( $j = 0; $j < $nameLen; $j++ )
        {
          $simpleChar = $this->GetSimpleChar( mb_substr($lowName, $j, 1) );
          $result[$j+$totalLen] = ($j == 0 ? strtoupper($simpleChar) : $simpleChar);
        }
        $totalLen += $nameLen;
      }    
      return join("",$result);     
    }     
  }
  
  class cStudent extends cUser
  {
    private $specID;
    private $year;
    
    function __construct( $id, $db )
    {
      $query = "SELECT id FROM tStudents WHERE id=".$id." AND bkp=0;";
      $result = $db->QueryToRow($query);
      if ( $result == 0 )
        $id = 0;
        
      parent::__construct( $id, $db );
      
      if ( $id > 0 )
      {
        $query = "SELECT * FROM tStudents WHERE id=".$id.";";
        $result = $this->db->QueryToRow($query);
        if ( $result )
        {
          $this->specID = $result["id_specialization"];
          $this->year = $result["year"];
        } 
        else
        {
          $this->specID = 0;
          $this->year = 0;
        }
      }
    }
    
    function LoadByISIC($isic, &$error)
    {
      if ( parent::LoadByISIC($isic, $error) )
      {
        $query = "SELECT id FROM tStudents WHERE id=".$this->id." AND bkp=0;";
        $result = $this->db->QueryToRow($query);
        if ( $result != 0 )
          return true;
          
        if ( $this->db->IsError() )
          $error = $this->db->GetError();
      }
      return false;
    }
    
    function DBCreate( $values, $specID, $year, &$error )
    {
      if ( parent::DBCreate( $values, $error ) )
      {
        $query = "INSERT INTO tStudents VALUES (".$this->id.",".$specID.",".$year.",0);";
        
        $result = $this->db->Query($query);
        if ( $result == false )
        {
          if ( $this->db->IsError() )
            $error = $this->db->GetError();
          else
            $error = "Chyba pri editovaní študenta!";
            
          parent::DBDelete($error2);
          return false;
        }
        $this->specID = $specID;
        $this->year = $year;
        return true; 
      }
      else 
        return false;
    }
    
    function DBEdit( $values, $specID, $year, &$error )
    {
      $query = "UPDATE tStudents SET id_specialization=".$specID.", year=".$year." WHERE id=".$this->id.";";
      $result = $this->db->Query($query);
      if ( $result )
      {
        $this->specID = $specID;
        $this->year = $year;      	
        return parent::DBEdit( $values, $error );
      }
      $this->specID = 0;
      $this->year = 0;
      $error = $this->db->GetError();
      return false;      	           
    }
    
    function DBDelete( &$error )
    {
      $this->specID = 0;
      $this->year = 0;
      
      $id = $this->id;
      if ( parent::DBDelete( $error ) )
      {
        $query = "DELETE FROM tStudents WHERE id=".$id.";";
        $result = $this->db->Query($query);
      
        if ( $result )
        {
          $query = "DELETE FROM tCourseToUser WHERE id_user=".$id.";";
          $result = $this->db->Query($query);
        }
        
        if ( !$result )
        {
          if ( $this->db->IsError() )
            $error = $this->db->GetError();
          else
            $error = "Chyba pri vymazávaní študenta!";
          return false;
        }
        return true;
     }
     else
       return false;
    }
    
    function GetProperties()
    {
      $result = parent::GetProperties();
      $result["type"] = "student";
      $result["specID"] = $this->specID;
      $result["year"] = $this->year;
      return $result;
    }
    
    function GetSpecialization()
    {
      $spec = new cSpecialization( $this->specID, $this->db );
      if ( $spec->IsLoaded() )
        return $spec;
        
      return NULL;
    }
  }

  class cTeacher extends cUser
  {
    function __construct( $id, $db )
    {
      parent::__construct( $id, $db );
    }
    
    function LoadByISIC($isic, &$error)
    {
      if ( parent::LoadByISIC($isic, $error) )
      {
        $query = "SELECT id FROM tTeachers WHERE id=".$this->id.";";
        $result = $this->db->QueryToRow($query);
        if ( $result != 0 )
          return true;
          
        if ( $this->db->IsError() )
          $error = $this->db->GetError();
      }
      return false;
    }

    function DBCreate( $values, &$error )
    {
      if ( parent::DBCreate( $values, $error ) )
      {
        $query = "INSERT INTO tTeachers VALUES (".$this->id.");";
        
        $result = $this->db->Query($query);
        if ( $result == false )
        {
          if ( $this->db->IsError() )
            $error = $this->db->GetError();
          else
            $error = "Chyba pri editovaní učiteľa!";
            
          parent::DBDelete($error);
          return false;
        }
        return true; 
      }
      else 
        return false;
    }
    
    function DBEdit( $values, &$error )
    {
      return parent::DBEdit( $values, $error );
    }
    
    function DBDelete( &$error )
    {
      $id = $this->id;
      if ( parent::DBDelete( $error ) )
      {
        $query = "DELETE FROM tTeachers WHERE id=".$id.";";
        $result = $this->db->Query($query);
        
        if ( $result )
        {
          $query = "UPDATE tCourseToUser SET id_user=0 WHERE id_user=".$id.";";
          $result = $this->db->Query($query);
          if ( $result )
          {
            $query = "UPDATE tSpecialization SET id_garant=0 WHERE id_garant=".$id.";";
            $result = $this->db->Query($query);
          }
        }
        
        if ( !$result )
        {
          if ( $this->db->IsError() )
            $error = $this->db->GetError();
          else
            $error = "Chyba pri vymazávaní učiteľa!";
          return false;
        }
        return true;
     }
      else
        return false;
    }

    function GetProperties()
    {
      $result = parent::GetProperties();
      $result["type"] = "teacher";
      return $result;
    }
  }
?>
