@extends('auth_api.layouts.auth')

@section('meta')
    @php
        $data = metaData('login');
        
    @endphp
@endsection

@section('description')
    {{ @$data->description }}
@endsection

@section('title')
    {{ __('login') }}
@endsection

@section('og:image')
    {{ asset(@$data->image) }}
@endsection

<link rel="canonical" href="{{ url()->current() }}" />

@section('content')
    <div class="right-content common-space">
        <div class="heading">
            {{-- <a href="javascript:;" id="return_back_btn" class="back" aria-label="back">
                <img src="{{ asset('frontend') }}/student-panel-old/images/arrow.svg" width="100%" height="100%" alt="arrow">
            </a> --}}
            <a href="{{env('APP_URL')}}" class="logo" aria-label="logo">
            <img src="{{ asset('frontend') }}/student-panel-old/images/logo.svg" width="100%" height="100%" alt="logo">
            </a>
            {{-- <p class="head">Login to Continue</p>
            <p class="sub-head">Your Hassle-Free Study Abroad Journey Starts Here!</p> --}}
        </div>
        <!--<div class="login-section">
            
            <div class="tabs">
                <p class="single-tab active" data-key="email" id="email_login">Email</p>
                <p class="single-tab " data-key="mobile" id="mobile_login">Mobile Number</p>
            </div>
            
            <form class="form" id="login_form">
                @csrf
                <input type="hidden" name="login_type" id="login_type" value="email_login">
                <div class="number panel mobile">

                    {{-- <div class="select-code">
                        <p class="country-code">
                            <select class="list" name="country_code" id="countrySelect">
                                <option value="">+91</option>
                            </select>
                        </p>
                    </div> --}}
                    
                    <div class="single-input">
                        <label for="Mobile Number" class="field-label">Enter Mobile Number</label>
                        <input type="tel" name="phone" id="phone" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\.*)\./g, '$1');" class="input-field" value=""
                            placeholder="Enter Mobile Number" maxlength="15">
                    </div>                    
                </div>
                <div class="single-input panel email">
                    <label for="" class="field-label">Enter Email Id</label>
                    <input type="email" name="email" id="email" class="input-field" placeholder="Enter Email Id" maxlength="100">
                </div>

                <div class="single-input">
                    <label for="Password" class="field-label">Password</label>
                    <input type="password" name="password" id="password" class="input-field" value="" placeholder="Password" maxlength="100">
                    <span class="pass" id="password_warning"></span>
                </div>
                <a href="/auth/forgot_password/email" id="forgot_link" class="forgot-pass">Forgot Password?</a>
                <button type="submit" id="forgot_submit_btn" class="btn">Submit<i id="spinner" class=""></i></button>
            </form>
        </div>
        <div class="social-links">
            <p class="small-text"><span>You can connect with us on</span></p>
            <ul class="link-list">
                <li class="single-link">
                    <a href="{{ route('social.login', 'facebook') }}" aria-label="facebook"><img src="{{ asset('frontend') }}/student-panel-old/images/facebook.svg" alt="facebook" width="100%" height="100%" /></a>
                </li>
                <li class="single-link">
                    <a href="{{ route('social.login', 'google') }}" aria-label="google"><img src="{{ asset('frontend') }}/student-panel-old/images/google.svg" alt="google" width="100%" height="100%" /></a>
                </li>
                {{-- <li class="single-link">
                    <a href="javacsript:;" aria-label="apple"><img src="{{ asset('frontend') }}/student-panel-old/images/apple.svg" alt="apple" /></a>
                </li> --}}
            </ul>
            <p class="signup">Don’t have an account? <a href="/register" class="signup-link">Sign Up Here</a></p>
        </div> -->
        <div class="form-body step-1">
            <lottie-player class="popup-img" src="{{ asset('frontend') }}/assets-desktop/js/login.json"
                    background="transparent" speed="1" width="100%" hight="100%"
                    style="width:120px; height:120px;" loop autoplay></lottie-player>
                <p class="head">Welcome to World’s Most Trusted Study Abroad Platform</p>
                <p class="popup-desc">Your Hassle-Free Study Abroad Journey Starts Here!</p>
                <form class="form-div" id="plan-lead-form">
                    <div class="single-input country-input">
                        <select name="country_code" id="" class="country-select">
                            <option value="" selected>IN +91</option>
                            {{-- <option value="" selected>IN(+91)</option>
                            <option value="" selected>IN(+91)</option>
                            <option value="" selected>IN(+91)</option> --}}
                        </select>

                        <input class="input-field phone-validate" type="tel" placeholder="Enter Your Mobile Number" value=""
                             aria-label="mobile number" name="phone">
                            <span class="spin-loader" style="display: none"></span>
                    </div>

                    <!--show when not Login-->
                    <div class="single-input name-input" style="display: none">
                            <input class="input-field" type="text" placeholder="First Name" value=""
                                id="" aria-label="Name" name="name">
                            <input class="input-field" type="text" placeholder="Last Name" value=""
                             aria-label="Name" name="last_name">
                    </div>
                    
                    <button class="form-btn submit-button" type="submit">Continue
                        <span class="spin-loader" style="display: none;"></span>
                    </button>
                    <div class="agree-checkbox">
                        {{-- <input type="checkbox" checked> --}}
                        <input type="checkbox"  value="Friday" checked>
                        <label class="bottom-text" >I agree to receive whatsapp messages from gradding</label>
                    </div>
                </form>
            <!--hide when screen-2 is visible-->
            
        </div>
        <div class="form-body step-2" style="display: none">
            <lottie-player class="popup-img" src="{{ asset('frontend') }}/assets-desktop/js/pin.json"
						background="transparent" speed="1" width="100%" height="100%"
						style="width:120px; height:120px;" loop autoplay></lottie-player>

                <p class="edit-num"><span class="phone_edit">+91 14253 52142</span>
                    <a href="javascript:;" class="edit-icon" id="edit__btn" aria-label="edit">
                        <svg width="14" height="14" viewBox="0 0 14 14" fill="none"
                            xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M7.30978 3.59676L2.18753 8.71901C2.11695 8.78962 2.07264 8.88225 2.06197 8.98151L1.75265 11.7645C1.74589 11.8256 1.75209 11.8875 1.77086 11.9461C1.78963 12.0046 1.82054 12.0586 1.86158 12.1044C1.90262 12.1503 1.95286 12.1869 2.00902 12.212C2.06519 12.2371 2.12601 12.2501 2.18753 12.2501C2.20361 12.2501 2.21967 12.2492 2.23566 12.2474L5.02034 11.9381C5.11961 11.9275 5.21223 11.8832 5.28284 11.8126L10.4033 6.69076L7.30978 3.59676ZM12.4093 2.82851L11.1716 1.59083C10.9255 1.34477 10.5917 1.20654 10.2437 1.20654C9.89563 1.20654 9.56185 1.34477 9.31572 1.59083L7.92841 2.97814L11.022 6.07214L12.4097 4.68439C12.6557 4.4382 12.7939 4.10439 12.7938 3.75636C12.7937 3.40833 12.6554 3.07458 12.4093 2.82851Z"
                                fill="#066AC9" />
                        </svg>

                    </a>
                </p>

                <p class="head login-condition">Create your 4 digit Login PIN</p>
                <form class="form-div" id="user-pin-form">
                    <div class="pin-input">
                        <input class="input-field" type="tel" value="" id="pin-input-0" aria-label="code"
								maxlength="1" oninput="handlePinInput(0, this);" onkeydown="handleKeyDown(event, 0);">
							<input class="input-field" type="tel" value="" id="pin-input-1" aria-label="code"
								maxlength="1" oninput="handlePinInput(1, this);" onkeydown="handleKeyDown(event, 1);">
							<input class="input-field" type="tel" value="" id="pin-input-2" aria-label="code"
								maxlength="1" oninput="handlePinInput(2, this);" onkeydown="handleKeyDown(event, 2);">
							<input class="input-field" type="tel" value="" id="pin-input-3" aria-label="code"
								maxlength="1" oninput="handlePinInput(3, this);" onkeydown="handleKeyDown(event, 3);">
                    </div>

                    <p class="wrong-pin-error" style="display: none">Invalid Pin</p>
                    <p class="small-head" style="display: none">Forgot Pin? <a href="javascript:;" class="blue reset-link">Reset</a></p> <!-- Hide when new pin is created-->

                    <button type="submit" class="form-btn submit-button">Continue
                        <span class="spin-loader" style="display: none;"></span>
                    </button>
                    <p class="bottom-text">By continuing, you agree to our <a class="link" target="_blank" href="/terms-condition">Terms of service</a> and <a class="link" target="_blank" href="/privacy-policy">Privacy policy</a></p>
                </form>
            <!--hide when screen-2 is visible-->
            
        </div>
        <div class="form-body step-3" style="display: none">
                <p class="head">Verification Code</p>
               <div class="edit-num-div">
                <p class="sub-head">Please Enter 4 Digit Code sent to: </p>
                <p class="edit-num"><span class="phone_edit">+91 14253 52142</span>
                    <a href="javascript:;" class="edit-icon" id="edit__btn1" aria-label="edit">
                        <svg width="14" height="14" viewBox="0 0 14 14" fill="none"
                            xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M7.30978 3.59676L2.18753 8.71901C2.11695 8.78962 2.07264 8.88225 2.06197 8.98151L1.75265 11.7645C1.74589 11.8256 1.75209 11.8875 1.77086 11.9461C1.78963 12.0046 1.82054 12.0586 1.86158 12.1044C1.90262 12.1503 1.95286 12.1869 2.00902 12.212C2.06519 12.2371 2.12601 12.2501 2.18753 12.2501C2.20361 12.2501 2.21967 12.2492 2.23566 12.2474L5.02034 11.9381C5.11961 11.9275 5.21223 11.8832 5.28284 11.8126L10.4033 6.69076L7.30978 3.59676ZM12.4093 2.82851L11.1716 1.59083C10.9255 1.34477 10.5917 1.20654 10.2437 1.20654C9.89563 1.20654 9.56185 1.34477 9.31572 1.59083L7.92841 2.97814L11.022 6.07214L12.4097 4.68439C12.6557 4.4382 12.7939 4.10439 12.7938 3.75636C12.7937 3.40833 12.6554 3.07458 12.4093 2.82851Z"
                                fill="#066AC9" />
                        </svg>

                    </a>
                </p>
               </div>
                <form class="form-div" id="verify_otp_form">
                    <div class="pin-input">
                        <input type="tel" name="digit1" class="input-field otp_enter"
                        oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');"
                        maxlength="1" value="" autocomplete="off" aria-label="code">
                    <input type="tel" name="digit2" class="input-field otp_enter"
                        oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');"
                        maxlength="1" value="" autocomplete="off" aria-label="code">
                    <input type="tel" name="digit3" class="input-field otp_enter"
                        oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');"
                        maxlength="1" value="" autocomplete="off" aria-label="code">
                    <input type="tel" id="" name="digit4" class="input-field otp_enter"
                        oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');"
                        maxlength="1" value="" autocomplete="off" aria-label="code">
                    </div>

                    <p class="wrong-otp-error" style="display: none">Invalid Pin</p>
                    <p class="resend-text" id="resend_timer">Resend OTP in <span class="timer" id="timer"   
                        >00.30</span></p>
                    {{-- <button class=" resend-btn" >Resend OTP</button> --}}
                    <p class="resend-text resend-btn" id="resend_block">Didn't get it?<a 
                            href="javascript:;" class="resend-link"> Resend Code</a></p>
                    <button type="submit" class="form-btn submit-button">Verify & Continue
                        <span class="spin-loader" style="display: none;"></span>
                    </button>
                </form>
            <!--hide when screen-2 is visible-->
            
        </div>
        {{-- do not show the last successful screen as user will be redirect to the dashboard once logged in  --}}
        {{-- <div class="form-body step-4" style="display: none">
            <lottie-player class="popup-img" src="{{ asset('frontend') }}/assets-desktop/js/success.json"
            background="transparent" speed="1" width="100%" hight="100%"
            style="width:133px; height:102px;" loop autoplay></lottie-player>
            <p class="head">Login Successful!</p>
        </div> --}}
    </div>
    </div>
