<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>

$(document).ready(function () {

    /*
    |--------------------------------------------------------------------------
    | INITIAL STEP LOCK
    |--------------------------------------------------------------------------
    */

    $('.step-item').each(function(index){

        if(index !== 0){

            $(this).addClass('locked d-none');
        }
    });

});


function showLoader(message='Processing...'){

    $('#loaderText').text(message);

    $('#globalLoader').css('display','flex');
}

function hideLoader(){

    $('#globalLoader').hide();
}

function clearValidationErrors(){

    $('.error-message').remove();

    $('.input-error').removeClass('input-error');

    $('.step-message').html('');
    $('#declarationError').html('');
     $('#termsError').html('');
}

function showInputError(inputId, message){

    $('#' + inputId).addClass('input-error');

    if($('#' + inputId).next('.error-message').length == 0){

        $('#' + inputId).after(
            '<div class="error-message">'+message+'</div>'
        );
    }
}

function showStepMessage(type, message, target){

    let className = '';

    if(type == 'success'){
        className = 'success-message';
    }

    if(type == 'error'){
        className = 'error-message';
    }

    if(type == 'loading'){
        className = 'loading-message';
    }

    $(target).html(
        '<div class="'+className+'">'+message+'</div>'
    );
}

/*
|--------------------------------------------------------------------------
| GO TO STEP
|--------------------------------------------------------------------------
*/

function goToStep(stepNumber) {

    $('.form-step').removeClass('active');

    $('#step' + stepNumber).addClass('active');

    $('.step-item').removeClass('active');

    $('.step-item').eq(stepNumber - 1)
        .addClass('active');

    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}

/*
|--------------------------------------------------------------------------
| UNLOCK STEP
|--------------------------------------------------------------------------
*/

function unlockStep(stepNumber){

    $('.step-item').eq(stepNumber - 1)
        .removeClass('locked d-none');
}

/*
|--------------------------------------------------------------------------
| PREVIOUS STEP
|--------------------------------------------------------------------------
*/

function prevStep(stepNumber){

    goToStep(stepNumber - 1);
}

/*
|--------------------------------------------------------------------------
| SIDEBAR CLICK
|--------------------------------------------------------------------------
*/

$('.step-item').click(function () {

    if($(this).hasClass('locked')){

        return false;
    }

    let index = $(this).index() + 1;

    goToStep(index);
});

/*
|--------------------------------------------------------------------------
| STEP 1 VERIFY USER
|--------------------------------------------------------------------------
*/

function verifyUser() {

    clearValidationErrors();

    let organization = $('#organization').val();
    let phone = $('#phone').val();
    let consent = $('#creditCheckConsent').is(':checked');

    // if(organization == '' || organization == 'Select'){

    //     showInputError(
    //         'organization',
    //         'Please select organization'
    //     );

    //     return;
    // }

    if(phone == ''){

        showInputError(
            'phone',
            'Please enter phone number'
        );

        return;
    }

    if(phone.length != 10){

        showInputError(
            'phone',
            'Phone number must be 10 digits'
        );

        return;
    }

if(!consent){

    $('#consentError').html(
        '<div class="error-message">Please accept terms and conditions</div>'
    );

    return;
}

    showLoader('Verifying...');

    showStepMessage(
        'loading',
        'Verifying... Please wait',
        '#step1Message'
    );

    $.ajax({

        url: "<?php echo e(url('verify-user')); ?>",

        type: "POST",

        data: {

            _token: "<?php echo e(csrf_token()); ?>",

            organization: organization??'',

            phone: phone
        },

        success: function(response) {

            hideLoader();

            if(response.status){

                $('.otpSection').removeClass('d-none');

                $('#verifyNumberBtn').hide();

                showStepMessage(
                    'success',
                    'OTP Sent Successfully.',
                    '#step1Message'
                );

            } else {

                showStepMessage(
                    'error',
                    response.message,
                    '#step1Message'
                );
            }
        },

        error: function(xhr){

            hideLoader();

            console.log(xhr.responseText);

            showStepMessage(
                'error',
                'Something went wrong',
                '#step1Message'
            );
        }
    });
}

/*
|--------------------------------------------------------------------------
| VERIFY OTP
|--------------------------------------------------------------------------
*/
function verifyOtp() {

    clearValidationErrors();

    let otp = $('#otp').val();

    if(otp == ''){

        showInputError(
            'otp',
            'Please enter OTP'
        );

        return;
    }

    showLoader('Verifying OTP...');

    showStepMessage(
        'loading',
        'Verifying OTP... Please wait',
        '#step1Message'
    );

    $.ajax({

        url: "<?php echo e(url('verify-otp')); ?>",

        type: "POST",

        data: {

            _token: "<?php echo e(csrf_token()); ?>",

            otp: otp,

          

            phone: $('#phone').val(),

            email: $('#email').val()
        },

        success: function(response) {

            hideLoader();

            if(response.status){

                showStepMessage(
                    'success',
                    'OTP verified successfully',
                    '#step1Message'
                );

                let step = response.current_step;

                /*
                PREFILL DATA
                */

                fillApplicationData(response.application);

                /*
                LOAD REVIEW DATA AGAIN
                */

                loadReviewData();

                /*
                UNLOCK STEPS
                */

                for(let i = 2; i <= step; i++){

                    unlockStep(i);

                    completeStep(i);
                }

                /*
                GO TO SAVED STEP
                */

                goToStep(step);

            } else {

                showStepMessage(
                    'error',
                    response.message,
                    '#step1Message'
                );
            }
        },

        error: function(xhr){

            hideLoader();

            console.log(xhr.responseText);

            showStepMessage(
                'error',
                'Something went wrong',
                '#step1Message'
            );
        }
    });
}

