<?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, lastlogin 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 {
                        //Default service key
                        $service = $row['service'];

                        //Check valid userkey lastlogin less than 30minutes
                        $valid_key = strtotime('+30 minutes',strtotime($row['lastlogin']));
                        $valid = ($valid_key <= time())?0:1;

                        if ($row['service'] != '' && $valid == 0){
                            //Key is not valid anymore => update new servicekey                           
                            $service = bin2hex(random_bytes(25));
                            $sql_service = 'UPDATE users SET service = ? WHERE id = ?';
                            $stmt_service = $conn->prepare($sql_service);
                            $stmt_service->execute([$service, $row['id']]);
                        } 
                        
                        $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);
}
?>