<html>
<head>
<script>
 function gohome(){window.top.location.href = '../../index.php?t=' + (new Date().getTime()); };/*To load from server i.e. refresh*/
 function goback(){history.go(-1); }
</script>
<link rel="stylesheet" href="../../CSS/style.css">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link  href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link  href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">

</head>
<body>
<?php
require 'super_secret_stuff.php';

if(isset($_POST["cancel"])){
  echo "<script>gohome()</script>" ;
  exit;
}

$con = mysqli_connect($website,$mysqli_username,$pw,$dbase);

// Validate form
$exp_name = "/^[A-Za-z .'-]+$/";
$exp_add = "/^[A-Za-z 0-9.'-]+$/";
$exp_email = "/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/";
$exp_no = "/^[0-9 ]+$/";
$err_msg = "";
$exp_pwd = "/^[A-Za-z0-9._]+$/";

$firstname = "";
$lastname  = "";
$email = "";
$auth  = "";
$pwd0  = "";
$pwd1  = "";
$pwd2  = "";

if(!empty($_POST["fname"]))$firstname = $_POST["fname"];
if(!empty($_POST["lname"]))$lastname  = $_POST["lname"];
if(!empty($_POST["email"]))$email  = $_POST["email"];
if(!empty($_POST["auth"]))$auth = $_POST["auth"];
if(!empty($_POST["pwd0"]))$pwd0 = $_POST['pwd0'];
if(!empty($_POST["pwd1"]))$pwd1 = $_POST['pwd1'];
if(!empty($_POST["pwd2"]))$pwd2 = $_POST['pwd2'];

if(!isset($firstname) || trim($firstname) == ''){
  $err_msg .= "No first name provided <br/>";
}elseif(!preg_match($exp_name,$firstname)){
  $err_msg .= "First name does not appear to be valid <br/>";
}

if(!isset($lastname) || trim($lastname) == ''){
  $err_msg .= "No last name provided <br/>";
}elseif(!preg_match($exp_name,$lastname)){
  $err_msg .= "Last name does not appear to be valid <br/>";
}

if(!isset($email) || trim($email) == ''){
  $err_msg .= "No email provided <br/>";
}elseif(!preg_match($exp_email,$email)){
  //$err_msg .= "Email does not appear to be valid <br/>";
}

if($pwd1 != $pwd2)                                           $err_msg .= "Passwords do not match please enter again<br/>";
if(trim($pwd1)     !== '' && !preg_match($exp_pwd,$pwd1))    $err_msg .= "Only allowed to enter alphanumerics and underscore as password please enter again<br/>";
$get_edit = "";
if(!empty($_GET["edit"]))$get_edit = $_GET["edit"];
if($get_edit == "yes"){
  $user_id = 0;
  if(!empty($_GET["uid"]))$user_id = (int)$_GET["uid"];
  if(empty($pwd0)){
    $err_msg .= "Password not given <br/>";
  }else{
    $res = mysqli_query($con,"SELECT password FROM User WHERE user_id = {$user_id}");
    while($row = mysqli_fetch_array($res))$pwd_from_db = $row[0];
    if(trim($pwd0) != trim($pwd_from_db)){
      $err_msg .= "Wrong password provided <br/>";
      $err_msg .= "password from form =={$pwd0}==<br/>";
      $err_msg .= "password from dbase ={$pwd_from_db}==<br/>";
      $err_msg .= "user id = {$user_id} <br/>";
    }
  }
}

// If invalid return to previous page
if($err_msg != ""){
  echo "<div class='w3-display-middle'> Error: <br/>" . $err_msg . "<br/>";
  echo "<button onclick='goback()'><a>BACK<i class='fa fa-chevron-left'></i></a></button>";
  mysqli_close($con);
  echo "</div></body></html>";
  exit;
}

