<?php
  include("database.php");
  $name = $email = "";

  session_start();
  if (isset($_SESSION["sid"]) && isset($_SESSION["sname"])) {
    header("Location: index.php");
    exit();
  } elseif (isset($_POST["submit"])) {
    $name = trim($_POST["myname"]);
    $email = trim($_POST["myemail"]);
    $pass = $_POST["mypass"];

    if (preg_match("/^[a-zA-Z]+$/", $name) && filter_input(INPUT_POST, "myemail", FILTER_VALIDATE_EMAIL) && strlen($pass) > 3) {
      $safeEmail = mysqli_real_escape_string($connection, $email);
      $query = "SELECT id FROM users WHERE email = '$safeEmail'";
      $result = mysqli_query($connection, $query);
      if (mysqli_num_rows($result) == 0) {
        $password = password_hash($pass, PASSWORD_DEFAULT);
        $query = "INSERT INTO users (id, name, email, password) VALUES (NULL, '$name', '$safeEmail', '$password')";
        if (mysqli_query($connection, $query)) {
          header("Location: signin.php");
          exit();
        }
      }
    }
  }
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Sign Up</title>
</head>
<body>
  <section>
    <form name="myform" method="post" action="signup.php">
      <p>Create Account</p>
      <p>
        <label for="myname">User Name: </label>
        <input type="text" id="myname" name="myname" value="<?php echo htmlspecialchars($name);?>">
      </p>
      <p>
        <label for="myemail">Email: </label>
        <input type="email" id="myemail" name="myemail" value="<?php echo htmlspecialchars($email);?>">
      </p>
      <p>
        <label for="mypass">Password: </label>
        <input type="password" id="mypass" name="mypass">
      </p>
      <input type="submit" name="submit" value="Sign Up">
    </form>
  </section>
</body>
</html>