<!DOCTYPE html>
<html lang="en">
<head>
    <?php $this->load->view('templates/components/head'); ?>
</head>
<body>
	<div class="PageLoaderHolder">
        <div class="PageLoader"></div>
    </div>
	<?php $this->load->view('templates/components/footer-scripts'); ?>
	<script src="<?php echo base_url().'assets/js/parsley.js'; ?>"></script>
    <main style="--header-height: 0px;">

        <section class="login">
            <div class="container">
                <div class="text-center mb-3">
                    <img width="122" class="header__logo" src="<?php echo base_url(); ?>assets/img/logo-color.svg" alt="" class="header__logo">
                </div>
		                
                <div class="card">
                    <div class="card-body">
                        <?php
		                    echo form_open('javascript:;', 'name="login_form" id="login_form" method="POST" data-parsley-validate=""');
		                ?>
                            <h5 class="text-center pb-3">Log in to TFI Portal</h5>
                            <div class="mb-3">
                            	<label for="email">Email<span class="required">*</span></label>
                                <input 
                                	type="email" 
                                    class="w-100 form-control" 
                                    id="email"
                                    name="email"
                                    data-parsley-trigger="keyup"
                                    data-parsley-errors-container="#email_error"
                                    required
								/>
                                <p class="error" id="email_error"></p>
                            </div>
                            <div class="mb-4">
                            	<label for="password">Password<span class="required">*</span></label>
                                <input 
                                	type="password" 
                                    class="w-100 form-control" 
                                    id="password"
                                    name="password"
                                    data-parsley-trigger="keyup"
                                    data-parsley-errors-container="#password_error"
                                    required
								/>
                                <p class="error" id="password_error"></p>
                            </div>
                            
                            <button type="submit" class="btn btn-primary" id="login_btn" disabled>Log in</button>

                        </form>

                        <?php
                            echo form_open('javascript:;', 'name="otp_verify_submit" id="otp_verify_submit" method="POST" data-parsley-validate="" style="display: none;"');
                        ?>
                        		<h5 class="text-center pb-3">Please enter the temporary login code sent to your email address</h5>
                        		<input type="hidden" name="email" value="" id="otp_verify_email" />
                        		<div class="mb-4">
				                    <label class="form-label mb-0">Enter the OTP</label>
				                    <div class="d-flex gap-4">
				                        <input type="text" class="form-control text-center otp-input" maxlength="1">
				                        <input type="text" class="form-control text-center otp-input" maxlength="1">
				                        <input type="text" class="form-control text-center otp-input" maxlength="1">
				                        <input type="text" class="form-control text-center otp-input" maxlength="1">
				                    </div>

				                    <div class="d-flex align-items-center justify-content-between">
                                        <div class="invalid-feedback d-block" id="email_otp_error"></div>
                                        <a href="javascript:;" style="font-size: 12px;" class="text-end form-text flex-shrink-0 cursor-pointer resend_otp d-none" class="">Resend OTP</a>
                                    </div>
                                    <div id="timer" style="font-size: 12px;" class="text-end form-text"></div>
				                </div>

				                <button type="submit" id="otp_verify_btn" class="btn btn-primary" disabled>Verify Email</button>

                        </form>

                        <div class="alert alert_message alert-danger mt-3 d-none" role="alert"></div>
                    </div>
                </div>

            </div>
        </section>

    </main>

    <input type="hidden" id="redirect_url" value="<?php echo isset($redirect_url) ? $redirect_url : ''; ?>">
    
	<?php $this->load->view('templates/components/footer'); ?>
	<script type="text/javascript">

		$(document).ajaxStart(function(){
	        // Show image container
	        $(".PageLoaderHolder").fadeIn('slow');
	    });

	    $(document).ajaxComplete(function(){
	        // Hide image container
	        $(".PageLoaderHolder").fadeOut('slow');
	    });

		$(document).ready(function(){
            $("#login_form").attr("action", 'javascript:;');
            $("#otp_verify_submit").attr("action", 'javascript:;');
        });

        let countdown = 20;
        let resendAttempts = 0;
		const maxResendAttempts = 2;
		let countdownInterval;

        function updateTimer() {
			const timerElement = document.getElementById('timer');
			timerElement.innerText = `Resend OTP in ${countdown} seconds`;
		}

		function showTimer(){
			updateTimer();

			countdownInterval = setInterval(() => {
				countdown--;

				// Update the timer display
        		updateTimer();
        		// Check if the countdown is complete
        		if (countdown === 0) {
        			countdown = 20;

        			if (resendAttempts >= maxResendAttempts) {
			            $(".resend_otp").addClass("d-none");
			        }else{
			        	$(".resend_otp").removeClass("d-none");
			        }
			        $("#timer").addClass("d-none");

        			clearInterval(countdownInterval);
        		}
			}, 1000);
		}


		$('#login_form').parsley().on('field:validated', function() {
	        var ok = $('.parsley-error').length === 0;
	       	$('.bs-callout-info').toggleClass('hidden', !ok);
	       	$('.bs-callout-warning').toggleClass('hidden', ok);

	       	var isValid = $('#login_form').parsley().isValid();
	       	$('#login_btn').prop('disabled', !isValid);
	    })
	    .on('form:submit', function() {
	        var formData = new FormData($("#login_form")[0]);
	        var base_url = '<?php echo base_url(); ?>';
	        var url = base_url+"login";

	        $(".error").html("");
	        $(".alert").html("");
	        $(".alert").addClass("d-none");

	        $.ajax({
	            type: "POST",
                dataType: "json",
                url: url,
                data: formData,
                //async: false,
                cache: false,
                contentType: false,
                processData: false,
	            beforeSend:function(){
	            	$(".formBox button svg").css("opacity", 1);
	            },
	            success: function(result) {

	            	if(result["status"] === false){
	           			$(".alert-danger").html(result['message']);
	           			$(".alert-danger").removeClass("d-none");
	            	}else{

	            		$("#otp_verify_email").val(result['email']);
	            		$("#display_email").html(result['email']);

	            		$("#login_form").fadeOut(function(){
							$("#otp_verify_submit").fadeIn();
							$(".resend_otp").addClass("d-none");
	        				$("#timer").removeClass("d-none");
		            		showTimer();
						});
	                }

	            },
	            error: function(result) {
	            	$(".alert-danger").html("Failed to perform this action.");
	           		$(".alert-danger").removeClass("d-none");
	            }
	        });
	    });

	    $(document).on("click", ".resend_otp", function(){
	    	if (resendAttempts < maxResendAttempts) {
	    		resendAttempts++;
		    	var email = $("#otp_verify_email").val();

		    	if(email){
		    		var base_url = '<?php echo base_url(); ?>';
			        var url = base_url+"resend-otp";
			        var data = {};

			        $(".error").html("");
			        $(".alert").html("");
			        $(".alert").addClass("d-none");


			        data["email"] = email;

			        var contentLoad = call_ajax(url, data, 'JSON', true, 'POST');
	                contentLoad.done(function(result){

	                    if(result["status"] === false){
		           			$(".alert-danger").html(result['message']);
	           				$(".alert-danger").removeClass("d-none");
		            	}else{
		            		
		            		$(".resend_otp").addClass("d-none");
	        				$("#timer").removeClass("d-none");
		            		showTimer();
		                }
	                });

		    	}else{
		    		$(".alert-danger").html("Invalid Email Address.");
	           		$(".alert-danger").removeClass("d-none");
		    	}
		    }else{
		    	$(".alert-danger").html("Maximum resend attempts reached. Please try again later.");
	           	$(".alert-danger").removeClass("d-none");
		    }
    	});

    	// Listen for changes in OTP input fields
		function enable_disbaled_verify_email(){
			var otpFilled = true;
		    $('.otp-input').each(function() {
		        if ($(this).val() === '') {
		            otpFilled = false;
		            return false; // Exit each loop early
		        }
		    });
		    $('#otp_verify_btn').prop('disabled', !otpFilled);
		    $(".invalid-feedback").html("");
		}

		// Function to distribute pasted OTP across inputs
		function handlePaste(e) {
		    const data = e.clipboardData.getData('text');
		    const otpInputs = document.querySelectorAll('.otp-input');

		    // Split the pasted data into individual characters and fill the inputs
		    data.split('').forEach((value, index) => {
		        if (index < otpInputs.length) {
		            otpInputs[index].value = value; // Assign each digit to corresponding input
		            if (index < otpInputs.length - 1) {
		                otpInputs[index + 1].focus(); // Move focus to next input
		            }
		        }
		    });

		    // Prevent the default paste behavior
		    e.preventDefault();
		    

		    enable_disbaled_verify_email()
		}

		// Function to move focus to next input on input
		function handleInput(e) {
		    const input = e.target;
		    const nextInput = input.nextElementSibling;

		    // Move focus to next input if it exists and current input has a value
		    if (input.value && nextInput && nextInput.classList.contains('otp-input')) {
		        nextInput.focus();
		    }

		    enable_disbaled_verify_email();
		}

		// Function to clear the input on backspace if OTP is wrong
		function handleBackspace(e) {
		    const input = e.target;
		    const previousInput = input.previousElementSibling;

		    if (e.key === 'Backspace' && input.value === '') {
		        // Clear the input
		        input.value = '';
		        // Move focus to previous input if it exists
		        if (previousInput && previousInput.classList.contains('otp-input')) {
		            previousInput.focus();
		        }
		    }
		}

		// Attach event listeners to each OTP input
		document.querySelectorAll('.otp-input').forEach(input => {
		    input.addEventListener('paste', handlePaste);
		    input.addEventListener('input', handleInput);
		    input.addEventListener('keydown', handleBackspace);
		});
		
	    $('#otp_verify_submit').parsley().on('field:validated', function() {
	        var ok = $('.parsley-error').length === 0;
	        $('.bs-callout-info').toggleClass('hidden', !ok);
	        $('.bs-callout-warning').toggleClass('hidden', ok);
	    })
	    .on('form:submit', function() {
	        var formData = new FormData($("#otp_verify_submit")[0]);
	        var base_url = '<?php echo base_url(); ?>';
	        var url = base_url+"login-verify";

	        var otpValue = '';
		    $('.otp-input').each(function() {
		        otpValue += $(this).val();
		    });

		    var redirect_url = $("#redirect_url").val();

		    // Prepare form data
		    formData.append('email_otp', otpValue);
		    formData.append('redirect_url', redirect_url);
		    formData.append('ref1', '<?php echo isset($ref1) ? $ref1 : ""; ?>');
		    formData.append('ref2', '<?php echo isset($ref2) ? $ref2 : ""; ?>');

	        $(".error").html("");
	        $(".alert").html("");
	        $(".alert").addClass("d-none");

	        $.ajax({
	            type: "POST",
                dataType: "json",
                url: url,
                data: formData,
                //async: false,
                cache: false,
                contentType: false,
                processData: false,
	            beforeSend:function(){

	            },
	            success: function(result) {

	            	if(result["status"] === false){
	           			$(".alert-danger").html(result['message']);
	           			$(".alert-danger").removeClass("d-none");
	            	}else{

	            		setTimeout(function () {
		                	window.location.href = result['redirect_url'];
		                }, 1000);
	                }

	            },
	            error: function(result) {
	            	$(".alert-danger").html("Failed to perform this action.");
	           		$(".alert-danger").removeClass("d-none");
	            }
	        });
	    });
	</script>
</body>
</html>