<%- include('./partials/header'); %>
<script src="https://hcaptcha.com/1/api.js" defer></script>
<div class="row mt-5">
    <div class="col-md-6 m-auto">
        <div class="card card-body" style="background-color: #b1cbe6;">
            <h1 class="text-center">Log In</h1>
            <br>
            <form action="/login" id="login-form" method="POST">
                <div id="login-error" class="alert alert-danger alert-dismissible fade show" role="alert">
                    <span id="login-error-message"></span>
                </div>
                <div id="login-success" class="alert alert-success alert-dismissible fade show" role="alert">
                    <span id="login-success-message"></span>
                </div>
                <div class="form group">
                    <label for="username">Username</label>
                    <input type="username" name="login-username" class="form-control" placeholder="Enter Username"
                        autocomplete="username" required>
                    <br>
                    <label for="password">Password</label>
                    <input type="password" name="login-password" class="form-control" placeholder="Enter Password"
                        autocomplete="new-password" required>
                    <br>
                    <div>
                        <a href="/recoveraccount">Forgot Password?</a>
                    </div>
                    <br>
                    <div class="h-captcha" data-sitekey="b5bed0d5-a077-493d-9ae0-3a66e4d05a6c"></div>
                    <br>
                    <input type="submit" id="login-button" value="Login" class="btn btn-primary btn-block">
                </div>
            </form>
        </div>
    </div>
</div>
<%- include('./partials/footer'); %>

<script>
    $(document).ready(() => {
        $(`#login-error`).hide();
        $(`#login-success`).hide();
    });

    $(`#login-button`).on(`click`, e => {
        e.preventDefault();

        $(`#login-button`).attr(`disabled`, true);
        $(`#login-error`).hide();
        $(`#login-success`).hide();

        $.ajax({
            type: `post`,
            url: `/login`,
            data: $(`#login-form`).serialize()
        }).then(res => {
            if (res.errors) {
                $(`#login-button`).attr(`disabled`, false);
                $(`#login-error`).show();
                hcaptcha.reset();
                
                $(`#login-error-message`).text(res.errors);
                console.error(`[ACCOUNT SERVER]: ${JSON.stringify(res.errors)}`);
            } else if (res.success) {
                $(`#login-button`).val(`Logged in, redirecting...`);
                $(`#login-success`).show();

                $(`#login-success-message`).text(res.success);
                console.log(`[ACCOUNT SERVER]: ${JSON.stringify(res.success)}`);

                window.location.reload();
            }
        });
    });
</script>