/*
|--------------------------------------------------------------------------
| SAVE STEP 2
|--------------------------------------------------------------------------
*/

function saveStep2() {

    clearValidationErrors();

    if($('#full_name').val() == ''){

        showInputError(
            'full_name',
            'Enter full name'
        );

        return;
    }
    
    
    if($('#organization').val() == ''){

        showInputError(
            'organization',
            'Please select organization'
        );

        return;
    }
    

    if($('#dob').val() == ''){

        showInputError(
            'dob',
            'Select date of birth'
        );

        return;
    }

    if($('#gender').val() == ''){

        showInputError(
            'gender',
            'Select gender'
        );

        return;
    }

    if($('#marital_status').val() == ''){

        showInputError(
            'marital_status',
            'Select marital status'
        );

        return;
    }

    if($('#father_name').val() == ''){

        showInputError(
            'father_name',
            'Enter father/spouse name'
        );

        return;
    }

    if($('#aadhaar_number').val() == ''){

        showInputError(
            'aadhaar_number',
            'Enter Aadhaar number'
        );

        return;
    }

    if($('#aadhaar_number').val().length != 12){

        showInputError(
            'aadhaar_number',
            'Aadhaar must be 12 digits'
        );

        return;
    }

    if($('#pan_number').val() == ''){

        showInputError(
            'pan_number',
            'Enter PAN number'
        );

        return;
    }

    // Current Address Validation
    
    if($('#current_country').val() == ''){

        showInputError(
            'current_country',
            'Select current country'
        );

        return;
    }
    
    if($('#current_address').val() == ''){

        showInputError(
            'current_address',
            'Enter current Address'
        );

        return;
    }

    if($('#current_state').val() == ''){

        showInputError(
            'current_state',
            'Select current state'
        );

        return;
    }

    if($('#current_city').val() == ''){

        showInputError(
            'current_city',
            'Enter current city'
        );

        return;
    }

    // Permanent Address Validation
        if($('#permanent_address').val() == ''){

        showInputError(
            'permanent_address',
            'Enter permanent Address'
        );

        return;
    }
    
    if($('#permanent_country').val() == ''){

        showInputError(
            'permanent_country',
            'Select permanent country'
        );

        return;
    }

    if($('#permanent_state').val() == ''){

        showInputError(
            'permanent_state',
            'Select permanent state'
        );

        return;
    }

    if($('#permanent_city').val() == ''){

        showInputError(
            'permanent_city',
            'Enter permanent city'
        );

        return;
    }

    showLoader('Saving Personal Details...');

    showStepMessage(
        'loading',
        'Saving personal details...',
        '#step2Message'
    );

    $.ajax({

        url: "<?php echo e(url('save-step-2')); ?>",

        type: "POST",

        data: {

            _token: "<?php echo e(csrf_token()); ?>",

            full_name: $('#full_name').val(),
            organization: $('#organization').val(),

            dob: $('#dob').val(),

            gender: $('#gender').val(),

            marital_status: $('#marital_status').val(),

            father_name: $('#father_name').val(),

            aadhaar_number: $('#aadhaar_number').val(),

            pan_number: $('#pan_number').val(),
            
            current_address: $('#current_address').val(),
            permanent_address: $('#permanent_address').val(),

            // Current Address
            current_country: $('#current_country').val(),

            current_state: $('#current_state').val(),

            current_city: $('#current_city').val(),

            // Permanent Address
            permanent_country: $('#permanent_country').val(),

            permanent_state: $('#permanent_state').val(),

            permanent_city: $('#permanent_city').val(),

            address_duration: $('#address_duration').val(),

            pincode: $('#pincode').val()
        },

        success: function(response) {

            hideLoader();

            if(response.status){

                showStepMessage(
                    'success',
                    'Personal details saved successfully',
                    '#step2Message'
                );

                completeStep(2);

                unlockStep(3);
                loadReviewData();

                goToStep(3);
                

            } else {

                showStepMessage(
                    'error',
                    response.message,
                    '#step2Message'
                );
            }
        },

        error: function(xhr){

            hideLoader();

            console.log(xhr.responseText);

            showStepMessage(
                'error',
                'Something went wrong',
                '#step2Message'
            );
        }
    });
}

/*
|--------------------------------------------------------------------------
| SAVE STEP 3
|--------------------------------------------------------------------------
*/

