<html>
<head>
  <link rel="stylesheet" type="text/css" href="CSS/styles.css">
  <?php
    include "Pages/header.php";
  ?>
  <script>
    function email_admin(){alert("send an email to the BEMServer administrator");}
    function display_floating_menu(i){
      var j = "typeof" + i;
      var obj = document.getElementById(i);
      var objt = document.getElementById(j);
      undisplay_floating_menu();
      obj.style.display='block';
      objt.style.display='block';
    }
    function undisplay_floating_menu(){
      var el = document.getElementsByClassName('floating-menu');
      for (var i=0;i<el.length; i++)el[i].style.display = "none";
      var e2 = document.getElementsByClassName('floating-menu-noborder');
      for (var i=0;i<e2.length; i++)e2[i].style.display = "none";
    }
    function really_delete_estate(i){
      var retVal = confirm("Are you sure?");
      if(retVal == true) window.location.href = "Pages/delete_estate_or_model.php?table=estate&id="+i;
    }
    function really_delete_model(i){
      var retVal = confirm("Are you sure?");
      if(retVal == true) window.location.href = "Pages/delete_estate_or_model.php?table=model&id="+i;
    }
    function pwd_chk(){
      var pwd1 = document.getElementById("pwd1");
      var pwd2 = document.getElementById("pwd2");
      if(pwd1.value.length > 0 && pwd2.value.length > 0){
        if(pwd1.value != pwd2.value){
          pwd1.value = "";
          pwd2.value = "";
          alert("passwords do not match");
        }
      }
    }
	function logout_from_elsewhere(i){
		alert("You were previously logged in to another computer (" + i + ") and have been logged out from there now.");
	}
	function get_estate_type(){
		var x = document.getElementsByClassName('estate_types');
		x[0].style.display = 'block';
	}
  </script>
</head>
<body style="background-color:white;">
<!-- ######## -->
<!--  HEADER  -->
<!-- ######## -->
<?php
  $eid = 0;$mid=0;
  if(isset($_GET['LGE'])){
	  $lge = $_GET['LGE'];
	  if($lge != 0)echo("<script type='text/javascript'>logout_from_elsewhere(\"{$lge}\");</script>");
  }
  if(isset($_GET['id'])){
    $eid=$_GET['id'];
    $res = mysqli_query($con,"UPDATE users SET latest_estate ={$eid} WHERE id = {$user_id}");
  }else{
    $res = mysqli_query($con,"SELECT latest_estate FROM users WHERE id = {$user_id}");
    $row = mysqli_fetch_array($res);
    $eid = $row['latest_estate'];
    if(is_numeric($eid)){
      $res = mysqli_query($con,"SELECT COUNT(name) FROM estates WHERE id = {$eid}");
      $row = mysqli_fetch_array($res);
      if($row[0] != 1)$eid = 0; // reset selected estate if it has been deleted
    }
  }
  if(isset($_GET['mid'])){
    $mid=$_GET['mid'];
    $res = mysqli_query($con,"UPDATE users SET latest_model ={$mid} WHERE id = {$user_id}");
  }else{
    $res = mysqli_query($con,"SELECT latest_model,latest_estate FROM users WHERE id = {$user_id}");
    $row = mysqli_fetch_array($res);
    $mid = $row['latest_model'];
    $i = $row['latest_estate'];
    if(is_numeric($mid) && is_numeric($i)){
      $res = mysqli_query($con,"SELECT estate FROM models WHERE id = {$mid}");
      $row = mysqli_fetch_array($res);
      if($i == $row[0]){
        $res = mysqli_query($con,"SELECT COUNT(name) FROM models WHERE id = {$mid}");
        $row = mysqli_fetch_array($res);
        if($row[0] != 1)$mid = 0; // reset selected estate if it has been deleted
      }else{
        $mid = 0;
      }
    }
  }

  if($user_id != 0)goto main_page;
?>

