<?php
/**
 * User: David Camacho
 * Date: 02/04/2015
 * Time: 2:21
 */

include_once "./controllers/Core.php";
include_once "./classes/Course.php";
include_once "./classes/Test.php";
include_once "./classes/Question.php";
include_once "./classes/Answer.php";

class TestController extends Core
{

    var $mode;
    var $id_test;
    var $output;

    public function TestController()
    {
        parent::Core();
        parent::isPrivateZone();

        // Check if id test is sent
        if (!isset($_POST["id_test"]))
            header('Location: main.php');
        $this->id_test = $_POST["id_test"];


        $this->test = new Test();

        //Check role, if student
        $role = $this->user->getRole();
        if ($this->user->getRole() == 0) {
            // Check if is user has course inscription
            $course = new Course();
            if (!$course->isRegisteredIntoCourse($_POST["id_test"]))
                header('Location: main.php');
            $course->destroy();

            $expire_date = $this->test->getExpireDate((int)$_POST["id_test"]);
            $results_date = $this->test->getResultsDate((int)$_POST["id_test"]);
            $open_date = $this->test->getOpenDate((int)$_POST["id_test"]);
            $is_delivered = $this->test->isDelivered((int)$_POST["id_test"]);
            $is_stored = $this->test->isStored((int)$_POST["id_test"]);

            // Save test for restore
            if (isset($_POST["save_test"]))
                $this->saveTest();
            // Deliver test
            elseif(isset($_POST["send_test"]))
                $this->deliverTest();
            // If closed
            elseif (  date("Y-m-d H:i:s", strtotime($expire_date))<= date("Y-m-d H:i:s") ){
                //if results_date < now
                if ( date("Y-m-d H:i:s", strtotime($results_date))<= date("Y-m-d H:i:s") )
                    $this->mode = "results"; // if closed and results_date <= now show results
                else
                    $this->mode = "no_results"; // if closed and results_date > now don't show results


            // If open
            }elseif( date("Y-m-d H:i:s", strtotime($open_date))<= date("Y-m-d H:i:s")){

                //if delivered show exit message
                if ($is_delivered){
                    $this->mode = "delivered"; //test delivered
                 //stored restore
                }elseif($is_stored){
                    $this->mode = "restore"; //restore test
                }else{
                    $this->mode = "blank"; //blank test
                }
            }else{
               header('Location: main.php');
            }

        //If teacher
        } elseif ($role == 1){
            // Check if is user is course Creator
            $course = new Course();
            if (!$course->isCourseCreator($_POST["id_test"]))
                header('Location: main.php');
            $course->destroy();

            $this->mode = "results"; //result test
        }


        if  ($this->mode == "no_results")
                $this->displayMessage( $this->langs->translate->getTranslate("no_result_yet"));
        elseif ($this->mode == "delivered")
                $this->displayMessage( $this->langs->translate->getTranslate("no_results_yet"));
        elseif ($this->mode == "results" ||
                $this->mode == "restore" ||
                $this->mode == "blank") {
            //Generate test
            $this->output = $this->buildTest();

        }

        //Display template
        $this->displayTemplate();

    }

    private function saveTest(){
        $questions= $this->test->getQuestions($this->id_test);

        $answer = new Answer();
        $id_user = (int)$this->user->getIdUser();

        for($i=0; $i < count($questions["id_question"]);$i++){

            if(isset($_POST["question_".$questions["id_question"][$i]])) {

                if ($answer->isAnsweredBefore($id_user, (int)$questions["id_question"][$i]))
                    $answer->updateUserAnswer($id_user, (int)$questions["id_question"][$i], (int)$_POST["question_" . $questions["id_question"][$i]]);
                else
                    $answer->insertAnswer($id_user, (int)$_POST["question_" . $questions["id_question"][$i]]);

            }
        }
        $this->test->removeStoredTest($id_user, (int)$this->id_test);
        $this->test->insertStoredTest($id_user,$this->id_test);
        header('Location: main.php');

    }

    private function deliverTest(){

        if ($this->test->isDelivered($this->id_test)){
            $this->displayMessage('already_delivered_test');
           return;
        }
        $questions= $this->test->getQuestions($this->id_test);

        $answer = new Answer();
        $id_user = (int)$this->user->getIdUser();

        for($i=0; $i < count($questions["id_question"]);$i++){

            if(isset($_POST["question_".$questions["id_question"][$i]])) {

                if ($answer->isAnsweredBefore($id_user, (int)$questions["id_question"][$i]))
                    $answer->updateUserAnswer($id_user, (int)$questions["id_question"][$i], (int)$_POST["question_" . $questions["id_question"][$i]]);
                else
                    $answer->insertAnswer($id_user, (int)$_POST["question_" . $questions["id_question"][$i]]);

            }
        }
        $this->test->removeStoredTest($id_user, (int)$this->id_test);
        $this->test->insertDeliveredTest($id_user,$this->id_test);
        $this->displayMessage('delivered_test');
    }


