<html>
<head>
<title>Take a Quiz/Test</title>
<link rel="stylesheet" href="quiz.css">
</head>
<body>
<h2 style='color:white'>   Take a Quiz/Test</h2>

<?php
//== Selection File ===========================================================
    $selection_file = '/home/sultans/web/php/demo/quiz/selection.txt';                  //selection file
//=============================================================================

    error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);      //all but warnings & notices

    $selections = Array();                              #selection file
    $questions  = Array();                              #questions file     
    $data       = Array();                              #selected data
         
    read_selections();
    read_questions();
    select_data();

    display();

    if ($_POST)                                         //if answers submitted 
    {
        print_submission();
        compute_grade();
    }

//===============================================================================
// Selection file contains selection critirea from which to sub-select one or 
// more questions from the overall questions.csv file 
//===============================================================================
    function read_selections()
    {
        global $selection_file, $selections;   
 
        $handle = fopen ($selection_file, 'r')  
                      or die ("Cannot open $selection_file for read"); 

        while($rec = fgets($handle))
        {
            $kv    = explode('=', $rec);        //split on =
            $key   = trim($kv[0]);              //value before the =
            $value = trim($kv[1]);              //value after the =
            $selections[$key] = $value;
        }
        fclose($handle);
    }
//===============================================================================
// Read entire questions file into an questions[] array 
//===============================================================================
    function read_questions()
    {
        global $selections, $questions;   
 
        $questions_file = $selections['questions_file'];

        $handle = fopen ($questions_file, 'r')  
                      or die ("Cannot open $questions_file for read"); 

        fgets($handle);                         //throw away the first line (Excel headers)

        while($rec = fgets($handle))
                $questions[] = $rec;            //add to the $questions array

        fclose($handle);
    }

//===============================================================================
// Select a subset of entire questions[] array into $data[] array  
//===============================================================================
    function select_data()
    {
        global $selections, $questions, $data;   
         
        $sel_owner   = $selections['select_owner'];
        $sel_dataset = $selections['select_dataset'];
        $sel_topic   = $selections['select_topic'];
        $sel_max     = $selections['select_max_q'];

        $max = 0;
        foreach($questions as $rec)
        {
            $fields = explode(',', $rec);

            $owner     = $fields[1];
            $dataset   = $fields[2];
            $topic     = $fields[3];
 
            if ($sel_owner   && $sel_owner   != $owner)   continue;  
            if ($sel_dataset && $sel_dataset != $dataset) continue;
            if ($sel_topic   && $sel_topic   != $topic)   continue; 
            if ($sel_max     && $sel_max     <= $max  )   continue;

            $data[]        = $fields;               //store question in data array
            $qNum          = $max+1;                //create a question number
            $data[$max][0] = $qNum;                 //change orig question number from file to new question number  
            $max++;
       } 
    } 

//===============================================================================
// Display html form to the screen
//===============================================================================
function display()
{               
    global $data;

    print "<form method=POST action=$_SERVER[PHP_SELF]> \n";                  //itself 
    print "<input type=submit value='Submit your Answers'><br><br> \n";
    print "<fieldset style='background-color:eeeeee; border-color:gold; width:350px; border-radius:10px'> \n";
    print "<legend>Enter Your Answers Below</legend> \n";

    foreach($data as $fields)
    {                       
        $qNum      = $fields[0];                    //question number
        $owner     = $fields[1];
        $dataset   = $fields[2];
        $topic     = $fields[3];
        $question  = $fields[4];
        $type      = $fields[5];                    //multiple or not
        $weight    = $fields[6];
        $correct   = $fields[7];                    //list of correct answers
        $a1_text   = trim($fields[8]);              //answer 1 from file
        $a2_text   = trim($fields[9]);              //answer 2 from file
        $a3_text   = trim($fields[10]);
        $a4_text   = trim($fields[11]);
        $a5_text   = trim($fields[12]);
        $a6_text   = trim($fields[13]);
        $a7_text   = trim($fields[14]);
        $a8_text   = trim($fields[15]);

        $a      = array(1,2,3,4,5,6,7,8);           //generate an array of 1,2,3...

        $a_text = array($a1_text,$a2_text,$a3_text,$a4_text,$a5_text,$a6_text,$a7_text,$a8_text);   //array of answers            

//        if (strtolower($a1_text)=='true')  $a[0] = 'T';
//        if (strtolower($a1_text)=='false') $a[0] = 'F';
//        if (strtolower($a2_text)=='true')  $a[1] = 'T';
//        if (strtolower($a2_text)=='false') $a[1] = 'F';

        $multiple = preg_match('/mult/i', $type) ? 'multiple' : '';         //check if type=multiple
        $boxType  = ($multiple) ? checkbox : radio;                         //if multiple boxType=checkbox else radio
        $bracket  = ($multiple) ? '[]' : '';                                //if multiple bracket=[]
        $qqNum = 'q'.$qNum;                                                 //append a 'q' in front of question number

        print "<table id=$qNum style='display:none'> \n";
        print "<tr><td><input type=button value=' < ' onclick=show($qNum-1,'prev')> \n";
        print "   <input type=button value=' > ' onclick=show($qNum+1,'next')> \n"; 
        print "<tr><td> \n";
        print "<tr><td><tr><td><b>Q$qNum - $question</b></td></tr> \n";

        $i=0;
        foreach($a_text as $answer)                                     //for each answer
        { 
            if ($answer != '')                                          //if answer has text
            {                    
                $n = $a[$i];                                            //$n = $a array[$i], which is the answer number
                if ($multiple)
                    for ($j=0; $j<count($_POST[$qqNum]); $j++)          //iterate for number of submitted answers
                    {                 
                        $checked = '';
                        if ($_POST[$qqNum][$j]==$n)                     //if submitted answer = $n
                        {  
                            $checked = 'checked';                       //turn the checkbox on
                            break;
                        }
                    }
                else
                    $checked = ($_POST[$qqNum]==$n) ? 'checked' : '';

                print "<tr><td><input type=$boxType name=$qqNum$bracket id=$qqNum.$n value=$n $checked>";
                print "<label for=$qqNum.$n> $n - $answer </label>\n";
            }
            $i++;
        }
        print "</table> \n";
    }  
    print "</fieldset> \n";
    print "<br><input type=submit value='Submit your Answers'><br><br> \n";
    print "</form> \n";
 }

