<?php
// generate html copy 1/2
// Start output buffering
ob_start();

// https://tryphp.w3schools.com/showphp.php?filename=demo_form_validation_complete

/***
// define variables and set to empty values
$A1 = $Aname1 = $Abutton_name1 = "";
$A2 = $Aname2 = $Abutton_name2 = "";
$A3 = $Aname3 = $Abutton_name3 = "";
$score = $total_score = "";

$nameErr = $emailErr = $genderErr = "";
$name = $email = $gender = $comment = "";
***/
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
    }
  }
/*
if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL";
    }
  }
  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }

*/
  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }
  }

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

?>

<?php
if ($include_heading == "no") {
${'xml'.$test}=simplexml_load_file("inc_quarterly_tests/".$test_ref);// or die("Error: Cannot create object $ xml");
  // don't include heading in xml_load_clog.inc
  // test_ref used from clog
}

else {
// was copy pasted from xml_load_quarterly_test_session.inc but now tweaked
/************* heading ***************/
echo "<div id=\"main\" class=\"main\" type=\"text/css\"> ";
echo "<div id=\"topic_area\" class=\"topic_area\" type=\"text/css\">";

/************* file ref ***************/
//$test_ref = "quarterly_test_kasperskygroup148_20230614.xml";
$test_ref = "quarterly_test_kasperskygroup148_20230314.xml";

${'xml'.$test}=simplexml_load_file("inc_quarterly_tests/".$test_ref);// or die("Error: Cannot create object $ xml");

echo "<div width=\"40%;\" style=\"float: left;\">\n";
echo "<h1><img src=\"pix/icons8-quiz-100.png\" width=\"70em\" border=\"0\" alt=\"test name\">".${'xml'.$test}->sbook_test_name."</h1>\n";
echo "<div align=\"right\" style=\"font-size:70%; color: #cdcdcd;\">by D.Potter</div></div>\n";
echo "&nbsp;</div>\n";

echo "<div style=\"margin-left: 35%\" align=\"left\">\n";
echo "<h2>Company: ".${'xml'.$test}->sbook_test_company. "</h2><br />\n";
echo "<h3>Group: ".${'xml'.$test}->sbook_test_group. "</h3><br />\n";
echo "<h3>Target level: ".${'xml'.$test}->sbook_test_level. "</h3><br />\n";
//echo "<h3>Test date: ".${'xml'.$test}->sbook_test_date. "</h3><br /><br />\n";
//echo "<h3>Student name: ______________________________________________  </h3><br /><br />\n";

date_default_timezone_set('Europe/Moscow');
$date = date('Y/m/d H:i:s');
$date4file_name = date('YmdH');
echo "<h3>Test date: ".$date."</h3><br /><br />\n";
?>

<form method="post" action="<?php echo htmlspecialchars('pg.php?content=sbook_plugins/xml_load_quarterly_test_on_line.inc');?>">

<?php
  if (!isset($_POST["name"])) {
echo "<h3>Student name: <input type=\"text\" name=\"name\" value=\"". $name ."\"></h3><br /><br />\n";
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if ((empty($name)) || (!preg_match("/^[a-zA-Z-' ]*$/",$name))) {
      $nameErr = "Only letters and white space allowed<br />\n";
echo "<input type=\"submit\" style=\"text-decoration: none; border: none; background-color: black; -moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius:8px; box-shadow: 0px 6px 6px 0px rgba(0,0,0,0.2); font-weight: bold; font-size: 90%; color: white;\" name=\"submit\" value=\"Submit a valid name to proceed\"><br />\n";  
//echo "<input type=\"submit\" style=\"text-decoration: underline; border: none; background-color: white; font-weight: bold; color: orange;\" name=\"submit\" value=\"Enter a valid name to proceed\"><br />\n";  
    }
  echo $nameErr."<br /><!-- name error-->\n";
echo "<h3>Student name: <input type=\"text\" name=\"name\" value=\"". $name ."\"></h3><br /><br />\n";
  }

  if (!isset($_POST["email"])) {
echo "<h3>E-mail: <input type=\"text\" name=\"email\" value=\"". $email ."\"></h3><br /><br />\n";
    $emailErr = "Email is required<br />\n";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
echo "<input type=\"submit\" style=\"text-decoration: none; border: none; background-color: black; -moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius:8px; box-shadow: 0px 6px 6px 0px rgba(0,0,0,0.2); font-weight: bold; font-size: 90%; color: white;\" name=\"submit\" value=\"Submit a valid e-mail to proceed\"><br />\n";  
//echo "<input type=\"submit\" style=\"text-decoration: underline; border: none; background-color: white; font-weight: bold; color: orange;\" name=\"submit\" value=\"Enter a valid e-mail to proceed\"><br />\n";  
    }
echo "<h3>E-mail: <input type=\"text\" name=\"email\" value=\"". $email ."\"></h3><br /><br />\n";
  echo $emailErr."<br /><!-- email error-->\n";
}