@endsection

@section('frontend_links')
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/18.2.1/css/intlTelInput.css" integrity="sha512-s51TDsIcMqlh1YdQbF3Vj4StcU/5s97VyLEEpkPWwP0CJfjZ/C5zAaHnG+DZroGDn1UagQezDEy61jP4yoi4vQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="{{ asset('frontend') }}/student-panel-old/css/login.css?v={{ env('ASSETS_VERSION') }}">
@endsection


@section('script')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/18.2.1/js/intlTelInput.min.js" integrity="sha512-uZZS8rsETXJQX6Jy57Zdc7PAmP83GCjC1F/LX0xUj12wY5SlfUX+CVnYFEX89doutQPeFbI9FjUCkpuTWqlBwg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="{{ asset('frontend') }}/student-panel-old/js/input-field.js"></script>
    {{-- <script src="{{ asset('frontend') }}/student-panel-old/js/login.js?v={{now()->format('his')}}"></script> --}}
    <script src="{{ asset('frontend') }}/assets-desktop/js/lottie-player.js?v={{ env('ASSETS_VERSION') }}"></script>
    <script src="{{ asset('frontend') }}/assets-desktop/js/validation.js?v={{ env('ASSETS_VERSION') }}"></script>

    
    {{-- <script src='https://www.google.com/recaptcha/api.js'></script> --}}
    {{-- <script>
   
        // Login See Password Button Function 
        $('#eyeButton').on('click', function(){
            let input = $('#password');
            let eye = $('.fas');
            input.attr('type') === 'password' ? input.attr('type','text') : input.attr('type','password');
            $('.eyebutton').hasClass('ph-eye-slash') ? $('.eyebutton').addClass('ph-eye').removeClass('ph-eye-slash') : $('.eyebutton').addClass('ph-eye-slash').removeClass('ph-eye');
        });


        function passToText(id, icon) {
            var input = $('#' + id);
            var eyeIcon = $('#' + icon);
            if (input.is('input[type="password"]')) {
                eyeIcon.html('<i class="ph-eye-slash @error('password') m-3 @enderror"></i>');
                input.attr('type', 'text');
            } else {
                eyeIcon.html('<i class="ph-eye @error('password') m-3 @enderror"></i>');
                input.attr('type', 'password');
            }
        }

        function loginCredentials(type) {
            if (type == 'candidate') {
                $('#email').val('candidate@mail.com')
                $('#password').val('password')
            } else {
                $('#email').val('company@mail.com')
                $('#password').val('password')
            }

            $('#login_form').submit();
        }

        if ({{ request('social_register') ?? 0 }} == 1) {
            LoginService();
        }

        function LoginService() {
            $("#ModalBtn").css("display", "block");
        }
    </script> --}}