function saveStep3() {

    clearValidationErrors();

    if(typeof calculateEMI === 'function'){
        calculateEMI();
    }

    if($('#loan_type').val() == ''){

        showInputError(
            'loan_type',
            'Select loan type'
        );

        return;
    }

    if($('#loan_amount').val() == ''){

        showInputError(
            'loan_amount',
            'Enter loan amount'
        );

        return;
    }

    if($('#loan_tenure').val() == ''){

        showInputError(
            'loan_tenure',
            'Enter loan tenure'
        );

        return;
    }

    if(parseInt($('#loan_tenure').val()) < 1 || parseInt($('#loan_tenure').val()) > 6){

        showInputError(
            'loan_tenure',
            'Loan tenure must be between 1 and 6 months'
        );

        return;
    }

    if($('#purpose_of_loan').val() == ''){

        showInputError(
            'purpose_of_loan',
            'Enter purpose of loan'
        );

        return;
    }

    if($('#preferred_emi').val() == ''){

        showInputError(
            'preferred_emi',
            'Enter preferred EMI'
        );

        return;
    }
    if($('#kit_cost').val() == ''){

        showInputError(
            'kit_cost',
            'Select Kit cost'
        );

        return;
    }
    if($('#down_payment').val() == ''){

        showInputError(
            'down_payment',
            'Select down payment'
        );

        return;
    }

    if((parseFloat($('#down_payment').val()) || 0) > (parseFloat($('#kit_cost').val()) || 0)){

        showInputError(
            'down_payment',
            'Down payment cannot be greater than kit cost'
        );

        return;
    }
    if($('#membership_fees').val() == ''){

        showInputError(
            'membership_fees',
            'Select membership fees'
        );

        return;
    }
    if($('#documentation_fees').val() == ''){

        showInputError(
            'documentation_fees',
            'Select documentation fees'
        );

        return;
    }
    if($('#rate_of_intrest').val() == ''){

        showInputError(
            'rate_of_intrest',
            'Select rate ofintrest'
        );

        return;
    }

    if($('#intrest_principle').val() == ''){

        showInputError(
            'intrest_principle',
            'Select intrest principle'
        );

        return;
    }

    if($('#loan_principle').val() == ''){

        showInputError(
            'loan_principle',
            'Select loan principle'
        );

        return;
    }

    
    if($('#deduction_principle').val() == ''){

        showInputError(
            'deduction_principle',
            'Select deduction principle'
        );

        return;
    }

    let kitCost = parseFloat($('#kit_cost').val()) || 0;
let downPayment = parseFloat($('#down_payment').val()) || 0;

let minimumDownPayment = kitCost * 0.20;

if (downPayment < minimumDownPayment) {

    Swal.fire({
        text: 'Minimum Down Payment should be 20% of Kit Cost.',
    });

    $('#down_payment').focus();

    return false;
}

    showLoader('Saving Loan Details...');

    showStepMessage(
        'loading',
        'Saving loan details...',
        '#step3Message'
    );

    $.ajax({

        url: "<?php echo e(url('save-step-3')); ?>",

        type: "POST",

        data: {

            _token: "<?php echo e(csrf_token()); ?>",

            loan_type: $('#loan_type').val(),

            loan_amount: $('#loan_amount').val(),

            loan_tenure: $('#loan_tenure').val(),

            purpose_of_loan: $('#purpose_of_loan').val(),

            total_interest: $('#total_interest').val(),

            total_payment: $('#total_payment').val(),

            preferred_emi: $('#preferred_emi').val(),

            processing_charges: $('#processing_charges').val(),

            employment_type: $('#employment_type').val(),
            kit_cost: $('#kit_cost').val(),
            down_payment: $('#down_payment').val(),
            membership_fees: $('#membership_fees').val(),
            documentation_fees: $('#documentation_fees').val(),
            rate_of_intrest: $('#rate_of_intrest').val(),
            loan_principle: $('#loan_principle').val(),
            intrest_principle: $('#intrest_principle').val(),
            deduction_principle: $('#deduction_principle').val(),
        },

        success: function(response) {

            hideLoader();

            if(response.status){

                showStepMessage(
                    'success',
                    'Loan details saved successfully',
                    '#step3Message'
                );

                completeStep(3);

                fillApplicationData(response.application);

                loadReviewData();

                unlockStep(4);

                goToStep(4);

            } else {

                showStepMessage(
                    'error',
                    response.message,
                    '#step3Message'
                );
            }
        },

        error: function(xhr){

            hideLoader();

            console.log(xhr.responseText);

            showStepMessage(
                'error',
                'Something went wrong',
                '#step3Message'
            );
        }
    });
}

/*
|--------------------------------------------------------------------------
| SAVE STEP 4
|--------------------------------------------------------------------------
*/

