<?php
	class cCoursePage extends cAdminPage
	{  	 
    private $menuItem;
    private $course;
    
    function __construct( $smarty, $db, $action, $post, $get  )
    {
      parent::__construct( $smarty, $db, $action, $post, $get  );
	  		
      $this->menuItem = $this->menu->GetItemByLabel("Predmety");
      $this->menuItem->bSelected = true;
      $this->menuItem->bExpanded = true;

      if ( $this->getParams["id"] > 0 )
        $this->course = new cCourse($this->getParams["id"], $this->db);
    }
    
    private function VerifyCourseValues(&$courseValues, &$error)
    {
      $error = "";
      //check if name is filled
      if ( empty( $this->postParams["name"] ) )
      {
        $this->smarty->assign("error", "Musíte zadať názov predmetu!");
      }
      else 
      {
        $query = "SELECT * FROM tCourse WHERE name='".$this->postParams["name"]."'";
        if ( $this->course )
          $query .= " AND id<>".$this->course->GetID().";";
        else
          $query .= ";";
        $result = $this->db->QueryToRow($query);
        $error = $this->db->GetError();

        if ( $result == 0 && empty( $error ) )
        {
          $courseValues["course"]["name"] = $this->postParams["name"];
          $courseValues["course"]["code"] = $this->postParams["code"];
          $courseValues["course"]["description"] = $this->postParams["description"];
          $courseValues["users"][0] = $this->postParams["teacher"];
          return true;
        }
        else if ( $result != 0 )
          $this->smarty->assign("error", "Názov predmetu už existuje!" );
      }
      return false;
    }
    
    function AddCourse(&$error)
    {
      if ( $this->VerifyCourseValues($values, $error) )
      {
        $this->course = new cCourse(0, $this->db);
        return $this->course->DBCreate($values, $this->error);
      }
      return false;
    }
    
    function EditCourse(&$error)
    {
      if ( $this->VerifyCourseValues($values, $error) )
      {
        if ( $this->course->DBEdit($values, $error) )
          return (($this->course->DBChangeTeacher($values["users"][0], $error) != NULL) || ($values["users"][0] == 0));
      }
      return false;
    }    
    
    function GetCourseList(&$error, $order)
    {
      $courseList = array();
      
      $query = "SELECT c.id as id FROM tCourse as c, tCourseToUser as cu LEFT JOIN tTeachers as t ON cu.id_user=t.id, tUser as u".
               " WHERE c.id=cu.id_course AND (cu.id_user=t.id OR cu.id_user=0) AND (t.id=u.id OR cu.id_user=0)";
      
      if ( $order == "nameD" )
         $query .= " ORDER BY c.name DESC, c.code;"; 
      else if ( $order == "code" )
         $query .= " ORDER BY c.code, c.name;"; 
      else if ( $order == "codeD" )
         $query .= " ORDER BY c.code DESC, c.name;"; 
      else if ( $order == "teacher" )
         $query .= " ORDER BY u.surname, c.name, c.code;"; 
      else if ( $order == "teacherD" )
         $query .= " ORDER BY u.surname DESC, c.name, c.code;"; 
      else
         $query .= " ORDER BY c.name, c.code;"; 

      $result = $this->db->QueryToArray($query);
      if ( $this->db->IsError() )
      {
        $error = $this->db->GetError();
        return NULL;
      }
      
      foreach ( $result as $value )
      {
        $course = new cCourse($value["id"], $this->db);
        if ( $course->IsLoaded() )
        {
          $courseList[$value["id"]] = $course->GetProperties();
          $teacher = $course->GetTeacher($this->error);
          if ( $teacher )
            $courseList[$value["id"]]["teacher"] = $teacher->GetProperties();
          else if ( !empty($this->error) )
            return NULL;
        }
      }
      $this->smarty->assign("order", $order);
      $this->smarty->assign("courseCount", count($courseList));
      return $courseList;            
    }
    
    function GetCourseInfo(&$error)
    {
      $this->smarty->assign("course", $this->course->GetProperties() );
      $teacher = $this->course->GetTeacher($error);            
      if ( empty($error) )
        $students = $this->course->GetStudents($error);
      
      if ( !empty($error) )
        return false;
      
      if ( $teacher )      
        $this->smarty->assign("teacher", $teacher->GetProperties() );

      if ( count($students) > 0 )
      {
        for ( $i = 0; $i < count($students); $i++ )
          $studentValues[$i] = $students[$i]->GetProperties();
          
        usort( $studentValues, "cmpUsers" );
        $this->smarty->assign("students", $studentValues);
      }    
      return true;
    }
    
    private function SearchResult(&$error)
    {
      $bCondEmpty = true;
      $c1 = "";
      $query = "";
      
      if ( !empty( $this->postParams["name"] ) )
      {
        $c1 = " c.name LIKE '".$this->postParams["name"]."%'";
        $bCondEmpty = false;
      }
      if ( !empty( $this->postParams["code"] ) )
      {
        $c2 = ($bCondEmpty ? "" : " AND")." c.code LIKE '".$this->postParams["code"]."%'";
        $bCondEmpty = false;
      }
      
      if ( $this->postParams["teacher"] > 0 )
      {
        $c3 = ($bCondEmpty ? "" : " AND")." c.id=cu.id_course AND cu.id_user=".$this->postParams["teacher"];
        $query = sprintf("SELECT id FROM tCourse AS c, tCourseToUser AS cu WHERE%s%s%s;", $c1, $c2, $c3);
      }
      else if ( !$bCondEmpty )
      {
        $query = sprintf("SELECT id FROM tCourse AS c WHERE%s%s;", $c1, $c2);
      }
      else
        return false;      
        
      $result = $this->db->QueryToArray($query);
      if ( $this->db->IsError() )
      {
        $error = $this->db->GetError();
        return false;
      }            
      
      $courses = array();
      $i = 0;
      foreach ( $result as $item )
      {
        $course = new cCourse($item["id"], $this->db);                
        if ( $course->IsLoaded() )
        {
          $courses[$i] = $course->GetProperties();
          $teacher = $course->GetTeacher($error);
          if ( $teacher )
            $courses[$i]["teacher"] = $teacher->GetProperties();
          else if ( !empty( $error ) )
            return $error; 
          $i++;
        }
      }
      $this->smarty->assign("courseCount", $i);      
      usort($courses, "CmpCourses");
      $this->smarty->assign("courses",  $courses);
      return true;
    }
		
    private function RemoveStudents(&$error)
    {
      if ( !$this->course )
        return false;
        
      foreach ( $this->postParams as $key => $value )
      {
        if ( $key != "remove" )
        {  
          if ( $this->GetUserType($key, $this->error) == "student" )
          {
            $student = new cStudent($key, $this->db);
            if ( $student )       
              $student->RemoveCourse($this->course->GetID(), $error);
          }
          if ( $error )
            return false;
        }        
      }
      return true;
    }
			
    function Process()
    {
      switch ( $this->action )
      {
        case "info":
          if ( $this->course )
          {  
            if ( $this->GetCourseInfo($this->error) )
              $this->bPageSet = true;
            else if ( !empty($this->error) )
              return false;
          }
        break;     
        
        case "do_add":
          if ( $this->AddCourse($this->error) && $this->GetCourseInfo($this->error) )
          {
            $this->smarty->assign("actionInfo", "Predmet bol úspešne pridaný.");
            $this->bPageSet = true;
            break;
          }
          else if ( !empty( $this->error ) )
            return false;
          $this->action = "add";
        //fallthrough          
        case "add":
          $teacherList = $this->GenerateTeacherSelectList($this->postParams["teacher"], $this->error);
          if ( !empty( $this->error ) )
            return false;
            
          $this->smarty->assign("teachers", $teacherList);
          $this->smarty->assign("nameV", $this->postParams["name"]);
          $this->smarty->assign("codeV", $this->postParams["code"]);
          $this->smarty->assign("descriptionV", $this->postParams["description"]);
          $this->smarty->assign("formUrlSuffix", "&amp;action=do_add");
          $this->smarty->assign("pageTitle","Pridať predmet");
          $this->smarty->assign("buttonLabel","Pridať");
          $subMItem = $this->menuItem->GetItemByLabel("Pridať");
          $this->bPageSet = true;
        break;
        
        case "edit":
          if ( $this->course )
          {
            $teacher = $this->course->GetTeacher( $this->error );
            if ( !empty( $this->error ) )
              return false;
            
            $id = $teacher ? $teacher->GetID() : 0;              
            $teacherList = $this->GenerateTeacherSelectList($id, $this->error);
            if ( !empty( $this->error ) )
              return false;

            $courseValues = $this->course->GetProperties();
            $this->smarty->assign("teachers", $teacherList);
            $this->smarty->assign("nameV", $courseValues["name"]);
            $this->smarty->assign("codeV", $courseValues["code"]);
            $this->smarty->assign("descriptionV", $courseValues["description"]);
            $this->smarty->assign("formUrlSuffix", "&amp;action=do_edit&amp;id=".$this->getParams["id"]);
            $this->smarty->assign("pageTitle","Editovanie predmetu");
            $this->smarty->assign("buttonLabel","Editovať");
            $this->smarty->assign("course", $this->course->GetProperties());
            $this->bPageSet = true;
          }     
        break;
        
        case "do_edit":
          if ( $this->course )
          {            
            if ( !$this->EditCourse($this->error) )
            {
              if ( !empty( $this->error ) )
                return false;
                
              $this->action = "edit";            
              $teacherList = $this->GenerateTeacherSelectList($this->postParams["teacher"], $this->error);
              if ( !empty( $this->error ) )
                return false;
  
              $this->smarty->assign("teachers", $teacherList);
              $this->smarty->assign("nameV", $this->postParams["name"]);
              $this->smarty->assign("codeV", $this->postParams["code"]);
              $this->smarty->assign("descriptionV", $this->postParams["description"]);
              $this->smarty->assign("formUrlSuffix", "&amp;action=do_edit&amp;id=".$this->getParams["id"]);
              $this->smarty->assign("pageTitle","Editovanie užívateľa");
              $this->smarty->assign("buttonLabel","Editovať");
              $this->smarty->assign("course", $this->course->GetProperties());
              $this->bPageSet = true;
            }
            else
            {            
              if ( $this->GetCourseInfo($this->error) )
                $this->bPageSet = true;
              else if ( !empty($this->error) )
                return false;
            }
          }
        break;   

        case "search_f":
          $teacherList = $this->GenerateTeacherSelectList(0, $this->error);
          if ( !empty( $this->error ) )
            return false;
            
          $subMItem = $this->menuItem->GetItemByLabel("Vyhľadať");
          $this->smarty->assign("teachers", $teacherList);
          $this->bPageSet = true;
        break;  
        
        case "do_search":
          if ( $this->SearchResult($this->error) )
            $this->bPageSet = true;
          else if ( !empty( $this->error ) )
            return false;                      
        break;
        
        case "remove_students":
          if ( $this->RemoveStudents($this->error) )
          {
            if ( empty($this->error) && $this->GetCourseInfo($this->error) )
              $this->bPageSet = true;
          }
          if ( !empty($this->error) )
            return false;
        break;
        
        case "do_delete":
          if ( $this->course )
          {
            if ( $this->course->DBDelete($this->error) )
              $this->smarty->assign("actionInfo", "Predmet bol vymazaný z databázy.");
            if ( !empty($this->error) )
              return false;
          }            
        break;
        
        case "delete":
          if ( $this->course )
          {
            $this->smarty->assign("course", $this->course->GetProperties() );
            $this->bPageSet = true;          	
          }
        break;
      }

      if ( !$this->bPageSet )
      {
        $subMItem = $this->menuItem->GetItemByLabel("Zoznam");
        $order = empty($this->getParams["order"]) ? "name" : $this->getParams["order"];        
        $courseList = $this->GetCourseList($this->error, $order);  
        if ( !empty( $this->error ) )
          return false;
        $this->smarty->assign("courses", $courseList);
      }    
      
      if ( $subMItem )
      {
        $this->menuItem->bSelected = false;
        $subMItem->bSelected = true;
      }
      return true;
    }
    
    function Draw()
    {
      if ( !$this->bPageSet )
      {
        $this->smarty->assign("content", "coursesList.tpl");
        $this->smarty->assign("title", "Zoznam predmetov" );
      }
      else
      {
        switch ( $this->action )
        {
          case "do_edit":
          case "do_add":
          case "remove_students":
          case "info":
            $this->smarty->assign("content", "courseDetails.tpl");
            $this->smarty->assign("title", "Informácie o predmete" );
          break;
          
          case "add":
            $this->smarty->assign("title", "Pridávanie predmetu" );
            $this->smarty->assign("content", "courseForm.tpl");
          break;

          case "edit":
            $this->smarty->assign("title", "Editovanie predmetu" );
            $this->smarty->assign("content", "courseForm.tpl");
          break;
          
          case "delete":
            $this->smarty->assign("title", "Vymazanie predmetu" );
            $this->smarty->assign("content", "courseDelete.tpl");
          break;
          
          case "search_f":
            $this->smarty->assign("title", "Vyhľadávanie predmetov" );
            $this->smarty->assign("content", "coursesSearch.tpl");
          break;
          
          case "do_search":
            $this->smarty->assign("title", "Výsledky vyhľadávania predmetov" );
            $this->smarty->assign("content", "coursesSearchResult.tpl");
          break;
        }
      }
      parent::Draw();
    }
	}
?>