<!-- ############ -->
<!--  LOGIN PAGE  -->
<!-- ############ -->
<div id="col-container">
  <div id="left-2col">
    <form method="post" action="Pages/login.php">
    <table style="margin:0 auto">
      <tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
      <tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
      <tr class="black-text">
        <td class="large-text" align="right">Email/username</td>
        <td><input type="text" tabindex="1" autofocus name="username" size="40"  maxlength="<?php echo($users_email);?>" required pattern="[a-z0-9._%+-@0-9.-]{2,}$" title="characters@characters.domain (characters followed by an @ sign, followed by more characters, and then a period and after the period, add at least 2 letters from a to z)"></td></br>
      </tr>
      <tr><td></td>
        <td><a class="small-text grey-text" style="float:right" href="javascript:email_admin()">forgot username</a></td>
      </tr>
      <tr class="black-text">
        <td class="large-text" align="right">Password</td>
        <td><input type="password" tabindex="2" name="password" size="40" maxlength="<?php echo($users_password);?>" required pattern="[A-Za-z#$@0-9._-+]{2,48}" title="Only alphanumerics _ . # $ - + and @ allowed"></td></br>
      </tr>
      <tr><td></td>
        <td><a class="small-text grey-text" style="float:right" href="javascript:email_admin()">forgot password</a></td>
      </tr>
      <tr><td></td>
        <td style="float:right">
          <input type="submit" style= "cursor:pointer" class="large-text" value="login">
        </td>
    </table>
    <input type="submit" hidden />
    </form>
  </div>
  <div id="right-2col">
    <form method="post" action="Pages/create_user.php">
    <table style="margin:0 auto">
      <tr class="black-text">
        <td class="large-text" align="right">Name</td>
        <td><input type="text" name="name" size="40" maxlength="<?php echo($users_name);?>" required pattern="[A-Za-z0-9\s]{2,240}" title="Only alphanumerics and space are allowed"></td></br>
      </tr>
      <tr class="black-text">
        <td class="large-text" align="right">Email</td>
        <td><input type="email" name="email" size="40" maxlength="<?php echo($users_email);?>" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" title="characters@characters.domain (characters followed by an @ sign, followed by more characters, and then a period and after the period, add at least 2 letters from a to z)"</td></br>
      </tr>
      <tr class="black-text">
        <td class="large-text" align="right">Password</td>
        <td><input type="password" name="pwd1" id="pwd1" onfocusout="pwd_chk()" size="40" maxlength="<?php echo($users_password);?>" required pattern="[A-Za-z#$@0-9._+-]{2,48}" title="Only alphanumerics _ . # $ - + and @ allowed"></td></br>
      </tr>
      <tr class="black-text">
        <td class="large-text" align="right">Retype Password</td>
        <td><input type="password" name="pwd2" id="pwd2" onfocusout="pwd_chk()" size="40" maxlength="<?php echo($users_password);?>" required pattern="[A-Za-z#$@0-9._+-]{2,48}" title="Only alphanumerics _ . # $ - + and @ allowed"></td></br>
      </tr>
      <tr class="black-text"><td></td>
        <td class="small-text" style="float:right">By registering you agree to <a class="grey-text" target="_blank" href="https://www.gnu.org/licenses/gpl-3.0.en.html">terms and conditions</a></td>
      </tr>
      <tr><td></td>
        <td style="float:right">
          <input type="submit" style= "cursor:pointer" class="large-text" value="register">
        </td>
    </table>
  </form>
  </div>
</div>
<?php
goto footer;
main_page:
?>