function saveStep4() {

    clearValidationErrors();

    if($('#monthly_income').val() == ''){

        showInputError(
            'monthly_income',
            'Enter monthly income'
        );

        return;
    }

    if($('#occupation').val() == ''){
        showInputError(
            'occupation',
            'Enter your working field'
        );
        return;
    }

    if($('#income_particulars').val() == ''){
        showInputError(
            'income_particulars',
            'Enter your income particulars'
        );
        return;
    }

      if($('#repayment_schedule').val() == ''){
        showInputError(
            'repayment_schedule',
            'Enter your repayment schedule'
        );
        return;
    }

      if($('#renewal_after').val() == ''){
        showInputError(
            'renewal_after',
            'Enter your renewal after'
        );
        return;
    }

      if($('#security_purpose').val() == ''){
        showInputError(
            'security_purpose',
            'Enter your security purpose'
        );
        return;
    }

    if($('#annual_income').val() == ''){

        showInputError(
            'annual_income',
            'Enter annual income'
        );

        return;
    }

    // if($('#salary_bank').val() == ''){
    //     return Swal.fire('Required','Enter salary bank name','error');
    // }

    // if($('#type_of_security').val() == ''){
    //     return Swal.fire('Required','Select security type','error');
    // }

    // if($('#estimated_value').val() == ''){
    //     return Swal.fire('Required','Enter estimated value','error');
    // }

    // if($('#ownership_details').val() == ''){
    //     return Swal.fire('Required','Enter ownership details','error');
    // }

    // if($('#bank_details').val() == ''){
    //     return Swal.fire('Required','Enter bank name','error');
    // }

    // if($('#account_number').val() == ''){
    //     return Swal.fire('Required','Enter account number','error');
    // }

    // if($('#ifsc_code').val() == ''){
    //     return Swal.fire('Required','Enter IFSC code','error');
    // }

    let existingIdProof =
        $('#idProofLink').attr('href');

    let existingAddressProof =
        $('#addressProofLink').attr('href');

    if(
        $('#id_proof')[0].files.length == 0 &&
        !existingIdProof
    ){

        showStepMessage(
            'error',
            'Upload ID proof',
            '#step4Message'
        );

        return;
    }

    if(
        $('#address_proof')[0].files.length == 0 &&
        !existingAddressProof
    ){

        showStepMessage(
            'error',
            'Upload address proof',
            '#step4Message'
        );

        return;
    }

    // if($('#income_proof')[0].files.length == 0){
    //     return Swal.fire('Required','Upload income proof','error');
    // }

    // if($('#bankstatements_proof')[0].files.length == 0){
    //     return Swal.fire('Required','Upload bank statements','error');
    // }

    showLoader('Uploading Documents...');

    showStepMessage(
        'loading',
        'Uploading documents... Please wait',
        '#step4Message'
    );

    let formData = new FormData();

    formData.append('_token', "<?php echo e(csrf_token()); ?>");

    /*
    |--------------------------------------------------------------------------
    | FILES
    |--------------------------------------------------------------------------
    */

    if($('#id_proof')[0].files[0]){

        formData.append(
            'id_proof',
            $('#id_proof')[0].files[0]
        );
    }

    if($('#address_proof')[0].files[0]){

        formData.append(
            'address_proof',
            $('#address_proof')[0].files[0]
        );
    }

    if($('#income_proof')[0].files[0]){

        formData.append(
            'income_proof',
            $('#income_proof')[0].files[0]
        );
    }

    if($('#bankstatements_proof')[0].files[0]){

        formData.append(
            'bankstatements_proof',
            $('#bankstatements_proof')[0].files[0]
        );
    }

    if($('#business_proof')[0].files[0]){

        formData.append(
            'business_proof',
            $('#business_proof')[0].files[0]
        );
    }


    if($('#on_boarding_letter')[0].files[0]){

        formData.append(
            'on_boarding_letter',
            $('#on_boarding_letter')[0].files[0]
        );
    }

    if($('#background_verification')[0].files[0]){

        formData.append(
            'background_verification',
            $('#background_verification')[0].files[0]
        );
    }

    if($('#file_name3')[0].files[0]){

        formData.append(
            'file_name3',
            $('#file_name3')[0].files[0]
        );
    }

    if($('#file_name4')[0].files[0]){

        formData.append(
            'file_name4',
            $('#file_name4')[0].files[0]
        );
    }

    if($('#file_name5')[0].files[0]){

        formData.append(
            'file_name5',
            $('#file_name5')[0].files[0]
        );
    }


    if($('#photo_proof')[0].files[0]){

        formData.append(
            'photo_proof',
            $('#photo_proof')[0].files[0]
        );
    }

    /*
    |--------------------------------------------------------------------------
    | TEXT FIELDS
    |--------------------------------------------------------------------------
    */

    formData.append(
        'other_income',
        $('#other_income').val()
    );

    formData.append(
        'annual_income',
        $('#annual_income').val()
    );

    // formData.append(
    //     'salary_bank',
    //     $('#salary_bank').val()
    // );

    // formData.append(
    //     'investments',
    //     $('#investments').val()
    // );

    // formData.append(
    //     'preperty_details',
    //     $('#preperty_details').val()
    // );

    // formData.append(
    //     'vehicles_owned',
    //     $('#vehicles_owned').val()
    // );

    // formData.append(
    //     'networth',
    //     $('#networth').val()
    // );

    // formData.append(
    //     'type_of_security',
    //     $('#type_of_security').val()
    // );

    // formData.append(
    //     'estimated_value',
    //     $('#estimated_value').val()
    // );

    // formData.append(
    //     'ownership_details',
    //     $('#ownership_details').val()
    // );

    // formData.append(
    //     'bank_details',
    //     $('#bank_details').val()
    // );

    // formData.append(
    //     'account_number',
    //     $('#account_number').val()
    // );

    formData.append(
        'monthly_income',
        $('#monthly_income').val()
    );

    formData.append(
        'occupation',
        $('#occupation').val()
    );
    formData.append(
        'income_particulars',
        $('#income_particulars').val()
    );
    formData.append(
        'repayment_schedule',
        $('#repayment_schedule').val()
    );
    formData.append(
        'renewal_after',
        $('#renewal_after').val()
    );
    formData.append(
        'security_purpose',
        $('#security_purpose').val()
    );

    //   formData.append(
    //     'ifsc_code',
    //     $('#ifsc_code').val()
    // );

    /*
    |--------------------------------------------------------------------------
    | AJAX
    |--------------------------------------------------------------------------
    */

    $.ajax({

        url: "<?php echo e(url('save-step-4')); ?>",

        type: "POST",

        data: formData,

        processData: false,

        contentType: false,

        success: function(response) {

            hideLoader();

            if(response.status){

                showStepMessage(
                    'success',
                    'Documents uploaded successfully',
                    '#step4Message'
                );

                completeStep(4);

                unlockStep(5);

                fillApplicationData(response.application);

                loadReviewData();

                goToStep(5);

            } else {

                showStepMessage(
                    'error',
                    response.message,
                    '#step4Message'
                );
            }
        },

        error: function(xhr){

            hideLoader();

            console.log(xhr.responseText);

            showStepMessage(
                'error',
                'Something went wrong',
                '#step4Message'
            );
        }
    });
}

