<?php
	class cTestGeneratingPage extends cTeacherPage
	{
	
    function SortDomainsAndSetLeftPadding(&$result, &$domains, $id_parent, $left)
    {
      $domains[$id_parent]["left"]=$left;
      array_push($result,$domains[$id_parent]);
      foreach ($domains[$id_parent]["subdomains"] as $key=>$value)
      {
        $this->SortDomainsAndSetLeftPadding($result,$domains,$value,$left+20);
      }
    }
    
    function SetLevelToDomain (&$domains, $id)
    {
      $level=($domains[$domains[$id]["id_parent"]]!=0 ? $domains[$domains[$id]["id_parent"]]["level"]+1 : 0);
      $domains[$id]["level"]=$level;
      foreach ($domains[$id]["subdomains"] as $value)
      {
        $this->SetLevelToDomain($domains,$value);
      }
    }
    
    function GetDataForGenerating(&$domains, &$questionCount)
    {
      $query = "SELECT tC.questionCount FROM tCourse AS tC ".
               "WHERE id=".$this->getParams["courseID"].";";
      $result = $this->db->QueryToRow($query);
      $questionCount=$result["questionCount"];
      
      $query = "SELECT tD.id AS id_domain, tD.id_parent, tQ.id AS id_question, ".
               "tAS.id AS id_answerSet ".
               "FROM tDomain AS tD, tQuestion AS tQ, tAnswerSet As tAS ".
               "WHERE tD.id_course=".$this->getParams["courseID"]." AND NOT tD.obsolete AND ".
               "tQ.id_domain=tD.id AND NOT tQ.obsolete AND tAS.id_question=tQ.id AND ".
               "NOT tAS.obsolete;";
      $result = $this->db->QueryToArray($query);
      if ($result!=0)
      {
        //vytvor zakladnu strukturu
        $domains=array();
        $domains[0]["id"]=0;
        $domains[0]["level"]=-1;
        $domains[0]["id_parent"]=-1;
        $domains[0]["subdomains"]=array();
        $domains[0]["questions"]=array();
        $domains[0]["min"]=$questionCount;
        $domains[0]["max"]=$questionCount;
        foreach ($result as $key=>$value)
        {
          if (!isset($domains[$value["id_domain"]]))
          {
            $domains[$value["id_domain"]]["id"]=$value["id_domain"];
            $domains[$value["id_domain"]]["id_parent"]=$value["id_parent"];
            $domains[$value["id_domain"]]["level"]=($value["id_parent"]==0 ? 0 : -1);
            $domains[$value["id_domain"]]["subdomains"]=array();
            $domains[$value["id_domain"]]["questions"]=array();
            $domains[$value["id_domain"]]["min"]=0;
            $domains[$value["id_domain"]]["max"]=0;
          }
          if (!isset($domains[$value["id_domain"]]["questions"][$value["id_question"]]))
          {
            $domains[$value["id_domain"]]["questions"][$value["id_question"]]["id"]=$value["id_question"];
            $domains[$value["id_domain"]]["questions"][$value["id_question"]]["id_domain"]=$value["id_domain"];
            $domains[$value["id_domain"]]["questions"][$value["id_question"]]["answerSets"]=array();
          }
          $domains[$value["id_domain"]]["questions"][$value["id_question"]]["answerSets"][$value["id_answerSet"]]=$value["id_answerSet"];
        }
        //dopln udaje min a max pre domeny
        $query = "SELECT tCTD.id_domain, tD.id_parent, tCTD.min, tCTD.max ".
                 "FROM tCourseToDomain As tCTD, tDomain AS tD ".
                 "WHERE tCTD.id_domain=tD.id AND tCTD.id_course=".$this->getParams["courseID"].";";
        $result = $this->db->QueryToArray($query);
        if ($result!=0)
        {
          foreach ($result as $key=>$value)
          {
            if (!isset($domains[$value["id_domain"]]))
            {
              $domains[$value["id_domain"]]["id"]=$value["id_domain"];
              $domains[$value["id_domain"]]["id_parent"]=$value["id_parent"];
              $domains[$value["id_domain"]]["subdomains"]=array();
              $domains[$value["id_domain"]]["questions"]=array();
            }
            $domains[$value["id_domain"]]["min"]=$value["min"];
            $domains[$value["id_domain"]]["max"]=$value["max"];
          }
        }
        //dopln kazdej domene zoznam jej poddomen
        foreach ($domains as $key=>$value)
        {
          if ($value["id"]!=0)
          {
            $domains[$value["id_parent"]]["subdomains"][$value["id"]]=$value["id"];
          }
        }
        //dopln kazdej domene zoznam otazok jej poddomen pokial sa moze z danej poddomeny vybrat aspon 1 otazka
        foreach ($domains as $key=>$value)
        {
          if ($value["max"]>0)
          {
            $id_parent=$value["id_parent"];
            while (($id_parent!=-1) && ($domains[$id_parent]["max"]>0))
            {
              foreach ($value["questions"] as $key2=>$value2)
              {
                $domains[$id_parent]["questions"][$key2]["id"]=$value2["id"];
                $domains[$id_parent]["questions"][$key2]["id_domain"]=$value2["id_domain"];
                $domains[$id_parent]["questions"][$key2]["answerSets"]=$value2["answerSets"];
              }
              $id_parent=$domains[$id_parent]["id_parent"];
            }
          }
        }
        //nastav hlbku kazdej domeny
        foreach ($domains as $key=>$value)
        {
          if ($value["level"]==0)
          {
            $this->SetLevelToDomain($domains, $value["id"]);
          }
        }
      }
    }
    
    function GenerateTest($domains, $questionCount)
    {
      //zistime maximalnu hlbku strukturovanych domen a ku kazdej domene si zaznacime, ze pocet 
      //vybratych testovych otazok je nulovy
      $maxLevel=-1;
      foreach ($domains as $key=>$value)
      {
        $domains[$key]["selectedQuestions"]=0;
        if ($value["level"]>$maxLevel)
        {
          $maxLevel=$value["level"];
        }
      }
      
      $test=array();
      srand ((float) microtime() * 10000000);
      //z kazdej domeny vybereme do testu tolko otazok, kolko je nastavenych ako minimum pre danu domenu
      //vyberame zostupne podla urovne domeny
      for ($level=$maxLevel;$level>=-1;$level--)
      {
        foreach ($domains as $key=>$value)
        {
          if ($value["level"]==$level)
          {
            for ($i=$value["selectedQuestions"]+1;$i<=$domains[$key]["min"];$i++)
            {
              if (count($test)>$questionCount)
              {
                return NULL;
              }
              if (count($domains[$key]["questions"])==0)
              {
                return NULL;
              }
              $question=$domains[$key]["questions"][array_rand($domains[$key]["questions"])];
              $id_question=$question["id"];
              $id_domain=$question["id_domain"];
              $id_answerSet=$question["answerSets"][array_rand($question["answerSets"])];
              array_push($test, array("id_domain"=>$id_domain, "id_question"=>$id_question, "id_answerSet"=>$id_answerSet));
              $deleteQuestions=array($question);
              while ($id_domain!=-1)
              {
                $domains[$id_domain]["selectedQuestions"]++;
                if ($domains[$id_domain]["selectedQuestions"]==$domains[$id_domain]["max"])
                {
                  $deleteQuestions=$domains[$id_domain]["questions"];
                }
                foreach ($deleteQuestions as $delKey=>$delValue)
                {
                  unset ($domains[$id_domain]["questions"][$delValue["id"]]);
                }
                if ($domains[$id_domain]["selectedQuestions"]>$domains[$id_domain]["max"])
                {
                  return NULL;
                }
                $id_domain=$domains[$id_domain]["id_parent"];
              }
            }
          }
        }
      }
      return $test;
    }
    
    function MakePageHeader($test, $courseName, $pdf, $font, $leftPadding)
    {
      pdf_setfont($pdf, $font, 20);
      pdf_show_xy($pdf, mb_convert_encoding("Predmet: ".$courseName, "iso-8859-2", "UTF-8"), $leftPadding, 770);
      pdf_setfont($pdf, $font, 14);
      pdf_show_xy($pdf, mb_convert_encoding("ID testu: ".$test["id"], "iso-8859-2", "UTF-8"), $leftPadding, 754);
    }
    
    function PrintText($text, $pdf, $len, $fontSize, $posX, $posY, $padding)
    {
      $text=wordwrap(mb_convert_encoding($text, "iso-8859-2", "UTF-8"), $len, "\n", 1);
      $posY-=$fontSize;
      $move=0;
      while ($text!=="")
      {
        $i=strpos($text, "\n");
        if ($i!==false)
        {
          pdf_show_xy($pdf, substr($text, 0, $i), $posX+$move, $posY);
          $text=substr($text, $i+1, strlen($text)-$i-1);
        }
        else
        {
          pdf_show_xy($pdf, $text, $posX+$move, $posY);
          $text="";
        }
        $posY-=$fontSize;
        if ($move==0) $move=$padding;
      }
    }
    
    function GetTextHeight($text, $len, $fontSize)
    {
      $text=wordwrap($text, $len, "\n", 1);
      return (substr_count($text,"\n")+1)*$fontSize;
    }
    
    function GetQuestionHeight($question, $questionFontSize, $answerFontSize)
    {
      $question["question"]=wordwrap("mmmm".$question["question"],27, "\n", 1);
      $height=substr_count($question["question"],"\n")*$questionFontSize;
      foreach ($question["answers"] as $value)
      {
        $value["text"]=wordwrap($value["text"],30, "\n", 1);
        $height+=(substr_count($value["text"],"\n")+1)*$answerFontSize;
      }
      return $height;
    }
    
    function MakePDF($tests)
    {
      $leftPadding=30;
      $startYPage=730;
      $endYPage=60;
      $questionFontSize=14;
      $answerFontSize=12;
      $marks=array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "x", "y", "z");
      $courseName=$this->CourseName();
      
      $pdf = pdf_new();
      pdf_open_file($pdf, "");
      pdf_set_info($pdf, "Author", "Probatur");
      pdf_set_info($pdf, "Title", "Testy");
      pdf_set_info($pdf, "Creator", "Probatur");
      pdf_set_info($pdf, "Subject", "Testy");
      //pdf_set_parameter($pdf, "Encoding", "iso8859-2 = fonts\iso8859-2.enc");  
      pdf_set_parameter($pdf, "FontOutline", "Courier=fonts/cour.ttf"); // get a custom font
      $font = pdf_findfont($pdf, "Courier",  "iso8859-2", 1); // declare custom font & embed into file
      
      $numTest=0;
      foreach ($tests as $keyTest=>$test)
      {
        $numTest++;
        pdf_begin_page($pdf, 595, 842);
        pdf_add_bookmark($pdf, "Test ".$numTest, 0, 0);
        $this->MakePageHeader($test, $courseName, $pdf, $font, $leftPadding);
        $aktYPos=$startYPage;
        $aktXPos=$leftPadding;
        $numQuestion=0;
        foreach ($test["test"]["questions"] as $keyQuestion=>$question)
        {
          $numQuestion++;
          if (($aktYPos-$this->GetQuestionHeight($question,$questionFontSize,$answerFontSize))<$endYPage)
          {
            if ($aktXPos==$leftPadding)
            {
              $aktXPos=310;
            }
            else
            {
              $aktXPos=$leftPadding;
              pdf_end_page($pdf);
              pdf_begin_page($pdf, 595, 842);
              $this->MakePageHeader($test, $courseName, $pdf, $font, $leftPadding);
            }
            $aktYPos=$startYPage;
          }
          pdf_setfont($pdf, $font, $questionFontSize);
          $this->PrintText($numQuestion.". ".$question["question"], $pdf, 27, $questionFontSize, $aktXPos, $aktYPos, 25);
          $aktYPos-=$this->GetTextHeight($numQuestion.". ".$question["question"], 27, $questionFontSize);
          $numAnswer=0;
          foreach ($question["answers"] as $keyAnswer=>$answer)
          {
            $numAnswer++;
            pdf_setfont($pdf, $font, $answerFontSize);
            $this->PrintText($marks[$numAnswer-1].") ".$answer["text"], $pdf, 30, $answerFontSize, $aktXPos+30, $aktYPos, 22);
            $aktYPos-=$this->GetTextHeight($marks[$numAnswer-1].") ".$answer["text"], 30, $answerFontSize);
          }
          $aktYPos-=$answerFontSize;
        }
        pdf_end_page($pdf);
      }
      pdf_close($pdf);

      $data = pdf_get_buffer($pdf);
      header("Content-type: application/pdf");
      header("Content-disposition: inline; filename=testy.pdf");
      header("Content-length: " . strlen($data));
      echo $data;
      $this->bAllowDraw=false;
      
      pdf_delete($pdf);
    }
    
    function ProcessPaperTests($tests)
    {
      //zisti znenie otazky a text odpovedi
      $tests2=array();
      $i=0;
      foreach ($tests as $keyTest=>$test)
      {
        foreach ($test["test"] as $keyAnswerSet=>$answerSet)
        {
          $query = "SELECT tQ.question, tA.text, tA.id ".
                   "FROM tQuestion AS tQ, tAnswerSet AS tAS, tAnswer AS tA ".
                   "WHERE tAS.id_question=tQ.id AND tA.id_answerSet=tAS.id AND ".
                   "tAS.id=".$answerSet["id_answerSet"].";";
          $result = $this->db->QueryToArray($query);
          if ($result!=0)
          {
            foreach ($result as $key=>$value)
            {
              $tests2[$i]["test"]["questions"][$answerSet["id_answerSet"]]["question"]=$value["question"];
              $tests2[$i]["test"]["questions"][$answerSet["id_answerSet"]]["id_answerSet"]=$answerSet["id_answerSet"];
              $tests2[$i]["test"]["questions"][$answerSet["id_answerSet"]]["answers"][$value["id"]]["id"]=$value["id"];
              $tests2[$i]["test"]["questions"][$answerSet["id_answerSet"]]["answers"][$value["id"]]["text"]=$value["text"];
            }
          }
        }
        $i++;
      }
      //poprehadzuje otazky a odpovede k otazkam
      foreach ($tests2 as $keyTest=>$test)
      {
        foreach ($test["test"]["questions"] as $keyAnswerSet=>$answerSet)
        {
          shuffle($tests2[$keyTest]["test"]["questions"][$keyAnswerSet]["answers"]);
        }
        shuffle($tests2[$keyTest]["test"]["questions"]);
      }
      //ulozi testy do databazy
      foreach ($tests2 as $keyTest=>$test)
      {
        $query = "INSERT INTO tTestTemplate (id_course, printed) VALUES(".
                 $this->getParams["courseID"].", 1);";
        $result = $this->db->Query($query);
        $testTemplateID=$this->db->InsertId();
        $query = "INSERT INTO tTest (id_testTemplate) VALUES(".$testTemplateID.");";
        $result = $this->db->Query($query);
        $testID=$this->db->InsertId();
        $tests2[$keyTest]["id"]=$testID;
        
        $i=1;
        foreach ($test["test"]["questions"] as $question)
        {
          $query = "INSERT INTO tTestItems (id_testTemplate, id_answerSet) VALUES(".
                   $testTemplateID.", ".$question["id_answerSet"].");";
          $result = $this->db->Query($query);
          $query = "INSERT INTO tTestAnswer (id_test, `index`) VALUES(".
                   $testID.", ".$i.");";
          $result = $this->db->Query($query);
          $testAnswerID=$this->db->InsertId();
          
          $j=1;
          foreach ($question["answers"] as $answer)
          {
            $query = "INSERT INTO tTestAnswerToAnswer (id_testAnswer, id_answer, `index`) VALUES(".
                     $testAnswerID.", ".$answer["id"].", ".$j.");";
            $result = $this->db->Query($query);
            $j++;
          }
          $i++;
        }
      }
      $this->MakePDF($tests2);
    }
    	 
    function __construct( $smarty, $db, $action, $postParams, $getParams )
    {
      parent::__construct( $smarty, $db, $action, $postParams, $getParams );
      $this->menu=new cCourseTeacherMenu;
      if (isset($this->getParams["courseID"]) && ($this->getParams["courseID"]!=="")) 
      {
        $this->menu->GenerateMenu("&amp;courseID=".$this->getParams["courseID"]);
      }
      else
      {
        $this->menu->GenerateMenu("");
      }
      $menuItem=$this->menu->GetItemByLabel("testy");
      $menuItem->bExpanded=true;
      $menuItem=$menuItem->GetItemByLabel("generovanie");
      $menuItem->bSelected=true;
    }
		
    function Process()
    {
      if ($this->bLoggedInAsTeacher && $this->IsTeacherToCourse())
      {
        if ($this->action==="generateTests") 
        {
          if (isset($this->postParams["number"]))
          {
            $this->postParams["number"]=(int)$this->postParams["number"];
            $domains=array();
            $this->GetDataForGenerating($domains,$questionCount);
            for ($i=1;$i<=$this->postParams["number"];$i++)
            {
              $test=$this->GenerateTest($domains,$questionCount);
              if (is_null($test))
              {
                $this->smarty->assign("informationText", "Generovanie testu zlyhalo. Asi sú zle nastavené hodnoty generovania.");
                break;
              }
              else
              {
                $query = "INSERT INTO tTestTemplate (id_course) VALUES(".$this->getParams["courseID"].");";
                $result = $this->db->Query($query);
                $testID=$this->db->InsertId();
                foreach ($test as $value)
                {
                  $query = "INSERT INTO tTestItems (id_testTemplate, id_answerSet) VALUES(".
                           $testID.", ".$value["id_answerSet"].");";
                  $result = $this->db->Query($query);
                }
                $this->smarty->assign("informationText", "Testy boli úspešne vygenerované.");
              }
            }
          }
          else
          {
            $this->smarty->assign("informationText", "Zle nastavený počet testov.");
          }
          $this->action="";
        }
        elseif ($this->action==="generatePaperTests") 
        {
          if (isset($this->postParams["number"]))
          {
            $this->postParams["number"]=(int)$this->postParams["number"];
            $domains=array();
            $this->GetDataForGenerating($domains,$questionCount);
            $tests=array();
            for ($i=1;$i<=$this->postParams["number"];$i++)
            {
              $test=$this->GenerateTest($domains,$questionCount);
              if (is_null($test))
              {
                $this->smarty->assign("informationText", "Generovanie testu zlyhalo. Asi sú zle nastavené hodnoty generovania.");
                break;
              }
              else
              {
                $tests[$i]["test"]=$test;
                $this->smarty->assign("informationText", "Testy boli úspešne vygenerované.");
              }
            }
            if (count($tests)!=0)
            {
              //uloz papierove testy a vytlac ich
              $this->ProcessPaperTests($tests);
            }
          }
          else
          {
            $this->smarty->assign("informationText", "Zle nastavený počet testov.");
          }
          $this->action="";
        }
        elseif ($this->action==="generateDemoTest") 
        {
          //zmazeme stary demo test
          $query = "SELECT tC.id_demoTest FROM tCourse AS tC ".
                   "WHERE tC.id=".$this->getParams["courseID"].";";
          $demoTestID = $this->db->QueryToRow($query);
          if ( $demoTestID != 0 )
          {
            if ($demoTestID["id_demoTest"]!=0)
            {
              $query = "DELETE FROM tTestItems ".
                       "WHERE id_testTemplate=".$demoTestID["id_demoTest"].";";
              $result = $this->db->Query($query);
              
              $query = "DELETE FROM tTestTemplate ".
                       "WHERE id=".$demoTestID["id_demoTest"].";";
              $result = $this->db->Query($query);
              
              $query = "UPDATE tCourse SET id_demoTest=0 ".
                       "WHERE id=".$this->getParams["courseID"].";";
              $result = $this->db->Query($query);
            }
          }
          
          //vytvorime novy demo test
          $domains=array();
          $this->GetDataForGenerating($domains,$questionCount);
          $test=$this->GenerateTest($domains,$questionCount);
          if (is_null($test))
          {
            $this->smarty->assign("informationText", "Generovanie testu zlyhalo. Asi sú zle nastavené hodnoty generovania.");
          }
          else
          {
            $query = "INSERT INTO tTestTemplate (id_course, printed) VALUES(".
                     $this->getParams["courseID"].", 0);";
            $result = $this->db->Query($query);
            $testID=$this->db->InsertId();
            foreach ($test as $value)
            {
              $query = "INSERT INTO tTestItems (id_testTemplate, id_answerSet) VALUES(".
                       $testID.", ".$value["id_answerSet"].");";
              $result = $this->db->Query($query);
            }
            $query = "UPDATE tCourse SET id_demoTest=".$testID." WHERE id=".$this->getParams["courseID"].";";
            $result = $this->db->Query($query);
            $this->smarty->assign("informationText", "Demo test bol úspešne vygenerovaný.");
          }
          $this->action="";
        }
        elseif ($this->action==="deleteTests") 
        {
          //vymazeme vsetky otazky z test tamplatov, ktore neboli este pouzite v teste
          $query = "DELETE tTI FROM tTestItems AS tTI, tTestTemplate AS tTT, tCourse AS tC ".
                   "WHERE tTI.id_testTemplate=tTT.id AND NOT tTT.printed AND tTT.id_course=tC.id AND ".
                   "tC.id=".$this->getParams["courseID"]." AND tC.id_demoTest!=tTT.id AND NOT EXISTS(".
                   "SELECT tT.id FROM tTest AS tT WHERE tT.id_testTemplate=tTT.id);";
          $result = $this->db->Query($query);
          
          //vymazeme samotne test templaty, ktore neboli este pouzite v teste
          $query = "DELETE tTT FROM tTestTemplate AS tTT, tCourse AS tC ".
                   "WHERE tTT.id_course=tC.id AND NOT tTT.printed AND ".
                   "tC.id=".$this->getParams["courseID"]." AND tC.id_demoTest!=tTT.id AND NOT EXISTS(".
                   "SELECT tT.id FROM tTest AS tT WHERE tT.id_testTemplate=tTT.id);";
          $result = $this->db->Query($query);
          
          //oznacime test templaty, ktore boli pouzite v teste, za zmazane
          $query = "UPDATE tTestTemplate, tCourse ".
                   "WHERE tTestTemplate.id_course=tCourse.id AND NOT tTestTemplate.printed AND ".
                   "tCourse.id=".$this->getParams["courseID"]." AND tCourse.id_demoTest!=tTestTemplate.id ".
                   "AND NOT EXISTS(SELECT tT.id FROM tTest AS tT WHERE tT.id_testTemplate=tTestTemplate.id);";
          $result = $this->db->Query($query);
          
          $this->action="";
        }
        elseif ($this->action==="deletePaperTests") 
        {
          //vymazeme udaje z tabulky tTestAnswerToAnswer
          $query = "DELETE tTATA FROM tCourse AS tC, tTestTemplate AS tTT, tTest AS tT, tTestAnswer AS tTA, tTestAnswerToAnswer AS tTATA ".
                   "WHERE tTT.printed AND tTT.id_course=tC.id AND ".
                   "tC.id=".$this->getParams["courseID"]." AND tC.id_demoTest!=tTT.id AND tT.id_testTemplate=tTT.id AND ".
                   "tT.id_user=0 AND tTA.id_test=tT.id AND tTATA.id_testAnswer=tTA.id;";
          $result = $this->db->Query($query);
          
          //vymazeme udaje z tTestAnswer
          $query = "DELETE tTA FROM tCourse AS tC, tTestTemplate AS tTT, tTest AS tT, tTestAnswer AS tTA ".
                   "WHERE tTT.printed AND tTT.id_course=tC.id AND ".
                   "tC.id=".$this->getParams["courseID"]." AND tC.id_demoTest!=tTT.id AND tT.id_testTemplate=tTT.id AND ".
                   "tT.id_user=0 AND tTA.id_test=tT.id;";
          $result = $this->db->Query($query);
          
          //vymazeme zaznamy z tTest
          $query = "DELETE tT FROM tCourse AS tC, tTestTemplate AS tTT, tTest AS tT ".
                   "WHERE tTT.printed AND tTT.id_course=tC.id AND ".
                   "tC.id=".$this->getParams["courseID"]." AND tC.id_demoTest!=tTT.id AND tT.id_testTemplate=tTT.id AND ".
                   "tT.id_user=0;";
          $result = $this->db->Query($query);
          
          //vymazeme vsetky otazky z test tamplatov, ktore neboli este pouzite v teste
          $query = "DELETE tTI FROM tTestItems AS tTI, tTestTemplate AS tTT, tCourse AS tC ".
                   "WHERE tTI.id_testTemplate=tTT.id AND tTT.printed AND tTT.id_course=tC.id AND ".
                   "tC.id=".$this->getParams["courseID"]." AND tC.id_demoTest!=tTT.id AND NOT EXISTS(".
                   "SELECT tT.id FROM tTest AS tT WHERE tT.id_testTemplate=tTT.id);";
          $result = $this->db->Query($query);
          
          //vymazeme samotne test templaty, ktore neboli este pouzite v teste
          $query = "DELETE tTT FROM tTestTemplate AS tTT, tCourse AS tC ".
                   "WHERE tTT.id_course=tC.id AND tTT.printed AND ".
                   "tC.id=".$this->getParams["courseID"]." AND tC.id_demoTest!=tTT.id AND NOT EXISTS(".
                   "SELECT tT.id FROM tTest AS tT WHERE tT.id_testTemplate=tTT.id);";
          $result = $this->db->Query($query);
          
          //oznacime test templaty, ktore boli pouzite v teste, za zmazane
          $query = "UPDATE tTestTemplate, tCourse ".
                   "WHERE tTestTemplate.id_course=tCourse.id AND tTestTemplate.printed AND ".
                   "tCourse.id=".$this->getParams["courseID"]." AND tCourse.id_demoTest!=tTestTemplate.id ".
                   "AND NOT EXISTS(SELECT tT.id FROM tTest AS tT WHERE tT.id_testTemplate=tTestTemplate.id);";
          $result = $this->db->Query($query);
          
          $this->action="";
        }
        elseif ($this->action==="saveSetup") 
        {
          if (isset($this->postParams["questionCount"]))
          {
            $this->postParams["questionCount"]=mysql_real_escape_string($this->postParams["questionCount"]);
            $query = "UPDATE tCourse SET questionCount=".$this->postParams["questionCount"]." ".
                     "WHERE id=".$this->getParams["courseID"].";";
            $result = $this->db->Query($query);
          }
          $query = "DELETE FROM tCourseToDomain WHERE id_course=".$this->getParams["courseID"].";";
          $result = $this->db->Query($query);
          foreach ($this->postParams as $key=>$value)
          {
            if ((strlen($key)>3) && (substr($key,0,3)==="min"))
            {
              $id=mysql_real_escape_string(substr($key,3,strlen($key)-3));
              $this->getParams["domainID"]=$id;
              if (isset($this->postParams["max".$id]) && ($this->IsCourseToDomain()))
              {
                $min=mysql_real_escape_string($value);
                $max=mysql_real_escape_string($this->postParams["max".$id]);
                $query = "INSERT INTO tCourseToDomain (id_course, id_domain, min, max) ".
                         "VALUES(".$this->getParams["courseID"].", ".$id.", ".$min.", ".$max.");";
                $result = $this->db->Query($query);
              }
            }
          }
          $this->action="setup";
          $this->smarty->assign("saved", true);
        }
      }
      return true;
    }
    
    function Draw()
    {
      if ($this->bLoggedInAsTeacher && ($this->IsTeacherToCourse())) 
      {
        if ($this->action==="")
        {
          $query = "SELECT COUNT(*) AS count FROM tTestTemplate AS tTT, tCourse AS tC ".
                   "WHERE tTT.id_course=tC.id AND tTT.id_course=".$this->getParams["courseID"]." AND ".
                   "tTT.id!=tC.id_demoTest AND NOT tTT.obsolete AND NOT tTT.printed;";
          
          $result = $this->db->QueryToRow($query);
          if ( $result != 0 )
          {
            $this->smarty->assign("countPCTests", $result["count"]);
          }
          else
          {
            $this->smarty->assign("countPCTests", 0);
          }
          
          $query = "SELECT COUNT(*) AS count FROM tTestTemplate AS tTT, tTest AS tT, tCourse AS tC ".
                   "WHERE tT.id_testTemplate=tTT.id AND tT.id_user=0 AND ".
                   "tTT.id_course=tC.id AND tTT.id_course=".$this->getParams["courseID"]." AND ".
                   "tTT.id!=tC.id_demoTest AND NOT tTT.obsolete AND tTT.printed;";
          
          $result = $this->db->QueryToRow($query);
          if ( $result != 0 )
          {
            $this->smarty->assign("countPrintedTests", $result["count"]);
          }
          else
          {
            $this->smarty->assign("countPrintedTests", 0);
          }
        }
        elseif ($this->action==="setup")
        {
          $query = "SELECT tC.questionCount FROM tCourse AS tC ".
                   "WHERE id=".$this->getParams["courseID"].";";
          $result = $this->db->QueryToRow($query);
          if ( $result != 0 )
          {
            $this->smarty->assign("questionCount", $result["questionCount"]);
          }
          $query = "SELECT tD.id, tD.id_parent, tD.subject, COALESCE(tCTD.min, 0) AS min, COALESCE(tCTD.max, 0) AS max ".
                   "FROM tDomain AS tD ".
                   "LEFT OUTER JOIN tCourseToDomain AS tCTD ON (tCTD.id_domain=tD.id) ".
                   "WHERE tD.id_course=".$this->getParams["courseID"]." AND NOT tD.obsolete ".
                   "ORDER BY tD.subject ASC;";
          $result = $this->db->QueryToArray($query);
          if ( $result != 0 )
          {
            $domains=array();
            foreach ($result as $value)
            {
              $domains[$value["id"]]=$value;
              $domains[$value["id"]]["subdomains"]=array();
            }
            foreach ($domains as $value)
            {
              if ($value["id_parent"]!=0)
              {
                $domains[$value["id_parent"]]["subdomains"][$value["id"]]=$value["id"];
              }
            }
            $result=array();
            foreach ($domains as $value)
            {
              if ($domains[$value["id"]]["id_parent"]==0)
              {
                $this->SortDomainsAndSetLeftPadding($result,$domains,$value["id"],0);
              }
            }
            $this->smarty->assign("domains", $result);
          }
        }
        else
        {
          $this->bAccessDenied=true;
        }
      }
      else
      {
        $this->bAccessDenied=true;
      }
      $this->smarty->assign("action", $this->action);
      $this->smarty->assign("course", $this->CourseName());
      $this->smarty->assign("courseID", $this->getParams["courseID"]);
      $this->smarty->assign("content","testGenerating.tpl");
      parent::Draw();
    }
	}
?>
