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

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } 

  //else {
  //  $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
  //  if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
  //    $nameErr = "Only letters and white space allowed";
  //  }
  //}
  
  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["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }
*/

} // if ($_SERVER["REQUEST_METHOD"] == "POST")

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 = $_GET["test_ref"]; // SHOULD BE DEFAULT FOR ON-LINE VERSION!!!
//http://127.0.0.1/www/ictnle.com2/pg.php?content=sbook_plugins/xml_load_quarterly_test_on_line.inc&test_ref=
//$test_ref = "quarterly_test_nzhuchkov_20240619.xml";
//$test_ref = "quarterly_test_nlmkind021_20240621.xml"; // check display sbook_test_open_cloze verb patterns (score count = OK but shows mistake when and|or)
// check display sbook_test_mcq grammar_inversion_after_negative_adverbials_selection_c1_01.csv (score count = OK but shows mistake when and|or)
//$test_ref = "quarterly_test_kasperskygroup204_20240619.xml";// check sbook_test_mcq
$test_ref = "quarterly_test_nagapova_20240613.xml"; // sbook_test_open_cloze add ignore capital letters &amp; spaces in (valid) submitted answers
//$test_ref = "quarterly_test_kasperskygroup148_20240613.xml";
//$test_ref = "quarterly_test_rrwcgroup5_20240619.xml";
//$test_ref = "quarterly_test_rrwcgroup5_20240320.xml";
//$test_ref = "quarterly_test_kasperskygroup148_20240319.xml";
//$test_ref = "quarterly_test_kasperskygroup204_20240320.xml";// check sbook_test_mcq
//$test_ref = "quarterly_test_nzhuchkov_20240318.xml"; // check why string not recognised 
//$test_ref = "quarterly_test_nlmkind021_20240315.xml";
//$test_ref = "quarterly_test_nlmkind022_20240318.xml";
//$test_ref = "quarterly_test_kasperskygroup204_20231213.xml";
//$test_ref = "quarterly_test_kasperskygroup148_20231214.xml";
//$test_ref = "quarterly_test_rrwcgroup5_20231213.xml";
//$test_ref = "quarterly_test_nlmkind022_20231213.xml";
//$test_ref = "quarterly_test_nlmkind021_20231215.xml";
//$test_ref = "quarterly_test_nzhuchkov_20231211.xml";
//$test_ref = "quarterly_test_kasperskygroup204_20230920.xml";
//$test_ref = "quarterly_test_kasperskygroup148_20230919.xml";
//$test_ref = "quarterly_test_nlmkind022_20230920.xml";
//$test_ref = "quarterly_test_kasperskyind222_20230919.xml";
//$test_ref = "quarterly_test_nlmkind021_20230919.xml";
//$test_ref = "quarterly_test_kasperskygroup204_20230920.xml";
//$test_ref = "quarterly_test_rrwcgroup5_20230920.xml";
//$test_ref = "quarterly_test_rrwcgroup5_20230614.xml";
//$test_ref = "quarterly_test_nlmkind021_20230613.xml";
//$test_ref = "quarterly_test_nlmkind022_20230614.xml";
//$test_ref = "quarterly_test_nlmkitspc40_20230608.xml";
//$test_ref = "quarterly_test_kasperskygroup204_20230614.xml";
//$test_ref = "quarterly_test_kasperskygroup148_20230615.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";
$test_log_contents ="<sbook_test>\n";
$test_log_contents = $test_log_contents."<sbook_test_ref>".${'xml'.$test}->sbook_test_name."</sbook_test_ref>\n";

echo "<div align=\"right\" style=\"font-size:70%; color: #cdcdcd;\">by D.Potter</div></div>\n";
echo "  </div>\n";

echo "<div style=\"margin-left: 35%\" align=\"left\">\n";
echo "<h2>Company: ".${'xml'.$test}->sbook_test_company. "</h2><br />\n";
$test_log_contents = $test_log_contents."<sbook_test_company>".${'xml'.$test}->sbook_test_company."</sbook_test_company>\n";
echo "<h3>Group: ".${'xml'.$test}->sbook_test_group. "</h3><br />\n";
$test_log_contents = $test_log_contents."<sbook_test_group>".${'xml'.$test}->sbook_test_group."</sbook_test_group>\n";
echo "<h3>Target level: ".${'xml'.$test}->sbook_test_level. "</h3><br />\n";
$test_log_contents = $test_log_contents."<sbook_test_level>".${'xml'.$test}->sbook_test_level."</sbook_test_level>\n";
//echo "<h3>Test date: ".${'xml'.$test}->sbook_test_date. "</h3><br /><br />\n";
echo "<h3>".($_POST["name"])."</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('Ymd_Hi');
echo "<h3>Test date: ".$date."</h3><br /><br />\n";
$test_log_contents = $test_log_contents."<sbook_test_date_submitted>".$date."</sbook_test_date_submitted>\n";
$test_log_contents = $test_log_contents."<sbook_test_date4file_name>".$date4file_name."</sbook_test_date4file_name>\n";
?>

