<?php
/* Prompt : โค้ด แบบฝึกหัด ส่งคำตอบแล้วนับคะแนนให้ ด้วย javascript
File Encoding : แฟ้ม Data เป็น ANSI, แฟ้ม Script เป็น UTF-8 ใช้ฟังก์ชัน iconv() ในการเปลี่ยน */
$file = (!isset($_REQUEST["file"])) ? 'test10math01' : htmlspecialchars($_REQUEST["file"]);
$header = '<!DOCTYPE html><html lang="th"><head><title>Exercise : '. $file .'</title><meta charset="utf-8" />
<style>input[type="radio"] { -ms-transform: scale(2); -webkit-transform: scale(2); transform: scale(2);margin-left:20px;margin-right:20px; }</style>
</head><body style="font-size:24px;font-weight:bold;background-color:#ddffff;">
<div style="width:600px;border:1px solid gray;margin-left:auto;margin-right:auto;display:block;background-color:white;">
<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
$footer = '<input type=hidden name=file value="'. $file .'"></form></div></body></html>';
$quiz_file = $file .'.txt';
/* function */
function read_quiz_data($filename) {
  $quiz_data = [];
  $handle = fopen($filename, "r");
  if ($handle) {
    while (($line = fgets($handle)) !== false) {
      /* ถ้าข้อมูลเป็น UTF-8 ก็ไม่ต้องใช้ iconv กับ $line */
      $line = iconv('TIS-620','UTF-8//ignore',$line); /* แปลงข้อมูลจาก ANSI เป็น UTF-8 */
      $data = explode("\t", trim($line));
      $quiz_data[] = $data; 
    }
    fclose($handle);
  }
  return $quiz_data;
}
function generate_quiz_html($quiz_data) {
  global $header, $footer;
  $html = $header;
  foreach ($quiz_data as $index => $ques_data) {
    $html .= '<p>' . ($index + 1) . '. ' . $ques_data[1] . '</p>';
    for ($i = 3; $i < count($ques_data); $i++) {
      $check = ($ques_data[2] == $i - 2) ? 1 : 0;
      $html .= '<input type="radio" name="q' . $index . '" value="' . $check . '">' . $ques_data[$i] . '<br>';
    }
    $html .= "\r\n";
  }
  $html .= '<input type="submit" value="Submit" style="width:300px;height:80px;font-size:30px;margin-left:auto;margin-right:auto;display:block;">';
  $html .= $footer;
  return $html;
}
function process_quiz_responses($quiz_data, $user_answers) {
  global $file;
  $correct_answers = 0;
  $html = '';
  for ($i = 0; $i < count($quiz_data); $i++) {
    if ($user_answers['q' . $i] == 1) {
      $correct_answers++;
      $html .= "<script>alert('". 'question : ' . ($i + 1) ." : [ / ] Correct Answer!');</script>";
    } else {
      $html .= "<script>alert('". 'question : ' . ($i + 1) ." : [ X ] Wrong Answer!');</script>";
    }
  }
  $html .= "<div style='margin-left:auto;margin-right:auto;display:block;font-size:30px;background-color:#ffffdd;border:1px solid gray;width:400px;'>
  ท่านได้คะแนน $correct_answers จาก " . count($quiz_data) . " ข้อ<br/><a href='?file=". $file . "'>Back</a></div>";
  return $html;
}
/* main process */
$quiz_data = read_quiz_data($quiz_file);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  echo process_quiz_responses($quiz_data, $_POST);
} else {
  echo generate_quiz_html($quiz_data);
}
?>