//===============================================================================
// Print submitted answers along with correct answers
//===============================================================================
    function print_submission()
    {
        global $data;   
 
        print "<table class=output border=1 style='width:400px; border-color:gold'> \n";
        print "<tr style='background-color:eeeeee'><th>Question<th>Your Answer(s)<th>Correct Answer(s)<th>Weight Value\n";

        for ($i=0; $i < count($data); $i++)         //iterate through all questions
        {
           $qNum  = $i;                             //iterate thru $data area starting at $qNum =0
           $qNum1 = $i+1;                           //access  the $_POST area starting at $qNum1=1           
           $qqNum1   = 'q'.$qNum1;                  //append q to question number   
           $QqNum1   = 'Q'.$qNum1;                  //append Q to question number (for display)
           $answer   = $_POST[$qqNum1];             //the submitted answer (from $_POST array)
           $weight   = $data[$qNum][6];             //the weight of the question (from file)
           $correct  = $data[$qNum][7];             //the list of correct answers (from file)
  
           if (is_array($answer))
                $answer = implode(' ', $answer);

           print "<tr style='text-align:center'><td>$QqNum1<td>$answer<td>$correct<td>$weight \n";
       }
       print "</table> \n";
 
    }
//===============================================================================
// Compute the grade and print
//===============================================================================
     function compute_grade()
    {
        global $data;   
 
        print "<br>";

        $earned_weight = 0;
        $total_weight  = 0;
//        $sub_answer    = $_POST[$qqNum1];         //submitted answer

        for ($i=0; $i < count($data); $i++)         //iterate through alll questions
        {
            $qNum  = $i;                            //iterate thru $data area starting at $qNum =0
            $qNum1 = $i+1;                          //access  the $_POST area starting at $qNum1=1           
            $qqNum1 = 'q'.$qNum1;                   //append q to question number   
            $type       = $data[$i][5];
            $weight     = $data[$i][6];
            $correct    = $data[$i][7];
            $submittedAnswer = $_POST[$qqNum1];     //submitted answer (could be an array if type=multiple)

            $total_weight += $weight;
            $multiple = preg_match('/mult/i', $type) ? 'multiple' : '';     //is type=multiple? 

            if ($multiple)                                          //if question was multiple choice
            {
                $a1_text = trim($data[$i][8]);                      //get answer1 from the file  
                $a2_text = trim($data[$i][9]);                      //get answer2
                $a3_text = trim($data[$i][10]);
                $a4_text = trim($data[$i][11]);
                $a5_text = trim($data[$i][12]);
                $a6_text = trim($data[$i][13]);
                $a7_text = trim($data[$i][14]);
                $a8_text = trim($data[$i][15]);
  
                $a_text = array();
                if ($a1_text != '') $a_text[] = $a1_text;           //add answer1 to the array
                if ($a2_text != '') $a_text[] = $a2_text;           //add answer2
                if ($a3_text != '') $a_text[] = $a3_text;
                if ($a4_text != '') $a_text[] = $a4_text;
                if ($a5_text != '') $a_text[] = $a5_text;
                if ($a6_text != '') $a_text[] = $a6_text;
                if ($a7_text != '') $a_text[] = $a7_text;
                if ($a8_text != '') $a_text[] = $a8_text;

                $howManyAnswers = count($a_text);                  //how many answers in questions file
                $correctAnswers = preg_split('/\s+/', $correct);   //how many correct answers in questions file

                if (count($submittedAnswer)>0)                     //if question was answered
                {
                    $earned_weight += $weight;                              //give full credit                  
                    foreach ($submittedAnswer as $sub_answer)
                        if (! in_array($sub_answer, $correctAnswers))
                            $earned_weight -= ($weight/$howManyAnswers);     //subtract for wrong answer
                    foreach ($correctAnswers as $corr_answer)
                        if (! in_array($corr_answer, $submittedAnswer))
                            $earned_weight -= ($weight/$howManyAnswers);     //subtract for wrong answer
                }   
            }
            else                                                    //if not multiple
                if ($submittedAnswer == $correct)
                    $earned_weight += $weight;                      //give credit 
        }

        $grade = ($earned_weight/$total_weight) * 100;
        $grade = round($grade,2);
        print "<table class=output border=1 style='width:400px; border-color:gold'> \n";
        print "<tr style='background-color:eeeeee'><th>Your Grade\n";
        print "<tr style='text-align:center'><td> $grade \n";
        print "</table> \n";
 
    }

//===============================================================================
?>

<script>
show(1)                           //show the first question

function show(id,direction)
{
    document.getElementById(id).style.display       ='block';           //show that particular id
    if (direction=='prev')
        document.getElementById(id+1).style.display ='none';            //hide the previous id  
    if (direction=='next')
        document.getElementById(id-1).style.display ='none';            //hide the next id  
} 

</script>
</body>
</html>