<?php
// 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"]);
  }

  if (empty($_POST["Aname1"])) {
    $Aname1Err = "Aname1 is required";
  } else {
    $Aname1 = test_input($_POST["Aname1"]);
  }

  if (empty($_POST["Aname2"])) {
    $Aname2Err = "Aname2 is required";
  } else {
    $Aname2 = test_input($_POST["Aname2"]);
  }

  if (empty($_POST["Aname3"])) {
    $Aname3Err = "Aname3 is required";
  } else {
    $Aname3 = test_input($_POST["Aname3"]);
  }

  }

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('YmdHis');
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: 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: 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: 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 "</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
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\">";

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!
$score = 0;

while (($line = fgets($handle, 4096)) !== false) {
$num_qs++; // 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;
if ((isset($_POST[$question_name])) && (preg_match_all(trim($_POST[$question_name][0]), trim($answer), $matches))) {
echo "$ matches [ 0 ]: ".$matches[0]."<br />\n";
}
echo "</option></li>\n";
echo "$ post question name $ A1: ".trim($_POST[$question_name][$A1])."<br />\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;
if ((isset($_POST[$question_name])) && (preg_match_all(trim($_POST[$question_name][0]), trim($answer), $matches))) {
}
echo "</option></li>\n";
echo "$ post question name $ A2: ".trim($_POST[$question_name][$A2])."<br />\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;
if ((isset($_POST[$question_name])) && (preg_match_all(trim($_POST[$question_name][0]), trim($answer), $matches))) {
echo "<h1> ✓ </h2>";
}
echo "</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;
}
} //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>";
}

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

// start next loop here

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: 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"])) {
//echo "Score = ".$score."<br />\n";
//echo ($num_qs+1)." num_qs<br />\n";
$sub_score = ((100/($num_qs+1))*($score));
echo "<meter value=$score min=\"0\" low=".(($num_qs+1)/2)." max=".($num_qs+1)."></meter> ".$sub_score."% ";
echo $exercise_type." ".$exercise_name." (".$selection_number.")<br />\n";

} 

} // if no heading else { 

?>
