<html>
<head>
  <link rel="stylesheet" href="../../CSS/style.css">
</head>
<body>
<?php
require 'super_secret_stuff.php';
$con = mysqli_connect($website,$mysqli_username,$pw,$dbase);

if(isset($_POST["cancel"])){
  mysqli_close($con);
  echo "<script>window.top.location.reload(true);</script>" ;
  exit;
}

$get_mode = "";
if(!empty($_GET["mode"]))$get_mode = $_GET["mode"];
if($get_mode == "logout"){
  $user_id = get_userid($con);
  mysqli_query($con,"DELETE FROM Current WHERE user_id = {$user_id}");
  mysqli_close($con);
  header ("Location: ../../index.php");
  exit;
}

if(isset($_POST["signup"])){
  mysqli_close($con);
  header ("Location: ../../index.php?signup=yes");
  exit;
}

if($get_mode == "edit"){
  $user_id = get_userid($con);
  mysqli_close($con);
  header ("Location: ../../index.php?edit=yes&user_id={$user_id}");
  exit;
}

// get email and password from db
$email = trim($_POST["email"]);
$paswd = trim($_POST["password"]);
$email_found = false;
$login = false;

$res = mysqli_query($con,"SELECT email,password,user_id FROM User");
while($row = mysqli_fetch_array($res)){
    if($email == $row[0]){
        $email_found = true;
        if(trim($paswd) == trim($row[1])){
          $login = true;
        }
        $userid = $row[2];
        break;
    }
}

if(!$email_found){
  echo "<div class='w3-display-middle'><h4>The email/username you entered has not been found on our servers, please register to become a member</h4></div>";
  exit;
}

if(!$login){
  echo "<div class='w3-display-middle'><h4>Your email/username has been found but your password is incorrect<br/>Email support team</h4></div>";
  exit;
}

// if we get this far then username and password are both valid
log_user_in($userid,$con);
mysqli_close($con);
echo "<script>window.top.location.href = '../../index.php'</script>";
?>
</body>
</html>