/*
|--------------------------------------------------------------------------
| FINAL SUBMIT
|--------------------------------------------------------------------------
*/

</script>

<script>
$(document).on('click', '#submitApplicationBtn', function () {

    clearValidationErrors();

    if(!$('#declarationCheck').is(':checked')){

        $('#declarationError').html(
            '<div class="error-message">Please accept declaration</div>'
        );

        return;
    }

    if(!$('#termsAgreement').is(':checked')){

        $('#termsError').html(
            '<div class="error-message">Please accept terms and conditions</div>'
        );

        return;
    }

    showLoader('Submitting Application...');

    showStepMessage(
        'loading',
        'Submitting application... Please wait',
        '#step5Message'
    );

    $.ajax({

        url: "<?php echo e(url('submit-application')); ?>",

        type: "POST",

        data: {

            _token: "<?php echo e(csrf_token()); ?>"
        },

        success: function(response) {

            hideLoader();

            if(response.status){

                showStepMessage(
                    'success',
                    response.message,
                    '#step5Message'
                );

                /*
                OPTIONAL SUCCESS PAGE
                */

                $('#step5').html(`

                    <div class="text-center py-5">

                        <h2 class="text-success">
                            Application Submitted Successfully
                        </h2>

                    </div>
                `);

            } else {

                showStepMessage(
                    'error',
                    response.message,
                    '#step5Message'
                );
            }
        },

        error: function(xhr){

            hideLoader();

            console.log(xhr.responseText);

            showStepMessage(
                'error',
                'Something went wrong',
                '#step5Message'
            );
        }
    });
});
</script>

<script>

function loadReviewData(){

    /*
    STEP 1
    */

    $('#review_organization').text(
        $('#organization').val()
    );

    $('#review_phone').text(
        $('#phone').val()
    );

    $('#review_email').text(
        $('#email').val()
    );

    /*
    STEP 2
    */

    $('#review_full_name').text(
        $('#full_name').val()
    );

        let dob = $('#dob').val();
        
        if(dob){
        
            let dobParts = dob.split('-');
        
            let formattedDob =
                dobParts[1] + '-' +
                dobParts[2] + '-' +
                dobParts[0];
        
            $('#review_dob').text(formattedDob);
        
        }else{
        
            $('#review_dob').text('');
        }

    $('#review_gender').text(
        $('#gender').val()
    );

    $('#review_marital_status').text(
        $('#marital_status').val()
    );

    $('#review_father_name').text(
        $('#father_name').val()
    );

    $('#review_aadhaar_number').text(
        $('#aadhaar_number').val()
    );

    $('#review_pan_number').text(
        $('#pan_number').val()
    );
    
      $('#review_passport').text(
        $('#passport').val()
    );
    
       $('#review_current_address').text(
        $('#current_address').val()
    );
    
       $('#review_permanent_address').text(
        $('#permanent_address').val()
    );
    
       $('#review_residence_type').text(
        $('#residence_type').val()
    );
    
       $('#review_address_duration').text(
        $('#address_duration').val()
    );
    
        $('#review_current_country').text($('#current_country').val());
$('#review_current_state').text($('#current_state').val());
$('#review_current_city').text($('#current_city').val());

$('#review_permanent_country').text($('#permanent_country').val());
$('#review_permanent_state').text($('#permanent_state').val());
$('#review_permanent_city').text($('#permanent_city').val());


    /*
    STEP 3
    */

    $('#review_loan_type').text(
        $('#loan_type').val()
    );

    $('#review_loan_amount').text(
        $('#loan_amount').val()
    );

    $('#review_loan_tenure').text(
        $('#loan_tenure').val()
    );

    $('#review_employment_type').text(
        $('#employment_type').val()
    );
    
     $('#review_purpose_of_loan').text(
        $('#purpose_of_loan').val()
    );
    
     $('#review_preferred_emi').text(
        $('#preferred_emi').val()
    );
    
    $('#review_total_interest').text(
    $('#total_interest').val()
    );
    
    $('#review_total_payment').text(
        $('#total_payment').val()
    );
    
   $('#review_processing_charges').text(
    $('#processing_charges').val()
    );
    
    $('#review_kit_cost').text(
        $('#kit_cost').val()
    );
    
    $('#review_down_payment').text(
        $('#down_payment').val()
    );
    
    $('#review_membership_fees').text(
        $('#membership_fees').val()
    );
    
    $('#review_documentation_fees').text(
        $('#documentation_fees').val()
    );
    
    $('#review_rate_of_intrest').text(
        $('#rate_of_intrest').val()
    );
     $('#review_loan_principle').text(
        $('#loan_principle').val()
    );
     $('#review_intrest_principle').text(
        $('#intrest_principle').val()
    );
     $('#review_deduction_principle').text(
        $('#deduction_principle').val()
    );
    //  $('#review_current_emi').text(
    //     $('#current_emi').val()
    // );
    
    //  $('#review_existing_loans').text(
    //     $('#existing_loans').val()
    // );

    // $('#review_credit_card_dues').text(
    //     $('#credit_card_dues').val()
    // );
    
    //  $('#review_outstanding_amount').text(
    //     $('#outstanding_amount').val()
    // );
    
 
    
 
    
//       $('#review_salary_bank').text(
//         $('#salary_bank').val()
//     );
    
//       $('#review_investments').text(
//         $('#investments').val()
//     );


//   $('#review_preperty_details').text(
//         $('#preperty_details').val()
//     );
    
//      $('#review_vehicles_owned').text(
//         $('#vehicles_owned').val()
//     );


//  $('#review_networth').text(
//         $('#networth').val()
//     );


//  $('#review_type_of_security').text(
//         $('#type_of_security').val()
//     );
    
    
//      $('#review_ownership_details').text(
//         $('#ownership_details').val()
//     );
    
    
//      $('#review_bank_details').text(
//         $('#bank_details').val()
//     );
    
//          $('#review_estimated_value').text(
//         $('#estimated_value').val()
//     );
    
//          $('#review_bank_details').text(
//         $('#bank_details').val()
//     );
    
    
//             $('#review_bank_details').text(
//         $('#bank_details').val()
//     );
    
//             $('#review_account_number').text(
//         $('#account_number').val()
//     );




//     /*
//     STEP 4
//     */

    $('#review_annual_income').text(
        $('#annual_income').val()
    );
    
    $('#review_monthly_income').text(
        $('#monthly_income').val()
    );

    $('#review_occupation').text(
        $('#occupation').val()
    );
    $('#review_income_particulars').text(
        $('#income_particulars').val()
    );
    $('#review_repayment_schedule').text(
        $('#repayment_schedule').val()
    );
    $('#review_renewal_after').text(
        $('#renewal_after').val()
    );
    $('#review_security_purpose').text(
        $('#security_purpose').val()
    );
    $('#review_other_income').text(
        $('#other_income').val()
    );
    
    


//     $('#review_ifsc_code').text(
//         $('#ifsc_code').val()
//     );

    
}


