<div class="form__wrapper">
    <form action="{{ route('password.email') }}" method="post" enctype="multipart/form-data" id="loginForm">
        @csrf
        <div class="heading__content">
            <h2 class="title">{{ __('forgot_password!') }}</h2>
            <p class="desc">{{ __('please_enter_your_email_address') }}</p>
        </div>

        <div class="form-group">
            <label for="login-email">
                {{ __('username_or_email') }}
                <span class="required">*</span>
            </label>
            <input type="email" class="form-control" name="email" id="login-email"
                placeholder="{{ __('your_email') }}" />
            <span id="error-email"></span>
        </div>

        <div class="btn__group">
            <button type="button" name="btn" class="btn btn-primary w-100" onclick="sendForgotPasswordRequest()">
                {{ __('send_request') }}
            </button>
        </div>
        <p class="account text-center">
            {{ __('already_have_an_account?') }}
            <a href="javascript:void(0)" id="signUp" onclick="ajaxModal('modal-md', '{{ route('login') }}')">
                {{ __('login') }}</a>
        </p>
    </form>
</div>
<script>
    "use strict";

    function sendForgotPasswordRequest() {
        const form = $('#loginForm');
        const formData = new FormData(form[0]);

        // Clear any previous error message
        $('#error-email').html('').removeClass('text-danger');

        $.ajax({
            url: form.attr('action'),
            method: form.attr('method'),
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                form[0].reset();
                window.location.href = "{{ route('home') }}"
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;

                    if (errors.email) {
                        $('#error-email').html(errors.email[0]).addClass('text-danger');
                    }
                } else {
                    alert('{{ __('something_went_wrong_try_again_later') }}');
                }
            }
        });
    }
</script>
