<?php
defined($security_key) or exit;

//------------------------------------------
// Get user_details
//------------------------------------------
$user_credentials = json_decode($input,true);
$username = $user_credentials['username'];
$password = $user_credentials['password'];

if (!empty($username) && !empty($password)) {

    $username = strip_tags(trim($username));
    $password = strip_tags(trim($password));

    $conn = new mysqli($db,$dbuser,$dbpw,$dbname);
            if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT id, username, password, service FROM users WHERE username='$username'";
    $result = $conn->query($sql);

        if ($result->num_rows == 1) {

            while ($row = $result->fetch_assoc())  {

                if (password_verify($password, $row['password'])) {

                    if(empty($row['service'])){
                    echo 'No service account found';
                    http_response_code(401);
                    }
                    else {
                    $service = $row['service'];

                    $jwt = createCommunicationToken($service);

                    $logindate = date('Y-m-d H:i:s');
                    $id = $row['id'];

                    $sql1 = "UPDATE users SET lastlogin = '$logindate'  WHERE id='$id'";
                    $conn->query($sql1);

                    echo json_encode(array('token' => $jwt));
                    }
                }
                else
                {
                http_response_code(203);
                }
            }
        }
        else {
        http_response_code(203);
        }
    $conn->close();
    }
else {
    http_response_code(400);
}
?>