function fillApplicationData(data){

    /*
    STEP 1
    */

    $('#organization').val(data.organization);
    $('#phone').val(data.phone);
    $('#email').val(data.email);

    /*
    STEP 2
    */

    $('#full_name').val(data.full_name);
    $('#dob').val(data.dob);
    $('#gender').val(data.gender);
    $('#marital_status').val(data.marital_status);
    $('#father_name').val(data.father_name);
    $('#aadhaar_number').val(data.aadhaar_number);
    $('#pan_number').val(data.pan_number);
    $('#passport').val(data.passport);

    $('#current_address').val(data.current_address);
    $('#permanent_address').val(data.permanent_address);
    
    $('#current_country').val(data.current_country);
$('#current_state').val(data.current_state);
$('#current_city').val(data.current_city);

$('#permanent_country').val(data.permanent_country);
$('#permanent_state').val(data.permanent_state);
$('#permanent_city').val(data.permanent_city);

    // $('#address_duration').val(data.address_duration);

    /*
    RADIO
    */

    // $('input[name="residenceType"][value="' + data.residence_type + '"]')
    //     .prop('checked', true);

    /*
    STEP 3
    */

    $('#loan_type').val(data.loan_type);
    $('#loan_amount').val(data.loan_amount);
    $('#loan_tenure').val(data.loan_tenure);
    $('#purpose_of_loan').val(data.purpose_of_loan);
    $('#preferred_emi').val(data.preferred_emi);
    $('#processing_charges').val(data.processing_charges);
    $('#down_payment').val(data.down_payment);
    $('#kit_cost').val(data.kit_cost);
    $('#membership_fees').val(data.membership_fees);
    $('#documentation_fees').val(data.documentation_fees);
    $('#rate_of_intrest').val(data.rate_of_intrest);
     $('#loan_principle').val(data.loan_principle);
      $('#intrest_principle').val(data.intrest_principle);
       $('#deduction_principle').val(data.deduction_principle);
    // $('#current_emi').val(data.current_emi);
    // $('#existing_loans').val(data.existing_loans);
    // $('#credit_card_dues').val(data.credit_card_dues);
    // $('#outstanding_amount').val(data.outstanding_amount);
    
    
    if(data.loan_amount && document.getElementById('loanAmountRange')){

            document.getElementById('loanAmountRange').value = data.loan_amount;
        }
        
        if(data.loan_tenure && document.getElementById('loanTenureRange')){
        
            let tenure = parseInt(data.loan_tenure);
        
            document.getElementById('loanTenureRange').value = tenure;
        }
        
        /*
        |--------------------------------------------------------------------------
        | RECALCULATE EMI AFTER DB LOAD
        |--------------------------------------------------------------------------
        */
        
        setTimeout(function(){
        
            calculateEMI();
        
            loadReviewData();
        
        }, 200);

    /*
    STEP 4
    */
$('#occupation').val(data.occupation);
$('#income_particulars').val(data.income_particulars);
$('#repayment_schedule').val(data.repayment_schedule);
$('#renewal_after').val(data.renewal_after);
$('#security_purpose').val(data.security_purpose);
    $('#monthly_income').val(data.monthly_income);
    $('#other_income').val(data.other_income);
    $('#annual_income').val(data.annual_income);
    // $('#salary_bank').val(data.salary_bank);
    // $('#investments').val(data.investments);

    // $('#preperty_details').val(data.preperty_details);

    // $('#vehicles_owned').val(data.vehicles_owned);

    // $('#networth').val(data.networth);

    // $('#type_of_security').val(data.type_of_security);

    // $('#estimated_value').val(data.estimated_value);

    // $('#ownership_details').val(data.ownership_details);

    // $('#bank_details').val(data.bank_details);

    // $('#account_number').val(data.account_number);

    // $('#ifsc_code').val(data.ifsc_code);
    
    /*
|--------------------------------------------------------------------------
| DOCUMENT PREVIEWS STEP 4
|--------------------------------------------------------------------------
*/

        if(data.id_proof){
        
            $('#idProofPreview').show();
        
            $('#idProofLink').attr(
                'href',
                 '<?php echo e(asset("storage")); ?>/' + data.id_proof
            );
        }
        
        if(data.address_proof){
        
            $('#addressProofPreview').show();
        
            $('#addressProofLink').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.address_proof
            );
        }
        
        if(data.income_proof){
        
            $('#incomeProofPreview').show();
        
            $('#incomeProofLink').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.income_proof
            );
        }
        
        if(data.bankstatements_proof){
        
            $('#bankStatementPreview').show();
        
            $('#bankStatementLink').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.bankstatements_proof
            );
        }
        
        if(data.business_proof){
        
            $('#businessProofPreview').show();
        
            $('#businessProofLink').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.business_proof
            );
        }

        if(data.on_boarding_letter){
        
            $('#on_boarding_letterPreview').show();
        
            $('#on_boarding_letterLink').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.on_boarding_letter
            );
        }

        if(data.background_verification){
        
            $('#background_verificationPreview').show();
        
            $('#background_verificationLink').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.background_verification
            );
        }

         if(data.file_name3){
        
            $('#file_name3Preview').show();
        
            $('#file_name3Link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.file_name3
            );
        }

         if(data.file_name4){
        
            $('#file_name4Preview').show();
        
            $('#file_name4Link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.file_name4
            );
        }

        if(data.file_name5){
        
            $('#file_name5Preview').show();
        
            $('#file_name5Link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.file_name5
            );
        }


        if(data.photo_proof){
        
            $('#photo_proofPreview').show();
        
            $('#photo_proofLink').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.photo_proof
            );
        }
        
        
        /*
        |--------------------------------------------------------------------------
        | STEP 5 DOCUMENTS
        |--------------------------------------------------------------------------
        */
        
        if(data.id_proof){
        
            $('#review_id_proof_box').show();
        
            $('#review_id_proof_link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.id_proof
            );
        
        }else{
        
            $('#review_id_proof_box').hide();
        }
        
        if(data.address_proof){
        
            $('#review_address_proof_box').show();
        
            $('#review_address_proof_link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.address_proof
            );
        
        }else{
        
            $('#review_address_proof_box').hide();
        }
        
        if(data.income_proof){
        
            $('#review_income_proof_box').show();
        
            $('#review_income_proof_link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.income_proof
            );
        
        }else{
        
            $('#review_income_proof_box').hide();
        }
        
        if(data.bankstatements_proof){
        
            $('#review_bankstatement_box').show();
        
            $('#review_bankstatement_link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.bankstatements_proof
            );
        
        }else{
        
            $('#review_bankstatement_box').hide();
        }
        
        
        if(data.business_proof){
        
            $('#review_business_proof_box').show();
        
            $('#review_business_proof_link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.business_proof
            );
        
        }else{
        
            $('#review_business_proof_box').hide();
        }


        if(data.on_boarding_letter){
        
            $('#review_on_boarding_letter_box').show();
        
            $('#review_on_boarding_letter_link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.on_boarding_letter
            );
        
        }else{
        
            $('#review_on_boarding_letter_box').hide();
        }

        if(data.background_verification){
        
            $('#review_background_verification_box').show();
        
            $('#review_background_verification_link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.background_verification
            );
        
        }else{
        
            $('#review_background_verification_box').hide();
        }


        if(data.file_name3){
        
            $('#review_file_name3_box').show();
        
            $('#review_file_name3_link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.file_name3
            );
        
        }else{
        
            $('#review_file_name3_box').hide();
        }

          if(data.file_name4){
        
            $('#review_file_name4_box').show();
        
            $('#review_file_name4_link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.file_name4
            );
        
        }else{
        
            $('#review_file_name4_box').hide();
        }


                  if(data.file_name5){
        
            $('#review_file_name5_box').show();
        
            $('#review_file_name5_link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.file_name5
            );
        
        }else{
        
            $('#review_file_name5_box').hide();
        }


                          if(data.photo_proof){
        
            $('#review_photo_proof_box').show();
        
            $('#review_photo_proof_link').attr(
                'href',
                '<?php echo e(asset("storage")); ?>/' + data.photo_proof
            );
        
        }else{
        
            $('#review_photo_proof_box').hide();
        }
}