<?php
/*** <form method="post" action="<?php echo htmlspecialchars("pg.php?content=sbook_plugins/xml_load_quarterly_test_on_line.inc&test_ref='$test_ref");?>"> ***/
// fix syntax htmlspecialchars
//echo "<form method=\"post\" action=\"htmlspecialchars('pg.php?content=sbook_plugins/xml_load_quarterly_test_on_line.inc&test_ref=$test_ref')\">\n";
//echo "<form method=\"post\" action=\"".htmlspecialchars("pg.php?content=sbook_plugins/xml_load_quarterly_test_on_line.inc&test_ref='.$test_ref.'")."\">\n";
echo "<form method=\"post\" action=\"pg.php?content=sbook_plugins/xml_load_quarterly_test_on_line.inc&test_ref=$test_ref\">\n";

  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"]); // bugs & doesn't display in e-mail
    // 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=\"name\" 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=\"".($_POST["name"])."\"></h3><br /><br />\n";
$test_log_contents = $test_log_contents."<sbook_test_student_name>".($_POST["name"])."</sbook_test_student_name>\n";
$name4file_name = trim(preg_replace("/[^\da-z]/i", '',mb_substr(($_POST["name"]), 0, 20)));
}

  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";
$test_log_contents = $test_log_contents."<sbook_test_student_email>".$email."</sbook_test_student_email>\n";
}
$test_log_contents = $test_log_contents."<sbook_test_total_score></sbook_test_total_score>\n";
$test_log_contents = $test_log_contents."<sbook_test_teacher_comments><![CDATA[]]></sbook_test_teacher_comments>\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]);

// empty - failed
//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}."% ";


// failed
//foreach ($_POST["score".$uniq_id] as $posted_score) 
foreach ($_POST["score".$uniq_id][0] 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)


// failed
// 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])) {

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";


// failed
// 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)
} 


/*********** GENERATE E-MAIL # 1 - fails *************/
// failed to implement here - see later

echo "Well-done! An e-mail has been sent to ".$email." with provisional results.<br />You can also check your answers below and print a copy.<br />\n";
echo "</div>\n";

