<?php
$logged =false; // l'utente ha passato l'autenticazione?
$username = $_POST['username'];
$password = $_POST['password'];

if(empty($username) or empty($password))
{
    header('location:loginform.php');
    die();  
}

$conn = mysqli_connect('localhost', 'root', '', 'test');

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// La password è memorizzata nel DB in chiaro
$sql ="select name, surname from users where username = ? and password = ?";
$st  = $conn->prepare($sql);

$password_sha2 = hash('sha256', $password);

// 3. Associa i parametri (s = stringa, s = stringa, i = intero)
$st->bind_param("ss", $username, $password_sha2);

// 4. Esegui lo statement
if($st->execute())
{
    $result = $st->get_result();

    if($row = $result->fetch_assoc())
    {
        $logged  = true;
        $name    = $row['name'];
        $surname = $row['surname'];
    }
}
// 5. Chiudi lo statement e la connessione
$st->close();
$conn->close();


if($logged) {
    print "Benvenuto $name $surname";
}
else{
     header('location:loginform.php?error=1');
}
?>