    private function displayMessage($msg)
    {
        $this->output = $this->output . '<div class="row">';
        $this->output = $this->output . '<div class ="panel small-12 medium-12 large-12 ">';
        $this->output = $this->output . '<div class ="small-6 small-centered columns">';
        $this->output = $this->output . '<p class="text-center">'.  $this->langs->translate->getTranslate($msg) . '</p>';
        $this->output = $this->output . '<a href="main.php" class="small-12 medium-12 large-12 button">' .$this->langs->translate->getTranslate("go_back") . '</a>';
        $this->output = $this->output . '</div>';
        $this->output = $this->output . '</div>';
        $this->output = $this->output . '</div>';


    }


    private function buildTest()
    {
        $output = "";
        $questions = array();

        $questions= $this->test->getQuestions($this->id_test);

        $output = $this->getButtons();
        $output = $output . '<div class="row">';
        $output = $output . '<div class ="panel small-12 medium-12 large-12">';

        if(count($questions["id_question"])<1) {
            $this->displayMessage( $this->langs->translate->getTranslate("no_questions_found"));
            return $this->output;
        }


        if ($this->mode == "restore")
            $output = $output . '<div data-alert class="alert-box success radius">
                                  ' . $this->langs->translate->getTranslate("saved_test_loaded") . '
                                  <a href="#" class="close">&times;</a>
                                </div>';


        for($i=0; $i < count($questions["id_question"]);$i++)
        {

            $output = $output . '<div class ="small-12 medium-12 large-12">';
            $output = $output . '<p><h5>(' .$questions["points"][$i] . ' ' .$this->langs->translate->getTranslate("points") . ')</h5><strong>' . ($i+1) . '. ' .$questions["question"][$i] . '</strong></p>';
            $output = $output . $this->getAnswers($questions["id_question"][$i]);
            $output = $output . '</div>';
            $output = $output . '<hr>';

        }
        $output = $output . '</div>';
        $output = $output . '</div>';

        //Send test button
        if ($this->mode == "blank" || $this->mode == "restore") {
            $output = $output . '<div class="row">';
            $output = $output . '<div class ="panel small-12 medium-12 large-12 ">';
            $output = $output . '<div class ="small-6 small-centered columns">';

            $output = $output . '
                <a role="button" href="#" class="alert button small-12" data-reveal-id="modal-button-send">' . $this->langs->translate->getTranslate('send_test') . '</a>
                <div id="modal-button-send" class="reveal-modal" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog">
                    <h2>Atenció</h2>
                    <p class="lead">' . $this->langs->translate->getTranslate('Només es pot entregar una vegada') . ' </p>
                    <p>' . $this->langs->translate->getTranslate('Està segur que vol entregar el test?') . '</p>

                    <!-- submit fix -->
                    <script>
                        function addSendState() {
                            var input = document.createElement("input");
                            input.setAttribute("type", "hidden");
                            input.setAttribute("name", "send_test");
                            input.setAttribute("value", "send");

                            //append to form element that you want .
                            document.getElementById("test_form").appendChild(input);
                            document.getElementById("test_form").submit();
                        }
                    </script>

                    <a href="#" onClick="addSendState()" class="alert button small-4 medium-4 large-4" style="margin-right:3em;" name="save_test" >' . $this->langs->translate->getTranslate('send_test') . '</a>
                    <a role="button" href="#" class="button small-4 medium-4 large-4 custom-close-reveal-modal">' . $this->langs->translate->getTranslate('no') . '</a>
                    <a class="close-reveal-modal" aria-label="Close">&#215;</a>
                </div>';


            $output = $output . '</div>';
            $output = $output . '</div>';
            $output = $output . '</div>';
        }else{
            $output = $output . '<div class="row">';
            $output = $output . '<div class ="panel small-12 medium-12 large-12 ">';
            $output = $output . '<div class ="small-6 small-centered columns">';
            $output = $output . '<a role="button" href="main.php" class="alert button small-12" >' . $this->langs->translate->getTranslate('go_back') . '</a>';
            $output = $output . '</div>';
            $output = $output . '</div>';
            $output = $output . '</div>';

        }


        return $output;



    }