<script>
    var userLogged = false;
	var userVerified = false;
	var reset = '';
    var resendLink = false;

	$(document).ready(function() {

		let interval;
		$("#plan-lead-form").on('submit', function(e) {
            e.preventDefault();
            mobileValidation();
            
			if (interval) {
                clearInterval(interval);
            }

            var formData = new FormData($(this)[0]);
            var _token = $('meta[name="csrf-token"]').attr('content');
            formData.append("_token", _token);

            var country = $('.country-select').val();
            country = country.split('@#$?');
            country_code = country[1];
            country = country[0];

            formData.append('country', country);
            formData.append('country_code', country_code);

			formData.append('reset', reset);
            if (ValidateForm($(this))) {
                $('.loader , .spin-loader').show();
                $('.submit-button').prop("disabled", true);
                
                if(!userLogged){
                    $.ajax({
                        type: 'POST',
                        url: '/student/otp-sent',
                        data: formData,
                        cache: false,
                        processData: false,
                        contentType: false,
                        success: (res) => {
                            if (res.status) {
                                $('.submit-button').prop("disabled", false);
                                $('.loader , .spin-loader').hide();
                                $('.step-1').hide();
                                $('.step-2').hide();
                                $('.step-3').show();
                                $('.resend-btn').hide()
                                $('#timer').html('00.30');
                                $('#resend_timer').show()
                                $('.wrong-otp-error').hide()
                                var number = country_code + ' ' + $('.phone-validate').val();
                                $('.phone_edit').html('+' + number);
                                // Get the timer element
                                var timerElement = document.getElementById('timer');

                                var timerValue = timerElement.innerHTML.split('.');

                                var seconds = parseInt(timerValue[0]) * 60 + parseInt(timerValue[1]);

                                // Function to update the timer
                                function updateTimer() {
                                    seconds--;
                                    if (seconds < 0) {
                                        clearInterval(interval);
                                        timerElement.innerHTML = '00.00';
                                        $('.resend-btn').show();
                                        $('#resend_timer').hide();
                                    } else {
                                        var minutes = Math.floor(seconds / 60);
                                        var remainingSeconds = seconds % 60;
                                        timerElement.innerHTML = (minutes < 10 ? '0' : '') + minutes + '.' +
                                            (remainingSeconds < 10 ? '0' : '') + remainingSeconds;
                                    }
                                }

                                // Call the updateTimer function every second
                                interval = setInterval(updateTimer, 1000);
                            } else if(res.status == 2){
                                $('.submit-button').prop("disabled", false);
                                $('.loader , .spin-loader').hide();
                                $('.step-1').hide();
                                $('.step-2').show();
                                var number = country_code + ' ' + $('.phone-validate').val();
                                $('.phone_edit').html('+' + number);
                                $('.wrong-otp-error').hide();
                                $('.login-condition').text('Enter Your 4 digit Login Pin');
                                $('.small-head').show();
                            } else{
                                $('.submit-button').prop("disabled", false);
                                $('.loader , .spin-loader').hide();
                            }
                            $(':input', '#plan-lead-form')
                                .not(':button, :submit, :reset, :hidden')
                                .val('');
						}, error: function(xhr, status, error) {
                            $('.submit-button').prop("disabled", false);
                            $('.loader , .spin-loader').hide();
                        }
                    });
                } else {
                    $('.submit-button').prop("disabled", false);
                    $('.loader , .spin-loader').hide();
                    $('.step-1').hide();
                    $('.login-condition').text('Enter Your 4 digit Login Pin');
                    $('.small-head').show();
                    $('.step-2').show();
                    var number = country_code + ' ' + $('.phone-validate').val();
                    $('.phone_edit').html('+' + number);
                }
            }
        });

		$("#verify_otp_form").on('submit', function(e) {
            e.preventDefault();
            formData = new FormData($(this)[0]);
            var _token = $('meta[name="csrf-token"]').attr('content');
            formData.append("_token", _token);
            var num1 = $('input[type="tel"][name="digit1"]').val();
            var num2 = $('input[type="tel"][name="digit2"]').val();
            var num3 = $('input[type="tel"][name="digit3"]').val();
            var num4 = $('input[type="tel"][name="digit4"]').val();
            var otp = num1 + '' + num2 + '' + num3 + '' + num4;
            formData.append("otp", otp);

            if (ValidateForm($(this))) {
                $('.loader , .spin-loader').show();
                $('.submit-button').prop("disabled", true);
                $.ajax({
                    type: 'POST',
                    url: '/student/otp-verification',
                    data: formData,
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: (res) => {
                        if (res.status) {
                            $(':input', '#verify_otp_form')
                                .not(':button, :submit, :reset, :hidden, #date')
                                .val('');
                            $('.submit-button').prop("disabled", false);
                            $('.loader , .spin-loader').hide();
                            $('.step-3').hide();
                            $('.step-2').show();
                            // $('#profile_complete').val(res.profile);
                            $('.wrong-otp-error').hide()
                            if (res.profile == 100) {
                                profile_complete = res.profile;
                                showCourseFilter()
                            }
                            userVerified = true;
							$('.small-head').hide();
                            $('.login-condition').text('Create your 4 digit Login PIN');
                        } else if (res.status == 0) {
                            $('.wrong-otp-error').show()
                            $('.submit-button').prop("disabled", false);
                            $('.loader , .spin-loader').hide();
                        }
                    }, error: function(xhr, status, error) {
                        $('.submit-button').prop("disabled", false);
                        $('.loader , .spin-loader').hide();
                    }
                });
            }
        });
	});	


	$(document).ready(function(){
		$('.single-filter-tab').on('click', function(){
			$('.single-filter-tab').removeClass('active');
			$(this).addClass('active');
		})

		$(document).on('input', '.phone-validate', handleInputAndChange);
		$(document).on('change', '.country-select', handleInputAndChange);

	});

	function handleInputAndChange() {
		var phoneValue = $('.phone-validate').val();
		var countryValue = $('.country-select').val();
		// Check both conditions before proceeding
		if (phoneValue.length === 10 && countryValue !== '') {
			mobileValidation();
		}
	}

	function mobileValidation()
	{
		$('.spin-loader').show();
		var phone = $('.phone-validate').val();
		var country = $('.country-select').val();
		var country_code = country.split('@#$?');
		country_code = country_code[1];
		$.ajax({
			type: 'POST',
			url: '/student/mobile-verification',
			data: {
				country_code: country_code,
				phone: phone,
				_token: $('meta[name="csrf-token"]').attr('content')
			},
			dataType: 'json',
			success: (res) => {
				if (res.status) {
					// Old User
					$('.name-input').hide();
					$('.spin-loader').hide();
					userLogged = true;
				} else if (res.status == 0) {
					// New User
					$('.name-input').show();
					$('.spin-loader').hide();
					userLogged = false;
				}
			}
		});
	}

	var countryName = '{{ getLocationInfoByIp() }}';
        countryValue = JSON.parse(countryName);

        var countryName = countryValue.country_name;

        $.ajax({
            url: "/countryArray.php",
            success: function(res) {
                $(".country-select").html(res);
                $('.country-select').val(function() {
                    return $('option[data-country="' + countryName + '"]', this).val();
                });
                selectedOption = $("option:selected", '.country-select');
                $(selectedOption).text(`${$(selectedOption).attr("data-country")} +${$(selectedOption).attr("data-code")}`);
                $("option:selected", '.country-select').text(
                    `${$(selectedOption).attr("data-sort_code")} +${$(selectedOption).attr("data-code")}`
                );
            }
        });

	$(".country-select").change(function(){
		$("option",this).each((i,e) => {
			if($(e).attr("data-code") != 'Country' || $(e).attr("value") != ''){
				$(e).text(`${$(e).attr("data-country")} +${$(e).attr("data-code")}`);
			}else{
				$(e).text(`${$(e).attr("data-country")} ${$(e).attr("data-code")}`);
			}
		})
		selectedOption = $("option:selected", this);
		if($(selectedOption).attr("data-code") == 'Country'){
			$("option:selected", this).text(`${$(selectedOption).attr("data-sort_code")} ${$(selectedOption).attr("data-code")}`)
		}else{
			$("option:selected", this).text(`${$(selectedOption).attr("data-sort_code")} +${$(selectedOption).attr("data-code")}`)
		}
	});

	
	actualPin = [];

	if ('{{ $device }}' == 'desktop') {
		function handlePinInput(index, inputField) {
			// Allow only numeric input
			$('.wrong-otp-error').hide()
			inputField.value = inputField.value.replace(/[^0-9]/g, '');

			// Store the real value in the array
			actualPin[index] = inputField.value;

			// Display the entered digit for 1 second, then replace with "*"
			setTimeout(() => {
				inputField.value = '*';
			}, 1000);

			// Move focus to the next input field
			if (index < 3 && inputField.value !== '') {
				document.getElementById(`pin-input-${index + 1}`).focus();
			}
		}

		function handleKeyDown(event, index) {
			$('.wrong-otp-error').hide()
			// Move to the previous input field on backspace
			if (event.key === 'Backspace') {
				const currentInput = document.getElementById(`pin-input-${index}`);
				const previousInput = document.getElementById(`pin-input-${index - 1}`);

				// Move focus to the previous input field
				if (index > 0 && currentInput.value === '') {
					previousInput.focus();
				}

				// Clear the value of the current input
				currentInput.value = '';
			}

			$('.wrong-otp-error').hide()
			// Allow only numeric input
			if (!/[0-9]/.test(event.key)) {
				event.preventDefault();
			}
		}
	} else {
		function handlePinInput(index, inputField) {
			// Allow only numeric input
			inputField.value = inputField.value.replace(/[^0-9]/g, '');

			$('.wrong-otp-error').hide()
			// Store the real value in the array
			actualPin[index] = inputField.value;

			// Move focus to the next input field
			if (index < 3 && inputField.value !== '') {
				document.getElementById(`pin-input-${index + 1}`).focus();
			}
		}

		function handleKeyDown(event, index) {
			// Move to the previous input field on backspace
			if (event.key === 'Backspace') {
				const currentInput = document.getElementById(`pin-input-${index}`);
				const previousInput = document.getElementById(`pin-input-${index - 1}`);

				// Move focus to the previous input field
				if (index > 0 && currentInput.value === '') {
					previousInput.focus();
				}

				// Clear the value of the current input
				currentInput.value = '';
			}
			$('.wrong-otp-error').hide()
			// Allow only numeric input
			if (!/[0-9]/.test(event.key)) {
				event.preventDefault();
			}
		}
	}


	$(document).on('submit', '#user-pin-form', function(e) {
            e.preventDefault();

            formData = new FormData($(this)[0]);
            var _token = $('meta[name="csrf-token"]').attr('content');
            formData.append("_token", _token);
            actualPin1 = actualPin.join('');
            formData.append("pin", actualPin1);

            if (ValidateForm($(this))) {
                $('.loader , .spin-loader').show();
                $('.submit-button').prop("disabled", true);
                if(!userVerified){
                    $.ajax({
                        type: 'POST',
                        url: '/student/pin-verification',
                        data: formData,
                        cache: false,
                        processData: false,
                        contentType: false,
                        success: (res) => {
                            if (res.status) {
                                $(':input', '#user-pin-form')
                                    .not(':button, :submit, :reset, :hidden')
                                    .val('');
                                $('.submit-button').prop("disabled", false);
                                $('.loader , .spin-loader').hide();
                                window.location.reload();

                            } else if (res.status == 0) {
                                $('.wrong-pin-error').show()
                                $('.submit-button').prop("disabled", false);
                                $('.loader , .spin-loader').hide();
                            }
                        }, error: function(xhr, status, error) {
                            $('.submit-button').prop("disabled", false);
                            $('.loader , .spin-loader').hide();
                        }
                    });
                } else{
                    $.ajax({
                        type: 'POST',
                        url: '/student/pin-generate',
                        data: formData,
                        cache: false,
                        processData: false,
                        contentType: false,
                        success: (res) => {
                            if (res.status) {
                                $(':input', '#user-pin-form')
                                    .not(':button, :submit, :reset, :hidden')
                                    .val('');
                                $('.submit-button').prop("disabled", false);
                                $('.loader , .spin-loader').hide();
                                $('#pin-popup').hide();
                                    // Retrieve the localStorage flag
                                    var hasTablet = localStorage.getItem('hasTablet');

                                    // Check the value and perform actions accordingly
                                window.location.reload();

                            } else if (res.status == 0) {
                                $('.wrong-pin-error').show()
                                $('.submit-button').prop("disabled", false);
                            }
                        }, error: function(xhr, status, error) {
                            $('.submit-button').prop("disabled", false);
                        }
                    });
                }
            }
        });


	$('[data-close="model"]').on('click', function() {
		// $('#get-in-touch-popup').hide();
		// $('#complete-profile-popup').hide();
		// $('#document-incomplete').hide();
		$('#login-success').hide();
	});

	var inputFields = document.querySelectorAll('.otp_enter');

	// Add input event listener to each input field
	inputFields.forEach(function(inputField, index) {
		inputField.addEventListener('input', function() {
			// If the input value is not empty and the length is equal to the maxlength
			if (this.value && this.value.length === parseInt(this.getAttribute('maxlength'))) {
				// If there is a next input field, focus on it
				if (index < inputFields.length - 1) {
					inputFields[index + 1].focus();
				}
			}
		});

		// Add keydown event listener to each input field
		inputField.addEventListener('keydown', function(event) {
			// If the backspace key is pressed and the input value is empty
			if (event.keyCode === 8 && !this.value) {
				// If there is a previous input field, focus on it
				if (index > 0) {
					inputFields[index - 1].focus();
				}
			}
		});
	});

	$('.resend-link').on('click', function() {
        if(resendLink === true){
			userLogged = false;
		}
		$('#plan-lead-form').submit();
	});

	$('.reset-link').on('click', function() {
		reset = 'reset';
		userLogged = false;
        resendLink = true;
        $('.loader , .spin-loader').show();
		$('#plan-lead-form').submit();
	});

    $(document).on('click', '.edit-icon', function() {
        $('.step-3').hide()
        $('.step-2').hide()
        $('.step-1').show()
    })

    if ('OTPCredential' in window) {
        window.addEventListener('DOMContentLoaded', async (e) => {
            try {
                const otpCredential = await navigator.credentials.get({
                    otp: { transport: ['sms'] },
                    // Remove the signal
                    // signal: ac.signal,
                });

                if (otpCredential && otpCredential.code) {
                    fillOtpInForm(otpCredential.code);
                    console.warn(`Received OTP: ${otpCredential.code}`);
                } else {
                    console.warn('No OTP received or invalid OTP credential.');
                }
            } catch (err) {
                console.error('Error obtaining OTP credential:', err);
            }
        });
    } else {
        alert('WebOTP not supported!');
    }

    function fillOtpInForm(otp) {
        for (let i = 0; i < otp.length; i++) {
            $('input[name="digit' + (i + 1) + '"]').val(otp[i]);
        }
        $('#verify_otp_form').submit();   
    }

    $(window).on('unload', function() {
		$('.phone-validate').val('');
	});
    </script>
@endsection
@section('css')
@endsection