// If number of users > 300 then produce message to email webmaster
$con = mysqli_connect($website,$mysqli_username,$pw,$dbase);
$res = mysqli_query($con,"SELECT COUNT(email) FROM User");
while($row = mysqli_fetch_array($res))$tot_users = $row[0];
if($tot_users > $max_users){
  mysqli_close($con);
  echo "<div class='w3-display-middle'> Error: <br/>Maximum number of users has been exceeded please email administrator at {$admin_email}<br/>";
  echo "<button onclick='goback()'><a>BACK<i class='fa fa-chevron-left'></i></a></button>";
  echo "</div></body></html>";
  exit;
}

if(isset($_GET["signup"]) && $_GET["signup"] == "yes"){

  // Check if this email is already present
  $res = mysqli_query($con,"SELECT email FROM User");
  while($row = mysqli_fetch_array($res)){
    if(trim($email) == trim($row[0])){
      echo "<div class='w3-display-middle'> Error: <br/>This email is already in use. Use another email. <br/>";
      echo "<button onclick='goback()'><a>BACK<i class='fa fa-chevron-left'></i></a></button>";
      mysqli_close($con);
      echo "</div></body></html>";
      exit;
    }
  }

  // Logout current user if logged in
  $user_id = get_userid($con);
  mysqli_query($con,"DELETE FROM Current WHERE user_id = {$user_id}");

  // Get user_id to insert
  $res = mysqli_query($con,"SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{$dbase}' AND TABLE_NAME = 'User'");
  while($row = mysqli_fetch_array($res))$user_id = $row[0];

  // Add new user
  gen_auth1:
  $authc = generateRandomString(16);
  if(!is_unique($con,$authc))goto gen_auth1;
  mysqli_query($con,"INSERT INTO User(user_type,fname,lname,email,password,auth_code)
  VALUES('0','{$firstname}','{$lastname}','{$email}','{$pwd1}','{$authc}')");
  
  // Login new user
  log_user_in($user_id,$con);

/* There are no primitive models for Calibro
  // Copy primitive models for this user
  $files = array_slice(scandir($proj_file_path_deep."primitive_models/"), 2); // lose . and .. from scandir output
  foreach($files as $zipfile){
    $newzipfile = $user_id."__".$zipfile;
    $from_file = $proj_file_path_deep."primitive_models/".$zipfile;
    $to_file   = $proj_file_path_deep."user_uploaded_models/".$newzipfile;
    copy($from_file,$to_file);
  }

  $res = mysqli_query($con,"SELECT * FROM Projects WHERE exemplarYN = 'Y'");
  //echo "<div class='w3-display-middle'>";
  while($row = mysqli_fetch_array($res)){
    $newzipfile = $user_id."__".$row[3];
    mysqli_query($con,"INSERT INTO Projects(name_string,lowlevel_name_string,tarball_name,exemplarYN,shared_between,pic_id)
                                    VALUES ('{$row[1]}',  '{$row[2]}'           ,'{$newzipfile}','N'        ,',{$user_id},','{$row[6]}')");
  }
  //echo "</div";exit;
  log_user_in($user_id,$con);
*/

  mysqli_close($con);
  echo "<div class='w3-display-middle'> <h4>You have been successfully signed up</h4>";

}elseif(isset($_GET["edit"]) && $_GET["edit"] == "yes"){
  if(empty($pwd1))$pwd1 = $pwd0;
  if(is_unique($con,$auth)){
	mysqli_query($con,"UPDATE User SET
                            fname   ='{$firstname}',
                            lname   ='{$lastname}',
                            password='{$pwd1}',
                            email   ='{$email}',
                            auth_code ='{$auth}'
                            WHERE user_id = {$user_id}");
    echo "<div class='w3-display-middle'> <h4>You have successfully changed your details</h4>";
  }else{
	echo "<div class='w3-display-middle'> <h4>Authentication code is not unique; details not saved</h4>";
  }
  mysqli_close($con);
}

echo "<button onclick='gohome()' style='float:right;opacity:0.6;'><i class='fa fa-check'></i></button>";
echo "</div></body></html>";

exit;
?>