$test_log = "tmp_files/test_log_".$name4file_name."_".$date4file_name."_".$test_ref;
$fh_test_log = fopen($test_log, 'w') or die("can't open file $test_log");

  /************* 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) {
$test_log_contents = $test_log_contents."<sbook_test_mcq>\n";
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;
$test_log_contents = $test_log_contents."<path_to_csv>".$path_to_csv."</path_to_csv>\n";

//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> ";
}
$test_log_contents = $test_log_contents."<exercise_nr>".$sbook_test_mcq->exercise_nr."</exercise_nr>\n";

echo "<h3>".$exercise_type."</h3> (".$selection_number.")";
$test_log_contents = $test_log_contents."<exercise_type>".$exercise_type."</exercise_type>\n";
$test_log_contents = $test_log_contents."<selection_number>".$selection_number."</selection_number>\n";

echo "<h5>".$exercise_name."</h5><br />";
$test_log_contents = $test_log_contents."<exercise_name>".$exercise_name."</exercise_name>\n";

echo "<style=\"font-size:70%\"><em>".$instructions."</em></font><br /><br />";
$test_log_contents = $test_log_contents."<instructions><![CDATA[\n".$instructions."]]></instructions>\n";

//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) {
$test_log_contents = $test_log_contents."<qa>\n";
${'num_qs'.$uniq_id}++; // or $counter = $counter + 1;
$test_log_contents = $test_log_contents."<qn>".${'num_qs'.$uniq_id}."</qn>\n";
list($question, $A1, $A2, $A3, $answer) = explode(";", $line);

echo "<br />\n";

echo "<li>".$question."<br />\n";
$test_log_contents = $test_log_contents."<qs><![CDATA[".$question."]]></qs>\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=\"3\" 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";
$test_log_contents = $test_log_contents."<ans>".$A1."</ans>\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";
$test_log_contents = $test_log_contents."<ans>".$A2."</ans>\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";
$test_log_contents = $test_log_contents."<ans>".$A3."</ans>\n";
}
echo "</select>\n";
echo "</div>\n";
$test_log_contents = $test_log_contents."<true>".$answer."</true>\n";

$test_log_contents = $test_log_contents."<submitted_answer>".($_POST[$question_name][0])."</submitted_answer>\n"; // associative array [$question_name] [0]
//$test_log_contents = $test_log_contents."<submitted_answer>".($_POST[$question_name])."</submitted_answer>\n"; // simple array [$question_name]

if (isset($_POST[$question_name])) {
//var_dump($_POST[$question_name]);

// 20240314
$question_name2 = preg_replace('/\s+/', '', (trim($_POST[$question_name][0])));
$answer2 = preg_replace('/\s+/', '', $answer);
// if(!preg_match_all('/\A'.$answer2.'\z/',$question_name2)) {
if(!preg_match_all('/\A'.$answer2.'\zi/',$question_name2)) {

//20240314 old
// 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";
$test_log_contents = $test_log_contents."<score>0</score>\n";
}
else {
echo "<div class=\"show_key2\">✓ ".$answer."</div><br />\n";
//$score++; // or $counter = $counter + 1;
${'score'.$uniq_id}++;
$test_log_contents = $test_log_contents."<score>".${'score'.$uniq_id}."</score>\n";
} //if (isset($_POST[$question_name]))
}
if (!isset($_POST[$question_name])) {
$test_log_contents = $test_log_contents."<score>0</score>\n";
} // if (!isset($_POST[$question_name]))

echo "</ol>\n";
echo "</li>\n<br />\n";
$test_log_contents = $test_log_contents."</qa>\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"])) {

${'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";
$test_log_contents = $test_log_contents."<sub_score>".${'sub_score'.$uniq_id}."</sub_score>\n";
} 

echo "</div><!-- class column test --> \n";
$test_log_contents = $test_log_contents."</sbook_test_mcq>\n";
} // end foreach as mcq



foreach (${'xml'.$test}->sbook_test_open_cloze as $sbook_test_open_cloze) {
$test_log_contents = $test_log_contents."<sbook_test_open_cloze>\n";
echo "<div class=\"column_test\">";

$path_to_csv = trim($sbook_test_open_cloze->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;
$test_log_contents = $test_log_contents."<path_to_csv>".$path_to_csv."</path_to_csv>\n";

//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_open_cloze->exercise_nr[0] != null) {
echo "<h3><span class=\"sbook_exercise_no\">".$sbook_test_open_cloze->exercise_nr . "</span></h3> ";
}
$test_log_contents = $test_log_contents."<exercise_nr>".$sbook_test_open_cloze->exercise_nr."</exercise_nr>\n";

echo "<h3>".$exercise_type."</h3> (".$selection_number.")";
$test_log_contents = $test_log_contents."<exercise_type>".$exercise_type."</exercise_type>\n";
$test_log_contents = $test_log_contents."<selection_number>".$selection_number."</selection_number>\n";

echo "<h5>".$exercise_name."</h5><br />";
$test_log_contents = $test_log_contents."<exercise_name>".$exercise_name."</exercise_name>\n";

echo "<style=\"font-size:70%\"><em>".$instructions."</em></font><br /><br />";
$test_log_contents = $test_log_contents."<instructions><![CDATA[\n".$instructions."]]></instructions>\n";

//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) {
$test_log_contents = $test_log_contents."<qa>\n";
//$num_qs++; // or $counter = $counter + 1;
${'num_qs'.$uniq_id}++; // or $counter = $counter + 1;
$test_log_contents = $test_log_contents."<qn>".${'num_qs'.$uniq_id}."</qn>\n";
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, 100)));

$test_log_contents = $test_log_contents."<qs>".$question."</qs>\n";
if (!isset($_POST[$question_name])) {
echo "<li>\n";
echo "<ol type=\"a\">";

//echo "<textarea name=\"".$question_name."\" rows=\"2\" cols=\"50\" style=\"background-color: efefef;\"></textarea><br />\n"; 
$question_block = "<input type=\"text\" name=\"".$question_name."\" value=\"\" style=\"width: 60%; background-color: #defdef;\"> &nbsp;"; 
$question_block = preg_replace('/\[ \]/', $question_block, $question);
echo $question_block;
}
$test_log_contents = $test_log_contents."<true>".$answer."</true>\n";

if (isset($_POST[$question_name])) {
echo "<li>".$question."<br />\n";
echo "<ol type=\"a\">";
//echo "<textarea name=\"".$question_name."\" rows=\"4\" cols=\"60\" style=\"background-color: efefef;\">".($POST_[$question_name])."</textarea><br />\n"; 
//$question2 = preg_replace('/^<br \/>\z/', '', $question);
//echo "qs 2".$question2."<hr />\n";
//$question3 = preg_replace('/\[/', '', $question2);
//$question3 = preg_replace('/\]/', '', $question3);
//echo "qs 3".$question3."<hr />\n";

$question_name2 = preg_replace('/\s+/', '', (trim($_POST[$question_name])));
$answer2 = preg_replace('/\s+/', '', $answer);

$test_log_contents = $test_log_contents."<submitted_answer>".($_POST[$question_name])."</submitted_answer>\n";

// 20240621-1111 todo update display 
// see xml_load_quarterly_test_logs.inc
//if((!preg_match_all('/'.$question2.'.*'.$question3.'\A'.$answer2.'\z/',$question_name2)) || (!preg_match_all('/'.$question3.'\A'.$answer2.'\z/',$question_name2))|| (!preg_match_all('/\A'.$answer2.'\z/',$question_name2))) 

// if(!preg_match_all('/\A'.$answer2.'\z/',$question_name2)) {
if(!preg_match_all('/\A'.$answer2.'\zi/',$question_name2)) {
echo "<div class=\"show_key2\">〆<strike>".($_POST[$question_name])."</strike><br />\n";
echo "✓ ".$answer."</div><br />\n";
$test_log_contents = $test_log_contents."<score>0</score>\n";
}
else {
echo "<div class=\"show_key2\">✓ ".$answer."</div><br />\n";
//$score++; // or $counter = $counter + 1;
${'score'.$uniq_id}++;
$test_log_contents = $test_log_contents."<score>".${'score'.$uniq_id}."</score>\n";
}
} //if (isset($_POST[$question_name]))

if (!isset($_POST[$question_name])) {
$test_log_contents = $test_log_contents."<score>0</score>\n";
} // if (!isset($_POST[$question_name]))

echo "</ol>\n";
echo "</li>\n<br />\n";
$test_log_contents = $test_log_contents."</qa>\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"])) {

${'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'.$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";
$test_log_contents = $test_log_contents."<sub_score>".${'sub_score'.$uniq_id}."</sub_score>\n";
} 

echo "</div><!-- class column test --> \n";
$test_log_contents = $test_log_contents."</sbook_test_open_cloze>\n";
} // end foreach (${'xml'.$test}->sbook_test_open_cloze as $sbook_test_open_cloze) 




foreach (${'xml'.$test}->sbook_test_cloze_sentence as $sbook_test_cloze_sentence) {
$test_log_contents = $test_log_contents."<sbook_test_cloze_sentence>\n";
echo "<div class=\"column_test\">";

$path_to_csv = trim($sbook_test_cloze_sentence->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;
$test_log_contents = $test_log_contents."<path_to_csv>".$path_to_csv."</path_to_csv>\n";

//read first line
$first_line = file($file);
list($exercise_type, $exercise_name, $selection_number, $instructions) = explode(";", $first_line[0]);
if ($sbook_test_cloze_sentence->exercise_nr[0] != null) {
echo "<h3><span class=\"sbook_exercise_no\">".$sbook_test_cloze_sentence->exercise_nr . "</span></h3> ";
}
$test_log_contents = $test_log_contents."<exercise_nr>".$sbook_test_cloze_sentence->exercise_nr."</exercise_nr>\n";

echo "<h3>".$exercise_type."</h3> (".$selection_number.")";
$test_log_contents = $test_log_contents."<exercise_type>".$exercise_type."</exercise_type>\n";
$test_log_contents = $test_log_contents."<selection_number>".$selection_number."</selection_number>\n";

echo "<h5>".$exercise_name."</h5><br />";
$test_log_contents = $test_log_contents."<exercise_name>".$exercise_name."</exercise_name>\n";

echo "<style=\"font-size:70%\"><em>".$instructions."</em></font><br /><br />";
$test_log_contents = $test_log_contents."<instructions><![CDATA[\n".$instructions."]]></instructions>\n";
//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'.$uniq_id} = -1; // -1 to start from 0 = mandatory for retrieving from array!
${'score'.$uniq_id} = 0;

while (($line = fgets($handle, 4096)) !== false) {
$test_log_contents = $test_log_contents."<qa>\n";
${'num_qs'.$uniq_id}++; // or $counter = $counter + 1;
$test_log_contents = $test_log_contents."<qn>".${'num_qs'.$uniq_id}."</qn>\n";
list($question, $A1, $A2, $A3, $answer) = explode(";", $line); // todo should be only 2 fields - fix csv first

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, 100)));

echo "<li>\n";
$test_log_contents = $test_log_contents."<qs><![CDATA[".$question."]]></qs>\n";
if (!isset($_POST[$question_name])) {
//echo "<ol type=\"a\">";
echo "<textarea name=\"".$question_name."\" rows=\"2\" cols=\"50\" style=\"background-color: #defccc;\">".$question."</textarea>\n"; 
}
$test_log_contents = $test_log_contents."<true>".$answer."</true>\n";

if (isset($_POST[$question_name])) {
echo $question."<br />\n";
echo "<ol type=\"a\">";
$question_name2 = preg_replace('/\s+/', '', (trim($_POST[$question_name])));
$answer2 = preg_replace('/\s+/', '', $answer);
//$answer2 = preg_replace('/\[/', '', $answer2); // 20231214
//$answer2 = preg_replace('/\]/', '', $answer2); // 20231214

$test_log_contents = $test_log_contents."<submitted_answer>".($_POST[$question_name])."</submitted_answer>\n";

//if(!preg_match_all('/\A'.$answer2.'\z/',$question_name2)) {
if(!preg_match_all('/\A'.$answer2.'\zi/',$question_name2)) {
echo "<div class=\"show_key2\">〆<strike>".($_POST[$question_name])."</strike><br />\n";
echo "✓ ".$answer."</div><br />\n";
$test_log_contents = $test_log_contents."<score>0</score>\n";
}
else {
echo "<div class=\"show_key2\">✓ ".$answer."</div><br />\n";
${'score'.$uniq_id}++;
$test_log_contents = $test_log_contents."<score>".${'score'.$uniq_id}."</score>\n";
}
echo "</ol>\n";
} //if (isset($_POST[$question_name]))

if (!isset($_POST[$question_name])) {
$test_log_contents = $test_log_contents."<score>0</score>\n";
} // if (!isset($_POST[$question_name]))

echo "</li>\n";
$test_log_contents = $test_log_contents."</qa>\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"])) {

${'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";
$test_log_contents = $test_log_contents."<sub_score>".${'sub_score'.$uniq_id}."</sub_score>\n";
} 

echo "</div><!-- class column test --> \n";
$test_log_contents = $test_log_contents."</sbook_test_cloze_sentence>\n";
} // end foreach (${'xml'.$test}->sbook_test_cloze as $sbook_test_cloze_sentence)




foreach (${'xml'.$test}->sbook_test_match as $sbook_test_match) {
$test_log_contents = $test_log_contents."<sbook_test_match>\n";
echo "<div class=\"column_test\">";

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

if (!empty($path_to_csv)) {
echo "<ol>";
$file = $path_to_csv;
$test_log_contents = $test_log_contents."<path_to_csv>".$path_to_csv."</path_to_csv>\n";

//read first line
$first_line = file($file);
list($exercise_type, $exercise_name, $selection_number, $instructions) = explode(";", $first_line[0]);

if ($sbook_test_match->exercise_nr[0] != null) {
echo "<h3><span class=\"sbook_exercise_no\">".$sbook_test_match->exercise_nr . "</span></h3> ";
}
$test_log_contents = $test_log_contents."<exercise_nr>".$sbook_test_match->exercise_nr."</exercise_nr>\n";

echo "<h3>".$exercise_type."</h3> (".$selection_number.")";
$test_log_contents = $test_log_contents."<exercise_type>".$exercise_type."</exercise_type>\n";
$test_log_contents = $test_log_contents."<selection_number>".$selection_number."</selection_number>\n";

echo "<h5>".$exercise_name."</h5><br />";
$test_log_contents = $test_log_contents."<exercise_name>".$exercise_name."</exercise_name>\n";

echo "<style=\"font-size:70%\"><em>".$instructions."</em></font><br /><br />";
$test_log_contents = $test_log_contents."<instructions><![CDATA[\n".$instructions."]]></instructions>\n";


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

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

    while (($line_match = fgets($handle_match, 4096)) !== false) {
$test_log_contents = $test_log_contents."<qa>\n";
${'num_qs'.$uniq_id}++; // or $counter = $counter + 1;
$test_log_contents = $test_log_contents."<qn>".${'num_qs'.$uniq_id}."</qn>\n";
list($question, $answer) = explode(";", $line_match);
$word_to_scramble = $question;
include ("sbook_plugins/scramble_words.inc");

$test_log_contents = $test_log_contents."<qs><![CDATA[".$scrambled_word."]]></qs>\n";
$search = $question;
$lines_to_number = str_replace("$search", '<span class="sbook_scrambled_word">'.$scrambled_word.'</span><!--<span class="show_key_sbook">'.$word_to_scramble.'</span>-->', $question);
//
//$question = $lines_to_number;
$scrambled_word = $lines_to_number;
$question_name = $uniq_id.$num_qs.trim(preg_replace("/[^\da-z]/i", '',mb_substr($question, 0, 100)));

if (!isset($_POST[$question_name])) {

//echo "<li>".$scrambled_word."<br />".$answer."<br /><br /><textarea name=\"".$question_name."\" rows=\"2\" cols=\"30\" style=\"background-color: #defdef;\"></textarea></li><br />\n"; 

$question_block = "<input type=\"text\" name=\"".$question_name."\" value=\"\" style=\"width: 50%; background-color: #defdef;\"> &nbsp;"; 
echo "<li>".$scrambled_word."<br />".$answer."<br /><br />".$question_block."</li><br />\n";

} // if (!isset($_POST[$question_name]))

$test_log_contents = $test_log_contents."<ans>".$answer."</ans>\n";
$test_log_contents = $test_log_contents."<true>".$word_to_scramble."</true>\n";
$test_log_contents = $test_log_contents."<submitted_answer>".($_POST[$question_name])."</submitted_answer>\n";

if (isset($_POST[$question_name])) {
echo "<li>\n";
$question_name2 = preg_replace('/\s+/', '', (trim($_POST[$question_name])));
//$answer2 = preg_replace('/\s+/', '', $answer);
$answer2 = preg_replace('/\s+/', '', $question);

//if(!preg_match_all('/\A'.$answer2.'\z/',$question_name2)) { // case sensitive
if(!preg_match_all('/\A'.$answer2.'\zi/',$question_name2)) { // i = ignore case
echo "<div class=\"show_key2\">〆<strike>".($_POST[$question_name])."</strike><br />\n";
echo "✓ ".$question."<br />\n";
echo "= ".$answer."</div><br />\n";
$test_log_contents = $test_log_contents."<score>0</score>\n";
}
else {
//echo "<div class=\"show_key2\">✓ ".$answer."</div><br />\n";
echo "<div class=\"show_key2\">✓ ".$question."<br />\n";
echo "= ".$answer."</div><br />\n";
//$score++; // or $counter = $counter + 1;
${'score'.$uniq_id}++;
$test_log_contents = $test_log_contents."<score>".${'score'.$uniq_id}."</score>\n";
}
echo "</li>\n";
} //if (isset($_POST[$question_name]))

if (!isset($_POST[$question_name])) {
$test_log_contents = $test_log_contents."<score>0</score>\n";
} // if (!isset($_POST[$question_name]))

$test_log_contents = $test_log_contents."</qa>\n";
    } // while (($line_match = fgets($handle_match, 4096)) !== false)
    if (!feof($handle_match)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle_match);
} // if ($handle_match)

echo "</ol>";
}

if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["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";
$test_log_contents = $test_log_contents."<sub_score>".${'sub_score'.$uniq_id}."</sub_score>\n";
} 

echo "</div><!-- class column test --> \n";
$test_log_contents = $test_log_contents."</sbook_test_match>\n";
} // foreach (${'xml'.$test}->sbook_test_match as $sbook_test_match)





foreach (${'xml'.$test}->sbook_test_wri as $sbook_test_wri) {
echo "<div class=\"column_test\">\n";
$test_log_contents = $test_log_contents."<sbook_test_wri>\n";

${'sbook_test_wri'.$uniq_id} = trim(preg_replace("/[^\da-z]/i", '',mb_substr($sbook_test_wri->exercise_nr.$sbook_test_wri->exercise_name.$sbook_test_wri->topics_for_wri, 0, 100)));

if ($sbook_test_wri->exercise_nr[0] != null) {
echo "<h3><span class=\"sbook_exercise_no\">".$sbook_test_wri->exercise_nr . "</span></h3> ";
}
$test_log_contents = $test_log_contents."<exercise_nr>".$sbook_test_mcq->exercise_nr."</exercise_nr>\n";
$test_log_contents = $test_log_contents."<exercise_type>".$exercise_type."</exercise_type>\n";
$test_log_contents = $test_log_contents."<selection_number>".$selection_number."</selection_number>\n";

$exercise_name = trim($sbook_test_wri->exercise_name);
if (!empty($exercise_name)) {
echo "<h3>".$sbook_test_wri->exercise_name."</h3><br />\n";
}
$test_log_contents = $test_log_contents."<exercise_name>".$exercise_name."</exercise_name>\n";

$instructions = trim($sbook_test_wri->instructions);
if (!empty($instructions)) {
echo "    <em>".$sbook_test_wri->instructions ."</em>\n";
}
$test_log_contents = $test_log_contents."<instructions><![CDATA[\n".$instructions."]]></instructions>\n";

$topics_for_wri = trim($sbook_test_wri->topics_for_wri);
if (!empty($topics_for_wri)) {
$topics_to_recycle = $topics_for_wri;
$topics_to_recycle = preg_replace ('/^/m', '<li>', $topics_to_recycle);
$topics_to_recycle = preg_replace ('/$/m', '</li>', $topics_to_recycle);

echo "<ol class=\"zebra\" type=\"a\">\n";
echo $topics_to_recycle;
echo "</ol>\n";
$test_log_contents = $test_log_contents."<topics_for_wri><![CDATA[".$topics_to_recycle."]]></topics_for_wri>\n";
}
          //.querySelector("#words_to_count_<?php echo ${'sbook_test_wri'.$uniq_id} ? >")
            //document.querySelector("#show_word_count_<?php echo ${'sbook_test_wri'.$uniq_id} ? >").innerText = res.length;

//            document.querySelector("#show_word_count<?php echo ${'sbook_test_wri'.$uniq_id} ? > ").innerText = res.length;
 //echo "<textarea name=\"".${'sbook_test_wri'.$uniq_id}."\" id=\"".${'sbook_test_wri'.$uniq_id}."\" rows=\"10\" cols=\"40\" style=\"background-color: efefef;\"></textarea><br />\n"; 
?>

<?php
if (!isset($_POST[${'sbook_test_wri'.$uniq_id}])) {
//echo "<textarea name=\"".${'sbook_test_wri'.$uniq_id}."\" rows=\"10\" cols=\"40\" style=\"background-color: efefef;\"></textarea><br />\n"; 
//echo "<textarea name=\"".${'sbook_test_wri'.$uniq_id}."\" id=\"words_to_count_".${'sbook_test_wri'.$uniq_id}."\" rows=\"10\" cols=\"40\" style=\"background-color: efefef;\"></textarea><br />\n"; 
echo "<textarea name=\"".${'sbook_test_wri'.$uniq_id}."\" id=\"words_to_count\" rows=\"30\" cols=\"60\" style=\"background-color: efefef;\"></textarea><br />\n"; 
//echo "Word count: <span id=\"show_word_count_".${'sbook_test_wri'.$uniq_id}."\">0</span><br />\n";
echo "Word count: <span id=\"show_word_count\">0</span><br />\n";

  } else {
          //${'sbook_test_wri'.$uniq_id} = test_input($_POST[${'sbook_test_wri'.$uniq_id}]); // bugs...
          //${'sbook_test_wri'.$uniq_id} = htmlspecialchars($_POST[${'sbook_test_wri'.$uniq_id}]);  // bugs...
} // if (!isset($_POST[${'sbook_test_wri'.$uniq_id}]))

if (isset($_POST[${'sbook_test_wri'.$uniq_id}])) {
echo "Submitted answer: <br /><textarea name=\"".${'sbook_test_wri'.$uniq_id}."\" rows=\"10\" cols=\"40\" style=\"background-color: efefef;\">".($_POST[${'sbook_test_wri'.$uniq_id}])."</textarea><br />\n"; 

//$test_log_contents = $test_log_contents."<sbook_test_wri>\n<".${'sbook_test_wri'.$uniq_id}.">\n".($_POST[${'sbook_test_wri'.$uniq_id}])."\n</".${'sbook_test_wri'.$uniq_id}.">\n</sbook_test_wri>\n";
$test_log_contents = $test_log_contents."<submitted_answer><![CDATA[\n".($_POST[${'sbook_test_wri'.$uniq_id}])."]]></submitted_answer>\n";
$test_log_contents = $test_log_contents."<suggested_answer><![CDATA[]]></suggested_answer>\n";
$test_log_contents = $test_log_contents."<key><![CDATA[".trim($sbook_test_wri->key)."]]></key>\n";
$test_log_contents = $test_log_contents."<sub_score></sub_score>\n";
$test_log_contents = $test_log_contents."</sbook_test_wri>\n";

// todo
//echo "Word count: <span id=\"show_word_count\">0</span><br />\n";

$key = trim($sbook_test_wri->key);
if (!empty($key)) {
echo "<div class=\"show_key3_to_print_for_feedback\">".$key."</div>";
}
} //if (isset($_POST[${'sbook_test_wri'.$uniq_id}]))

// todo?
//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 "<meter value=\"\" min=\"0\" low=\"\" max=\"\"></meter> % ";
//echo $sbook_test_wri->exercise_number." ".$exercise_name."<br />\n";

echo "</div><!-- class column test --> \n";
?>
<script>
<!--
//  https://www.geeksforgeeks.org/how-to-make-a-word-count-in-textarea-using-javascript/
        document
          .querySelector("#words_to_count")
          .addEventListener("input", function countWord() {
            let res = [];
            let str = this.value.replace(/[\t\n\r\.\?\!]/gm, " ").split(" ");
            str.map((s) => {
              let trimStr = s.trim();
              if (trimStr.length > 0) {
                res.push(trimStr);
              }
            });
            document.querySelector("#show_word_count").innerText = res.length;
          });
    // -->
    </script>


<?php
} //foreach (${'xml'.$test}->sbook_test_wri as $sbook_test_wri)


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";

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...
} 

// 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();


/*********** GENERATE E-MAIL # 2 - works only at end of file *************/
/***/
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["score"])){

//if (isset($_POST["name"]) && isset($_POST["email"]) && !empty($_POST["score".$uniq_id])) {
//if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["score".$uniq_id][0])) 
//$mailfrom = "duncan.potter@ictnle.com <ictnle.com@300gp.ovh.net>"; 
//$mailfrom = "noreply@ictnle.com <ictnle.com@300gp.ovh.net>"; 
$mailfrom = "duncanpotter@yandex.ru"; 
//$recipientEmail = "duncanpotter@yandex.ru"; //tmp while getting ready for TH
//$recipientEmail = $_POST['email'];
$recipientemail = $email;
$emailSubject = "Quarterly test - Provisional results";
$successMessage = "Message sent successfully";
//$message1   = $_POST['message1'];

	$priority = 3;
	$php_version = phpversion();
	$headers = "From: $mailfrom\n";
	$headers .= "MIME-Version: 1.0\n";
	$headers .= "Content-type: text/plain; charset=utf-8\n";
	$headers .= "X-Priority: $priority\n";
        $headers .= "X-Sender: <www.ictnle.com>\n"; 
	$headers .= "X-Mailer: PHP $php_version\n";
        $headers .= "X-auth-smtp-user: duncan.potter@ictnle.com\n";
        $headers .= "X-abuse-contact: duncan.potter@ictnle.com\n"; 
        //$headers .= "Bcc: duncan.potter@ictnle.com\n";
        $headers .= "Bcc: duncanpotter@yandex.ru\n";
        $subject = $emailSubject." - Company: ".${'xml'.$test}->sbook_test_company." - Group: ".${'xml'.$test}->sbook_test_group." by " .$name ." (".$date.")";
	//$to_email = $recipientemail. ", duncan.potter@ictnle.com";
	$to_email = $recipientemail;
//        $content = $message1.$message2.$message3.$message4;

//$content = "You may find a copy of your submitted test here: <a href=\"www.ictnle.com/tmp_files/${date4file_name}_${test_ref}_${name4file}.html\"></a>\n";        
//$content = "<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}."% ".$exercise_type." ".$exercise_name." (".$selection_number.")<br /><hr />\n". ("tmp_files/${date4file_name}_${test_ref}_${name4file}.html");

$file = ("tmp_files/${date4file_name}_${test_ref}_${name4file}.html");
$email_contents = file_get_contents($file); // string
//var_dump ($email_contents);
$email_contents = strip_tags($email_contents,['h1', 'h2', 'h3','h4', 'h5', 'br', 'em', 'meter', 'input', 'ol', 'li', 'strike', 'a']);

mail($to_email, $subject, $email_contents, $headers);

// debug only
//echo "E-mail contents: <br />\n";
//echo $email_contents."<hr />\n"; // should fail to display in browser

//$email_contents2 = file($file); // array
//foreach ($emails_contents2 as $line) {
//echo $line."<hr />\n";
//}

} // if(isset($_POST['submit']))

} // if no heading else { 

if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["score"])) {
$test_log_contents = $test_log_contents."</sbook_test>\n";
fwrite($fh_test_log, $test_log_contents) or die ("can't run fwrite");
fclose($fh_test_log) or die("can't fclose fh");
} // if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["score"]))

?>
