<form class="form form2" action="{{route('login.with.otp')}}" method="post">
    @csrf
    <div class="form-group">
        <label>Phone<sup style="color: red;">*</sup></label>
        <input type="text" name="phone" id="phone"
            class="form-control @error('phone') is-in-valid @enderror" required />
        <button type="button" id="send_otp" class="btn btn-warning my-2">Send OTP</button>
        @error('phone')
        <span class="invalid-feedback" role="alert">{{ $message }}</span>
        @enderror
    </div>
    <div class="form-group">
        <label>OTP <sup style="color: red;">*</sup></label>
        <input type="text" name="otp" id="otp"
            class="form-control @error('otp') is-in-valid @enderror" required />
        @error('otp')
        <span class="invalid-feedback" role="alert">{{ $message }}</span>
        @enderror
    </div>
    <input class="form-control" type="submit" value="Login" style="background:var(--primary_color)">
</form>

@push('js')
<script>
    $(document).ready(function(){
        $('#send_otp').on('click', function(e) {
            e.preventDefault();
            var phone = $('#phone').val();
            var otpTimestamp = localStorage.getItem('otpTimestamp');
            var currentTime = new Date().getTime();

            if (otpTimestamp && currentTime - otpTimestamp < 60000) {
                alert('Please wait for 1 minute before requesting a new OTP.');
                return;
            }

            if (phone) {
                $.post("{{ route('login.with.otp') }}", { phone: phone, _token: '{{ csrf_token() }}' })
                .done(function(response) {
                    console.log(response);
                    if (response.status === 'true') {
                        localStorage.setItem('otpTimestamp', new Date().getTime());
                        alert('OTP sent successfully');
                    } else {
                        localStorage.removeItem('otpTimestamp');
                        alert(response.message);
                    }
                })
                .fail(function(error) {
                    alert(error.responseJSON.message);
                });
            } else {
                alert('Phone number is required');
            }
        });
    });
</script>
@endpush
