<?php 
include($_SERVER['DOCUMENT_ROOT'] . '/config/sessionStart.php');
include($_SERVER['DOCUMENT_ROOT'] . '/logic/testinput.php');

$data = json_decode(file_get_contents('php://input'));
$username = testinput($data->email);
$passwordUnhashed = testinput($data->password);

loginUser($username, $passwordUnhashed);

function loginUser($username, $passwordUnhashed)
{
    require($_SERVER['DOCUMENT_ROOT'] . '/config/setupDBAccess.php');
    
    $sql = "SELECT `username`, `password`, `role` FROM `user` WHERE `username` = ?";
    $stmt = $db->prepare($sql);
    $stmt->bind_param("s", $username);


    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($username, $password, $role);
    if ($stmt->num_rows == 1) {
        $stmt->fetch();
        if (password_verify($passwordUnhashed, $password)) {
            $response = "success";
            $_SESSION['username'] = $username;
            $_SESSION['role'] = $role;
            $_SESSION['loggedIn'] = true;
        } else {
            $response = "failure";
        }
    } else {
        $response = "failure";
    }
    $stmt->close();
    $db->close();
    
    echo $response;
}




?>