function completeStep(step){

    console.log(step);

    $('#stepNav' + step).addClass('completed');

    console.log($('#stepNav' + step));
}
</script>

<script>

$(document).ready(function () {


    const loanAmountRange = document.getElementById('loanAmountRange');
    const loanTenureRange = document.getElementById('loanTenureRange');

    const annualInterest = 18;

    if($('#loan_tenure').val() == ''){
        $('#loan_tenure').val(1);
    }

    function normalizeNumber(value) {
        value = String(value ?? '').replace(/[^0-9.]/g, '');

        return parseFloat(value) || 0;
    }

    function syncLoanAmount() {
        const kitCost = normalizeNumber($('#kit_cost').val());
        const downPayment = normalizeNumber($('#down_payment').val());
        const loanAmount = Math.max(kitCost - downPayment, 0);

        $('#loan_amount').val(Math.round(loanAmount));

        if(loanAmountRange){
            loanAmountRange.value = Math.round(loanAmount);
        }

        return loanAmount;
    }



    function calculateEMI() {

        let principal = syncLoanAmount();

        let tenureYears =
            parseFloat($('#loan_tenure').val()) || 1;


        if(principal > 5000000){
            principal = 5000000;
        }

        if(tenureYears < 1){
            tenureYears = 1;
        }

        if(tenureYears > 6){
            tenureYears = 6;
        }


        $('#loan_amount').val(Math.round(principal));
        $('#loan_tenure').val(tenureYears);


        if(loanAmountRange){
            loanAmountRange.value = principal;
        }

        if(loanTenureRange){
            loanTenureRange.value = tenureYears;
        }


        const monthlyInterest =
            annualInterest / 12 / 100;

        const months =
            tenureYears;

        const emi =
            principal > 0
                ? (principal * monthlyInterest * Math.pow(1 + monthlyInterest, months)) /
                    (Math.pow(1 + monthlyInterest, months) - 1)
                : 0;

        const totalInterest =
            (emi * months) - principal;

        const membershipFee = principal * 0.025;
        const documentationFee = 125;

        const totalAmountBeforeProcessing =
            emi * months;

        const processingCharges = principal * 0.01;

        const totalPayment =
    principal +
    totalInterest +
    processingCharges +
    membershipFee +
    documentationFee;
const totalPeriods = months * 12;

const loanPrinciple = totalPeriods > 0
    ? totalPayment / totalPeriods
    : 0;

const interestPrinciple = totalPeriods > 0
    ? totalInterest / totalPeriods
    : 0;

const deductionPrinciple =
    loanPrinciple + interestPrinciple;


        if($('#loanAmountDisplay').length){
            $('#loanAmountDisplay').text(
             Number(principal).toLocaleString()
            );
        }

        if($('#loanTenureDisplay').length){
            $('#loanTenureDisplay').text(
                tenureYears + ' Months'
            );
        }

        if($('#emiDisplay').length){
            $('#emiDisplay').text(
                Math.round(emi).toLocaleString()
            );
        }

        if($('#interestDisplay').length){
            $('#interestDisplay').text(
                 Math.round(totalInterest).toLocaleString()
            );
        }
        
        if($('#processingchargesDisplay').length){
            $('#processingchargesDisplay').text(
                 Math.round(processingCharges).toLocaleString()
            );
        }

        if($('#paymentDisplay').length){
            $('#paymentDisplay').text(
                Math.round(totalPayment).toLocaleString()
            );
        }



        $('#preferred_emi').val(
            Math.round(emi)
        );

        $('#total_interest').val(
            Math.round(totalInterest)
        );

       $('#rate_of_intrest').val(
            annualInterest + '%'
        );

        $('#processing_charges').val(
             Math.round(processingCharges)
        );

        $('#total_payment').val(
            Math.round(totalPayment)
        );

        $('#membership_fees').val(
            Math.round(membershipFee)
        );

        $('#documentation_fees').val(
            documentationFee
        );

        $('#loan_principle').val(Math.round(loanPrinciple));
        $('#intrest_principle').val(Math.round(interestPrinciple));
        $('#deduction_principle').val(Math.round(deductionPrinciple));
    }



    if(loanAmountRange){
        loanAmountRange.addEventListener('input', function () {

            $('#loan_amount').val(this.value);

            calculateEMI();
        });
    }

    if(loanTenureRange){
        loanTenureRange.addEventListener('input', function () {

            $('#loan_tenure').val(this.value);

            calculateEMI();
        });
    }



    $('#kit_cost, #down_payment').on('input blur', function () {
        calculateEMI();
    });

 $('#loan_tenure').on('change', function () {

    let value = parseInt($(this).val());

    if (isNaN(value)) {
        value = 1;
    }

    if (value < 1) value = 1;
    if (value > 6) value = 6;

    $(this).val(value);

    if (typeof loanTenureRange !== 'undefined' && loanTenureRange) {
        loanTenureRange.value = value;
    }

    calculateEMI();
});


    calculateEMI();


    window.calculateEMI = calculateEMI;

});

</script>

<script>
    function showInputError(inputId, message){

        let input = $('#' + inputId);
    
        input.addClass('input-error');
    
        let wrapper = input.closest('.field-wrapper');
    
        if(wrapper.next('.error-message').length === 0){
            wrapper.after(
                '<div class="error-message">' + message + '</div>'
            );
        }
    }

</script>
<?php /**PATH /home/neefc25/public_html/kapstono/resources/views/pages/partials/scripts.blade.php ENDPATH**/ ?>