<?php
require_once "database.php";
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare('SELECT id, name, surname, office, role, email, password, gender, recipient_id FROM users WHERE email = ?')) {
 // Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
 $stmt->bind_param('s', $_POST['email']);
 $stmt->execute();
 // Store the result so we can check if the account exists in the database.
 $stmt->store_result();
 if ($stmt->num_rows > 0) {
  $stmt->bind_result($id, $name, $surname, $office, $role, $email, $password, $gender, $recipient_id);
  $stmt->fetch();
  // Account exists, now we verify the password.
  // Note: remember to use password_hash in your registration file to store the hashed passwords.
  if (password_verify($_POST['password'], $password)) {
   // Verification success! User has logged-in!
   // Create sessions, so we know the user is logged in, they basically act like cookies but remember the data on the server.
   /* $comb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   $shfl = str_shuffle($comb);
   $session_id = substr($shfl,0,30); */
   session_regenerate_id();
   $sql_update = "UPDATE users SET session_id='" . session_id() . "' WHERE id = " . $id . "";
   $con->query($sql_update);
   $_SESSION['loggedin']     = true;
   $_SESSION['username']     = $name . " " . $surname;
   $_SESSION['name']         = $name;
   $_SESSION['surname']      = $surname;
   $_SESSION['office']       = $office;
   $_SESSION['role']         = $role;
   $_SESSION['email']        = $email;
   $_SESSION['id']           = $id;
   $_SESSION['gender']       = $gender;
   $_SESSION['recipient_id'] = $recipient_id;
   die($_SESSION['username']);
  } else {
   // Incorrect password
   die("2");
  }
 } else {
  // Incorrect username
  die("3");
 }
 $stmt->close();
}