// STEP 1
if (!isset($_POST["name"]) && !isset($_POST["email"])) {
echo "</div>\n";
  /************* end heading *************/
echo "<input type=\"submit\" style=\"text-decoration: none; border: none; background-color: black; -moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius:8px; box-shadow: 0px 6px 6px 0px rgba(0,0,0,0.2); font-weight: bold; font-size: 120%; color: white;\" name=\"submit\" value=\"Submit your name &amp; e-mail to proceed\"><br />\n";  
//echo "<input type=\"submit\" style=\"text-decoration: underline; border: none; background-color: white; font-weight: bold; color: green;\" name=\"submit\" value=\"Enter your name &amp; e-mail to proceed\"><br />\n";  
//echo "<input type=\"submit\" style=\"text-decoration: underline; border: none; background-image: linear-gradient(to bottom right, #96ceb4, #454140);; font-weight: bold; color: white;\" name=\"submit\" value=\"Enter your name &amp; e-mail to proceed\"><br />\n";  
echo "</form>\n";
} // if (!isset($_POST["name"]) && !isset($_POST["email"]))


// STEP 2
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["score"])) {
//var_dump($_POST[$score]);

// todo - display score here instead of at the bottom
//if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["score"])) {
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["score".$uniq_id][0])) {

// todo array? $num_qs => $posted_score
foreach ($_POST["score".$uniq_id] as $posted_score) {

${'sub_score'.$uniq_id} = ((100/(${'num_qs'.$uniq_id}+1))*($posted_score));
${'sub_score'.$uniq_id} = (round(${'sub_score'.$uniq_id}, 1)); // round up to avoid decimals
echo "<meter value=$posted_score min=\"0\" low=".((${'num_qs'.$uniq_id}+1)/2)." max=".(${'num_qs'.$uniq_id}+1)."></meter> ".${'sub_score'.$uniq_id}."% ";
echo $exercise_type." ".$exercise_name." (".$selection_number.")<br />\n";
} // foreach ($_POST["score".$uniq_id] as $posted_score)
} 

echo "Well-done! An e-mail has been sent to ".$email." with provisional results.<br />You can check your answers below.<br />\n";
echo "</div>\n";
  /************* end heading *************/
} // if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["score"]))


