<?php
  require 'include/head.inc';
  require 'include/session.inc';
  require 'include/common.inc';

  if ( ! isset($SESSIONS_next) ) {
    block("red", "submission closed");
    exit;
  }

  if(isset($_POST['submit']) && $_POST['mnumber']!="") {
    require 'include/usercheck.inc';

    $exchecked = $_POST['exchecked'];

    $mnumber = $_POST['mnumber'];
    $sessionid = $SESSIONS[$SESSIONS_next]['id'];

    if($db->query("SELECT COUNT(*) FROM workdone WHERE mnumber = $mnumber AND session = $sessionid")->fetch(PDO::FETCH_NUM)[0] == 1) {
      $db->query("DELETE FROM workdone WHERE mnumber = $mnumber AND session = $sessionid");
      print '<table bgcolor="lightgreen">';
        print '<tr><th><b><font color="white">deleted old submission</font></b></th><tr>';
      print '</table>';
    }

    $excount = count($exchecked);
    $donestring = implode(',', $exchecked);

    $db->query("INSERT INTO workdone (mnumber,session,manydone,thisdone) 
        VALUES (\"$mnumber\", \"$sessionid\", \"$excount\", \"$donestring\")");

    print '<table bgcolor="lightgreen">';
      print '<tr><th><b><font color="white">submitted</font></b></th><tr>';
    print '</table>';
    exit;
  }

?>

  <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <table bgcolor="black">
    <tr><th><b><font color="white">submit examples for <?php echo $SESSIONS[$SESSIONS_next]['timestr']; ?></font></b></th><tr>
  </table>

  <table>
    <tr>  
      <th align="left">Mat.nummer:</th> <th align="left"><input type="text" name="mnumber"></th>
    </tr>
    <tr>  
      <th align="left">Password:</th> <th align="left"><input type="text" name="password"></th>
    </tr>
 
    <tr><th colspan=2></th></tr>

    <tr>
      <th align="left">Examples:</th>
      <th>

        <?php
          $exnum=0;
 	  foreach (explode(",",$SESSIONS[$SESSIONS_next]['examples']) as $exid) {
 	    print " <input type='checkbox' name='exchecked[]' value=$exid>$exid ";
	    $exnum++;
	    if ($exnum%3 == 0) { print ""; }
	  }
        ?>
      </th>	
    </tr>

    <tr><th colspan=2></th></tr>

    <tr>
      <th align="left"><input type="submit" name="submit" value="Submit"></th> <th></th>
    </tr>
  </table>
</form>