<html>
<head>
  <link rel="stylesheet" type="text/css" href="../CSS/styles.css">
  <?php
    $id = 0; $editing="";
    if(isset($_GET['id']))$id=$_GET['id'];
    if(isset($_GET['editing']))$editing=$_GET['editing'];
    if(isset($_GET['submittedpreviously']))$submittedpreviously=$_GET['submittedpreviously'];
  ?>
  <script>
    function focus_on_name(){document.getElementById('name').select();}
    function focus_on_me(i){
      // if (document.activeElement.id != i)
        document.getElementById(i).select();
    }
    function validate(){
      var str_2_test = document.getElementById('purpose').value;
      var regex      = /^[-\s\.\,a-zA-Z0-9]*$/;
      var result = regex.test(str_2_test);
      if(result == false){
        alert ("Incorrect format for Purpose. Only alphanumerics, hyphen, comma and space allowed.");
        return false;
      }
      return true;
    }
    function submit_form(){
        validate();
        if(validate())document.getElementById('editmodel').submit();
    }
  </script>
  <style>
    /* for some reason textarea is not referencing style sheet */
    textarea{
      font-size:0.8em;
      font-family: Source Sans Pro, sans-serif;
    }
  </style>
</head>
<body onload = "focus_on_name()" style="background-color:white;">
  <?php include "header.php";
    if($editing == "estate"){
      if(isset($_GET['action'])){
        mysqli_query($con,"UPDATE estates SET name = \"{$_POST['name']}\" WHERE id = {$id}");
        mysqli_query($con,"UPDATE estates SET type = {$_POST['etype']} WHERE id = {$id}");
        header("location: ../index.php");
      }
      $res = mysqli_query($con,"SELECT COUNT(type) FROM estate_types;");
      $row = mysqli_fetch_array($res);
	    $selectsize = $row[0];
      $res = mysqli_query($con,"SELECT name,type FROM estates WHERE id = {$id}");
      $row = mysqli_fetch_array($res);
      $name = $row['name'];
	    $type = $row['type'];
      echo ("
        <div id='col-container'>
        <form method='post' action='edit_estate_or_model.php?id={$id}&editing={$editing}&action=doit'>
          <table>
            <tr>
              <td class='small-text grey-text'>Name</td><td><input class='small-text grey-text' id='name' type='text'
                maxlength='240' pattern='[A-Za-z#\s$@0-9._+-]{2,48}' title='Minimum 2 characters and only alphanumerics _ . # $ - + space and @ allowed.'
                value='{$name}' required name='name' size='90' onclick=focus_on_me('name') autofocus>
              </td>
            </tr>
			<tr>
			  <td class='small-text grey-text'>Type</td>
			  <td><select class='small-text grey-text' name='etype' size='{$selectsize}'onchange='if(this.value != 0) {this.form.submit();}'>");
     	  	  $res = mysqli_query($con,"SELECT id,type FROM estate_types");
         	  while($row = mysqli_fetch_array($res))echo("<option value='{$row[0]}'>{$row[1]}</option>");
              echo("
			  </td>
			</tr>
          </table>
          <input type='submit' disabled hidden />
        </form>
        </div>
      ");
    }elseif($editing == "model"){
      if(isset($_GET['action'])){
        $err = 0;
        $filename = $_FILES["tarball"]["name"];
        $picturename = $_FILES["picture"]["name"];
        if($filename != "" && is_string($filename)){
          $path_parts = pathinfo($filename);
          $filename_only = $path_parts['basename'];
          if(is_unique_str($con,$filename_only,"tarball","models")){
            $filename_only = $path_parts['basename'];
          }else{
            $dt_now = new DateTime();
            $filename_only = $dt_now->format('ymdHis') . $path_parts['basename'];
          }
          $tmpname = $_FILES['tarball']['tmp_name'];
          $md5sum = md5_file($tmpname);
          $tarball_file_n_path = $proj_file_path . $filename_only;
          if(move_uploaded_file($_FILES["tarball"]["tmp_name"],$tarball_file_n_path)){
            mysqli_query($con,"UPDATE MODELS SET tarball=\"{$filename_only}\", md5=\"{$md5sum}\" WHERE id={$id}");
          }else{
            $err = 1;
          }
          // }else{
          //   echo ("<h1>Filename {$filename_only} is already in use, use another file name. Aborting ... Use browser back button to proceed</h1>");
          //   exit;
          // }
        }
        if($picturename != "" && is_string($picturename)){
          $picfile = "../Images/model{$id}.jpg";
          if(move_uploaded_file($_FILES["picture"]["tmp_name"],$picfile)){
            // do nothing
          }else{
            $err = 1;
          }
        }
        // purpose is textarea type input and needs to be validated

        mysqli_query($con,"UPDATE MODELS SET name=\"{$_POST['name']}\",author=\"{$_POST['author']}\",purpose=\"{$_POST['purpose']}\" WHERE id={$id}");
        if($err != 0){
          echo ("Error: There was a problem with the upload contact your system provider"); exit;
        }

        // if user revised model after test was suspended then set the same test to start again
        if(isset($_GET['submittedpreviously'])){
          date_default_timezone_set("Europe/London");
          $dt = date("d/m/Y h:i:s");
          $res = mysqli_query($con,"UPDATE results SET result=0,requested_at='{$dt}' WHERE id = {$submittedpreviously}");
          header("location: ../dashboard.php");
        }else{
          header("location: ../index.php");
        }

      }else{
        $res = mysqli_query($con,"SELECT name,tarball,author,purpose FROM models WHERE id = {$id}");
        $row = mysqli_fetch_array($res);
        $name = $row['name'];
        $tarball = $row['tarball'];
        $author = $row['author'];
        $purpose = $row['purpose'];
        echo ("
          <div id='col-container'>"
        );
        if(isset($_GET['submittedpreviously'])){
          echo ("<form method='post' id='editmodel' action='edit_estate_or_model.php?id={$id}&editing={$editing}&action=doit&submittedpreviously={$submittedpreviously}' enctype='multipart/form-data'>");
        }else{
          echo ("<form method='post' id='editmodel' action='edit_estate_or_model.php?id={$id}&editing={$editing}&action=doit' enctype='multipart/form-data'>");
        }
        echo ("
          <table>
            <tr>
              <td class='small-text grey-text'>Name
              </td>
              <td><input class='small-text grey-text' id='name'   required type='text' value='{$name}'
                  name='name'    size='90' onclick=focus_on_me('name') autofocus placeholder='240 characters'
                  maxlength='240' pattern='[A-Za-z#\s$@0-9._+-]{2,48}' title='Minimum 2 characters and only alphanumerics _ . # $ - + space and @ allowed.'>
              </td>
            </tr>
            <tr>
              <td class='small-text grey-text'>File
              </td>
              <td class='small-text grey-text'>
                  <input id='tarball' type='file' value='{$tarball}' style= 'cursor:pointer;' class='medium-text grey-text'
                  name='tarball' title='Expecting tar.gz file'>");
                  if(is_string($tarball) && $tarball != "")echo("currently uploaded <a class='grey-text' href='download.php?tarball={$tarball}'>{$tarball}</a>");
                  echo("
              </td>
            </tr>
            <tr>
              <td class='small-text grey-text'>Image
              </td>
              <td class='small-text grey-text'>
                  <input id='picture' type='file' value='{$id}.jpg' style= 'cursor:pointer;' class='medium-text grey-text'
                  name='picture' title='Expecting jpg file'>");
                  if(file_exists("../Images/model{$id}.jpg"))echo("currently uploaded <a class='grey-text' href='../Images/model{$id}.jpg'>image</a>");
                  echo("
              </td>
            </tr>
            <tr>
              <td class='small-text grey-text'>Author
              </td>
              <td><input class='small-text grey-text' id='author'  type='text' value='{$author}'
                  name='author'  size='90' onclick=focus_on_me('author') placeholder='240 characters'
                  maxlength='240' pattern='[A-Za-z#\s$@0-9._+-]{2,48}' title='Minimum 2 characters and only alphanumerics _ . # $ - + space and @ allowed.'>
              </td>
            </tr>
            <tr>
              <td class='small-text grey-text'>Purpose
              </td>
              <td><textarea class='small-text grey-text' id='purpose' rows='5' cols='75'
                  name='purpose' onclick=focus_on_me('purpose') placeholder='480 characters' onfocusout='validate()'
                  maxlength='480' pattern='[A-Za-z#\s$@0-9._+-]{2,48}' title='Minimum 2 characters and only alphanumerics _ . # $ - + space and @ allowed.'>{$purpose}</textarea>
              </td>
            </tr>
          </table>
          <!--<input type='submit' value='OK'/>-->
          <input action='action' onclick='window.history.go(-1); return false;'  style='cursor:pointer;' class='medium-text grey-text' type='button' value='Back' />
          <input type='button' onclick='submit_form()' style='cursor:pointer; position:absolute' class='medium-text grey-text' value='OK'>
          </form>
          </div>
        ");
      }
    }
  ?>
</body>
</html>