// STEP 3
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (isset($_POST["name"]) && isset($_POST["email"]) && empty($_POST["question_name"]) && empty($_POST["score"])) {

if (isset($_POST["name"]) && isset($_POST["email"]) && !isset($_POST["score"])) {
echo "Complete the test.<br />\nClick <strong>submit (at the bottom)</strong> to receive an e-mail with your provisional score &amp; answers.<br />\n";
}
echo "</div>\n";
  /************* end heading *************/

// DISPLAY TEST
echo "<div class=\"flex-container\">";

// START LOOP
foreach (${'xml'.$test}->sbook_test_mcq as $sbook_test_mcq) {
echo "<div class=\"column_test\">";

$path_to_csv = trim($sbook_test_mcq->path_to_csv);
$uniq_id = trim(preg_replace("/[^\da-z]/i", '',mb_substr($path_to_csv, 0, 60)));
//echo $uniq_id;

if (!empty($path_to_csv)) {
//echo "<ol class=\"zebra\">";
echo "<ol>";
$file = $path_to_csv;

//read first line
$first_line = file($file);
list($exercise_type, $exercise_name, $selection_number, $instructions) = explode(";", $first_line[0]);
//echo "<em>".$first_line[0]."</em><br />";
//echo "<img valign=\"bottom\" src=\"pix/icons8-drill-100.png\" width=\"35\" border=\"0\" alt=\"controlled practice\"> <h3>".$exercise_type."</h3> - ";
if ($sbook_test_mcq->exercise_nr[0] != null) {
echo "<h3><span class=\"sbook_exercise_no\">".$sbook_test_mcq->exercise_nr . "</span></h3> ";
}
echo "<h3>".$exercise_type."</h3> (".$selection_number.")";
echo "<h5>".$exercise_name."</h5><br />";
echo "<style=\"font-size:70%\"><em>".$instructions."</em></font><br /><br />";

//read first line, but do nothing with it
$handle = fopen($file, "r");
$line = fgets($handle);

//now read the rest of the file line by line
if ($handle) {
//$num_qs = -1; // -1 to start from 0 = mandatory for retrieving from array!
${'num_qs'.$uniq_id} = -1; // -1 to start from 0 = mandatory for retrieving from array!
//$score = 0;
${'score'.$uniq_id} = 0;

while (($line = fgets($handle, 4096)) !== false) {
//$num_qs++; // or $counter = $counter + 1;
${'num_qs'.$uniq_id}++; // or $counter = $counter + 1;
list($question, $A1, $A2, $A3, $answer) = explode(";", $line);

echo "<br />\n";

echo "<li>".$question."<br />\n";
echo "<ol type=\"a\">";
$question_name = $uniq_id.$num_qs.trim(preg_replace("/[^\da-z]/i", '',mb_substr($question, 0, 60)));

echo "<div class=\"select select-multiple\">\n";
echo "<select name=\"".$question_name."[]\" size=\"4\" multiple=\"multiple\" tabindex=\"1\">\n";

//  echo "<li><option value=\"\">(choose one or more with Control + click)</option></li>\n";

$A1 = trim($A1);
$Aname1 = $num_qs.trim(preg_replace("/[^\da-z]/i", '',mb_substr($A1, 0, 60)));
if (!empty($A1)) {
  echo "<li><option value=\"$A1\">".$A1."</option></li>\n";
}

$A2 = trim($A2);
$Aname2 = $num_qs.trim(preg_replace("/[^\da-z]/i", '',mb_substr($A2, 0, 60)));
if (!empty($A2)) {
  echo "<li><option value=\"$A2\">".$A2."</option></li>\n";
}

$A3 = trim($A3);
$Aname3 = $num_qs.trim(preg_replace("/[^\da-z]/i", '',mb_substr($A3, 0, 60)));
if (!empty($A3)) {
  echo "<li><option value=\"$A3\">".$A3."</option></li>\n";
}
echo "</select>\n";
echo "</div>\n";

if (isset($_POST[$question_name])) {
//var_dump($_POST[$question_name]);
if (trim($_POST[$question_name][0]) != trim($answer)) {
echo "<div class=\"show_key2\">〆<strike>".($_POST[$question_name][0])."</strike><br />\n";
echo "✓ ".$answer."</div><br />\n";
}
else {
echo "<div class=\"show_key2\">✓ ".$answer."</div><br />\n";
//$score++; // or $counter = $counter + 1;
${'score'.$uniq_id}++;
}
} //if (isset($_POST[$question_name]))


echo "</ol>\n";
echo "</li>\n<br />\n";
    } //  while (($line = fgets($handle, 4096)) !== false)
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
} // if ($handle)

echo "</ol>";
}

if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["score"])) {
//echo "Score = ".$score."<br />\n";
//echo ($num_qs+1)." num_qs<br />\n";
//$sub_score = ((100/($num_qs+1))*($score));

${'sub_score'.$uniq_id} = ((100/(${'num_qs'.$uniq_id}+1))*(${'score'.$uniq_id}));
${'sub_score'.$uniq_id} = (round(${'sub_score'.$uniq_id}, 1)); // round up to avoid decimals

// KEEP FOR FUTURE ARRAY TO DISPLAY RESULTS EARLIER (outside of loop...)
echo "<textarea name=${'score'.$uniq_id} style=\"display:none;\">".${'score'.$uniq_id}."</textarea>"; // = mandatory to retrieve value in post
echo "<textarea name=${'num_qs'.$uniq_id} style=\"display:none;\">".${'num_qs'.$uniq_id}."</textarea>"; // = mandatory to retrieve value in post
echo "<textarea name=${'sub_score'.$uniq_id} style=\"display:none;\">".${'sub_score'.$uniq_id}."</textarea>"; // = mandatory to retrieve value in post


// DISPLAY RESULTS (w/in loop)
//echo "<meter value=$score min=\"0\" low=".(($num_qs+1)/2)." max=".($num_qs+1)."></meter> ".$sub_score."% ";
echo "<meter value=${'score'.$uniq_id} min=\"0\" low=".((${'num_qs'.$uniq_id}+1)/2)." max=".(${'num_qs'.$uniq_id}+1)."></meter> ".${'sub_score'.$uniq_id}."% ";
echo $exercise_type." ".$exercise_name." (".$selection_number.")<br />\n";
} 