    private function getAnswers($id_question)
    {

        $question = new Question();
        $id_user = (int)$this->user->getIdUser();
        $answers= $question->getAnswers((int)$id_question);

        if(count($answers["id_answer"])<1)
            return "<p>" . $this->langs->translate->getTranslate("no_answers_found") . "</p>";

        $style = "";
        $checked = "";
        $output = '<div class="row">';
        $output = $output . '<div class ="panel small-12 medium-12 large-12">';
        $output = $output . '<p><strong>' . $this->langs->translate->getTranslate("answers") . '</strong><p>';
        $answer = new Answer();
        for($i=0; $i < count($answers["id_answer"]);$i++)
        {

            // Show user answer if results or restore mode
            if (($this->mode == "results" || $this->mode == "restore") && $answer->hasUserAnsweredThis($id_user, (int)$answers["id_answer"][$i]))
                $checked = 'checked';

            // Show red background if failed answer
            if ($this->mode == "results" && $answer->hasUserAnsweredThis($id_user, (int)$answers["id_answer"][$i]) && !$question->isCorrectAnswer((int)$answers["id_answer"][$i]))
                $style = 'style="background-color:#EC3A61;"';

            // Show red background if is the correct answer
            if ($this->mode == "results" && $question->isCorrectAnswer((int)$answers["id_answer"][$i]))
                $style = 'style="background-color:#96DB5E;"';

            $output = $output . '<div class ="small-12 medium-12 large-12" ' . $style . '>';


            $output = $output . '<input type="radio" name="question_'. (int)$id_question . '" value="'.(int)$answers["id_answer"][$i] . '" id="answer_'.(int)$answers["id_answer"][$i] . '" ' .$checked. ' ><label for="answer_'.(int)$answers["id_answer"][$i] . '" >  ' .$answers["text"][$i] . '</label>';
            $output = $output . '</div>';

            $style = "";
            $checked = "";
        }
        $output = $output . '</div>';
        $output = $output . '</div>';
        return $output;



    }

    private function getButtons()
    {

        $output = "";
        if ($this->mode == "blank" || $this->mode == "restore") {
            $output = '
                <div class="row">
                    <div class="small-6 medium-3 large-3 columns">
                        <a role="button" href="#" class="button" data-reveal-id="modal-button-back">' . $this->langs->translate->getTranslate('go_back') . '</a>
                        <div id="modal-button-back" class="reveal-modal" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog">
                            <h2>Atenció</h2>
                            <p class="lead">' . $this->langs->translate->getTranslate('Si surt, el test no es guardara ni s\'entregará.') . '</p>
                            <p>' . $this->langs->translate->getTranslate('Està segur que vol sortir sense guardar?') . '</p>
                            <a role="button" href="main.php" class="button small-4 medium-4 large-4" style="margin-right:3em;">' . $this->langs->translate->getTranslate('yes') . '</a>
                            <a role="button" href="#" class="button small-4 medium-4 large-4 custom-close-reveal-modal">' . $this->langs->translate->getTranslate('no') . '</a>
                            <a class="close-reveal-modal" aria-label="Close">&#215;</a>
                        </div>
                    </div>

                    <div class="small-6 medium-3 large-3 columns">


                        <a role="button" href="#" class="success button" data-reveal-id="modal-button-save">' . $this->langs->translate->getTranslate('save_test_and_back') . '</a>
                        <div id="modal-button-save" class="reveal-modal" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog">
                            <h2>Atenció</h2>
                            <p class="lead">' . $this->langs->translate->getTranslate('Si guarda el test no s\'entregará fins que ho facis manualment') . '</p>
                            <p>' . $this->langs->translate->getTranslate('Està segur que vol guardari sortir?') . '</p>

                            <!-- submit fix -->
                            <script>
                                function addSaveState() {
                                    var input = document.createElement("input");
                                    input.setAttribute("type", "hidden");
                                    input.setAttribute("name", "save_test");
                                    input.setAttribute("value", "save");

                                    //append to form element that you want .
                                    document.getElementById("test_form").appendChild(input);
                                    document.getElementById("test_form").submit();
                                }
                            </script>


                            <input type="submit" onClick="addSaveState()" class="success button small-4 medium-4 large-4" style="margin-right:3em;" name="save_test" value="' . $this->langs->translate->getTranslate('save_test_and_back') . '">
                            <a role="button" href="#" class="button small-4 medium-4 large-4 custom-close-reveal-modal">' . $this->langs->translate->getTranslate('no') . '</a>
                            <a class="close-reveal-modal" aria-label="Close">&#215;</a>
                        </div>

                    </div>

                </div>';
        }

        return $output;
    }

    private function displayTemplate()
    {
        include_once('./templates/' . _template . '/views/test.html');
    }


}