<!-- ########### -->
<!--  MAIN PAGE  -->
<!-- ########### -->
<div id="col-container">
  <div id="col1of4">
    <table>
      <tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
      <tr><td class='Xlarge-text grey-text'>Project<td></tr>
        <tr><td><hr></td></tr></table>
      <?php
        echo ("<table  onmouseleave='undisplay_floating_menu()'>");
        $res = mysqli_query($con,"SELECT id,name FROM estates WHERE owners LIKE '%,{$user_id},%'");
        while ($row = mysqli_fetch_array($res)){
          $i = $row['id'];
          $name = $row['name'];
          $textcolor = "grey-text";
          if($eid == $i){
            $ename = $row['name'];
            $textcolor = "black-text";
          }
          echo("
            <tr>
              <td class='large-text'>
                <div onmouseover='display_floating_menu(\"estate{$i}\")'>
                  <a class='no-underline {$textcolor}' href='index.php?id={$i}'>{$name}</a>
                </div>
              </td>
            </tr>
            <tr>
              <td>
                <div class='floating-menu' id='estate{$i}'>
                  <a  class='small-text grey-text' href='index.php?id={$i}'>select</a>
                  <a  class='small-text grey-text' href='Pages/edit_estate_or_model.php?id={$i}&editing=estate'>edit</a>
                  <a  class='small-text grey-text' href='javascript:really_delete_estate({$i})'>delete</a>
                </div>
              </td>
            </tr>
          ");
        } // while every name in estates
      ?>
    </table>
    <div id="add_stuff4col">
      <a class="grey-text medium-text">Add project</a>
      <!--<form method="post" action="Pages/add_estate_or_model.php">-->
      <form method="post" id="estatetypeform" action="Pages/add_estate_or_model.php">
	    <!-- if enter is pressed then do call js function, implicit posting of form is turned off by disabling the next submit button -->
        <input type="text" maxlength="240" pattern="[A-Za-z#\s$@0-9,._+-]{2,48}" onkeydown = "if (event.keyCode == 13)get_estate_type()"
		  title="Minimum 2 characters and only alphanumerics _ , . # $ - + space and @ allowed." autofocus name="name" size="40">
        <input type="hidden" name="table" value="estates">
        <input type="submit" disabled hidden /> <!-- disabled so that the form is not submitted on hitting enter -->
      </form>
    </div>
  </div>
  <div id="col2of4">
    <table>
      <tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
      <tr><td class='Xlarge-text grey-text'>Project type<td></tr>
        <tr><td><hr></td></tr></table>
      <?php
        echo ("<table  onmouseleave='undisplay_floating_menu()'>");
        $res = mysqli_query($con,"SELECT id,type FROM estates WHERE owners LIKE '%,{$user_id},%'");
        while($row = mysqli_fetch_array($res)){
          $i = $row['id'];
          $typeid = $row['type'];
          $resA = mysqli_query($con,"SELECT type FROM estate_types WHERE id = {$typeid}");
		  $rowA = mysqli_fetch_array($resA);
		  $type = $rowA[0];
          $textcolor = "grey-text";
          if($eid == $i)$textcolor = "black-text";
          echo("
            <tr>
              <td class='large-text'>
                <div>
                  <a class='no-underline {$textcolor}' >{$type}</a>
                </div>
              </td>
            </tr>
            <tr>
              <td>
                <div class='floating-menu-noborder' id='typeofestate{$i}'>
                  <a  class='small-text grey-text' >&nbsp</a>
                </div>
              </td>
            </tr>
          ");
        } // while every name in estates
      ?>
    </table>
    <div id="add_stuff4col_estate_type" class="estate_types">
		<?php
          $res = mysqli_query($con,"SELECT COUNT(type) FROM estate_types;");
          $row = mysqli_fetch_array($res);
	      $selectsize = $row[0];
		?>
        <a class="grey-text medium-text">Select type</a></br>
		<!-- below input type select (by using its form attribute) is part of the add project form even though is not enclosed in the form <tags> -->
	    <select name="estateTypeList" size="<?php echo $selectsize;?>" form="estatetypeform" onchange='if(this.value != 0) {this.form.submit();}'>
	    <?php
	  	  $res = mysqli_query($con,"SELECT id,type FROM estate_types");
    	  while($row = mysqli_fetch_array($res))echo("<option value='{$row[0]}'>{$row[1]}</option>");
	    ?>
	    </select>
    </div>
  </div>
  <div id="col3of4">
    <table>
      <?php
      if($eid != 0){
        echo("<tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>");
        if($eid != 0)echo ("<tr><td class='Xlarge-text grey-text'>Available models<td></tr>");
        echo("<tr><td><hr></td></tr></table>");
        echo ("<table  onmouseleave='undisplay_floating_menu()'>");
        $res = mysqli_query($con,"SELECT id,name FROM models WHERE estate = {$eid}"); // TODO only display this users models
        while ($row = mysqli_fetch_array($res)){
          $i = $row['id'];
          $name = $row['name'];
          $textcolor = "grey-text";
          if($mid == $i)$textcolor = "black-text";
          echo("
            <tr>
              <td class='large-text'>
                <div onmouseover='display_floating_menu(\"model{$i}\")'>
                  <a class='no-underline {$textcolor}' href='index.php?id={$eid}&mid={$i}'>{$name}</a>
                </div>
              </td>
            </tr>
            <tr>
              <td>
                <div class='floating-menu' id='model{$i}'>
                  <a  class='small-text grey-text' href='index.php?id={$eid}&mid={$i}'>select</a>
                  <a  class='small-text grey-text' href='Pages/edit_estate_or_model.php?id={$i}&editing=model'>edit</a>
                  <a  class='small-text grey-text' href='javascript:really_delete_model({$i})'>delete</a>
                </div>
              </td>
            </tr>
          ");
        }
      }
      ?>
    </table>
    <div id="add_stuff4col">
      <?php if($eid != 0)echo("
      <a class='grey-text medium-text'>&nbsp&nbspAdd model</a>
      <form method='post' action='Pages/add_estate_or_model.php'>
        &nbsp
        <input type='text' maxlength='240' pattern='[A-Za-z#\s$@0-9,._+-]{2,48}' title='Minimum 2 characters and only alphanumerics _ , . # $ - + space and @ allowed.' name='name' size='40'>
        <input type='hidden' name='table' value='models'>
        <input type='hidden' name='eid' value='{$eid}'>
        <input type='submit' hidden />

        <!-- <input type='submit' value='OK' class='grey-text' style='cursor:pointer'> -->
      </form>");
      ?>
    </div>
  </div>
  <div id="col4of4">
    <?php
      if($eid != 0 && $mid !=0){
        $res = mysqli_query($con,"SELECT tarball,created,author,purpose,name FROM models WHERE id = {$mid}");
        while($row = mysqli_fetch_array($res)){
          $mname = $row['tarball'];
          $created = $row['created'];
          $author = $row['author'];
          $purpose = $row['purpose'];
          $name = $row['name'];
        }
        echo("<p class='grey-text large-text' style='margin-left:10px'>");
        if(file_exists("Images/model{$mid}.jpg")){
          echo("<a href='Images/model{$mid}.jpg'><img src='Images/model{$mid}.jpg' class='model-img4col'></a></br>");
        }else{
          echo("<a href='Pages/edit_estate_or_model.php?id={$mid}&editing=model'><img src='Images/click2add.jpg' class='model-img4col'></a>");
        }
        echo("<a href='Pages/edit_estate_or_model.php?id={$mid}&editing=model' class='no-underline grey-text'>
          </br>
          <table class='grey-text medium-text'>
            <tr>
              <td>Selection:</td><td>{$ename}: {$name}</td>
            </tr>
            <tr>
              <td>Purpose:</td><td>{$purpose}</td>
            </tr>
            <tr>
              <td>Created:</td><td>{$created}</td>
            </tr>
            <tr>
              <td>Author:</td><td>{$author}</td>
            </tr>
            <tr>
              <td>File:</td><td>{$mname}</td>
            </tr>
          </table>
          </a></p>
          <form method='post' action='assmnt_req.php?mid={$mid}'>
            <input type='submit' style='cursor:pointer;margin-right:20px;float:right' class='medium-text grey-text' value='Select'>
          </form>
        ");
      }
    ?>
  </div>
</div>
<?php mysqli_close($con);?>
<!-- ######## -->
<!--  FOOTER  -->
<!-- ######## -->
<?php footer:?>
<div id="footer">
  <hr>
  <?php include "Pages/footer.php";?>
</div>
</body>
</html>
<!-- TO DO
make php files called
logout.php
login.php
create_user.php



-->