echo "</div><!-- class column test --> \n";
} // end foreach as mcq

// start next loop here
foreach (${'xml'.$test}->sbook_test_match as $sbook_test_match) {
// todo
}

foreach (${'xml'.$test}->sbook_test_match_jumbled_definitions as $sbook_test_match_jumbled_definitions) {
// todo
}

foreach (${'xml'.$test}->sbook_test_shuffled as $sbook_test_shuffled) {
// todo
}

foreach (${'xml'.$test}->sbook_test_lis as $sbook_test_lis) {
// todo
}

foreach (${'xml'.$test}->sbook_test_wri as $sbook_test_wri) {
// todo
}

foreach (${'xml'.$test}->sbook_test_rea_wri as $sbook_test_rea_wri) {
// todo
}



echo "</div> <!-- end flex-container -->\n";

//echo "<div style=\"clear: both;\"></div>\n";

// keep just in case
//echo "Comments:<br />\n<textarea name=\"comment\" rows=\"5\" cols=\"40\">$comment</textarea><br />\n";

if (isset($_POST["name"]) && isset($_POST["email"]) && !isset($_POST["score"])) {
echo "<textarea name=\"score\" style=\"display:none;\">".$score."</textarea>"; // = mandatory to retrieve value in post
echo "<input type=\"submit\" style=\"text-decoration: none; border: none; background-color: black; -moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius:8px; box-shadow: 0px 6px 6px 0px rgba(0,0,0,0.2); font-weight: bold; font-size: 120%; color: white;\" name=\"submit\" value=\"Submit answers\"><br /><br /><br />\n";  
//echo "<input type=\"submit\" style=\"text-decoration: underline; border: none; background-color: white; font-weight: bold; color: green;\" name=\"submit\" value=\"Submit answers\"><br />\n";  
}

echo "</form>\n";
} // if (isset($_POST["name"]) && isset($_POST["email"]) && empty($_POST["score"])) 
} // if (!filter_var($email, FILTER_VALIDATE_EMAIL))

if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["score"])) {
// grand total should be here...
} 

} // if no heading else { 

// generate html copy 2/2
$name4file = trim(preg_replace("/[^\da-z]/i", '',mb_substr($name, 0, 60)));
file_put_contents("tmp_files/${date4file_name}_${test_ref}_${name4file}.html", ob_get_contents());
// end buffering and displaying page
ob_end_flush();
?>
