<%- include('./partials/header'); %>
<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">Change Password</h1>
            <br>
            <form action="/signup" id="changepassword-form" method="POST">
                <div id="changepassword-error" class="alert alert-danger alert-dismissible fade show" role="alert">
                    <span id="changepassword-error-message"></span>
                </div>
                <div class="form group">
                    <label for="password">New Password</label>
                    <input type="password" name="new-password" class="form-control" placeholder="Password"
                        autocomplete="new-password" required>
                    <br>
                    <label for="password">Confirm Password</label>
                    <input type="password" name="new-password-confirm" class="form-control"
                        placeholder="Confirm Password" autocomplete="new-password" required>
                    <br>
                    <input type="submit" id="changepassword-button" value="Change Password" class="btn btn-primary btn-block">
                </div>
            </form>
        </div>
    </div>
</div>
<%- include('./partials/footer'); %>

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

    const token = window.location.pathname.split(`/`)[2]

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

        $(`#changepassword-button`).attr(`disabled`, true);

        $(`#changepassword-error`).hide();
        $(`#changepassword-success`).hide();

        $.ajax({
            type: `post`,
            url: `/changepassword/${token}`,
            data: $(`#changepassword-form`).serialize()
        }).then(res => {
            if (res.errors) {
                $(`#changepassword-button`).attr(`disabled`, false);
                $(`#changepassword-error`).show();

                $(`#changepassword-error-message`).text(res.errors);
                return false;
            } else if (res.success) {
                $(`#changepassword-button`).attr(`disabled`, false);
                $(`#changepassword-error`).show();

                $(`#changepassword-error-message`).text(res.success);

                setTimeout(() => {window.location.href=`/login`}, 2500)

                return true;
            }
        });
    });
</script>