
// "use strict";
$table = $("#bstable");

let current_fs, next_fs, previous_fs; // Fieldsets
let current = 1;
let selectedValue = $('input[name="account_type"]:checked').val();

$('input[name="account_type"]').on('change', function (event) {
    event.preventDefault();
    selectedValue = $('input[name="account_type"]:checked').val();
    setAccountTypeProgressBar();
});


function setAccountTypeProgressBar(){
     if (selectedValue === "business") {
        $('.kybDiv').show();
        $('.kycDiv').hide();
        if( $('#country_id').val() == '39'){
            $('.quebecBusinessNumberDiv').show();
            $('.federalBusinessNumberDiv').show();
            $('.socialInsuranceNumberDiv').hide();
        }
        $('.identity_type').html("KYB");
        var html = `  <li style="width:16.66%" id="choose_type" class="active"><strong>Account Type</strong></li>
        <li style="width:16.66%" id="personal_info" class="personal"><strong>Personal Information</strong></li>
        <li style="width:16.66%" id="payment" class="identification"><strong>Identification Document</strong></li>
        <li style="width:16.66%" id="Business Documents" class="Business Documents"><strong>Business Documents</strong></li>  
        <li style="width:16.66%" id="declarations" class="declarations_process"><strong>Declarations</strong></li>
        <li style="width:16.66%" id="confirm" class="confirmation"><strong>Verification</strong></li>`;
        $('.progressbar-identify-form').html(html);
    } else{
        if( $('#country_id').val() == '39'){
            $('.socialInsuranceNumberDiv').show();
            $('.quebecBusinessNumberDiv').hide();
            $('.federalBusinessNumberDiv').hide();
        }
        $('.kybDiv').hide();
        $('.kycDiv').show();
        $('.identity_type').html("KYC");
        var html = `  <li style="width:20%" id="choose_type" class="active"><strong>Account Type</strong></li>
        <li style="width:20%" id="personal_info" class="personal"><strong>Personal Information</strong></li>
        <li style="width:20%" id="payment" class="identification"><strong>Identification Document</strong></li>
        <li style="width:20%" id="declarations" class="declarations_process"><strong>Declarations</strong></li>
        <li style="width:20%" id="confirm" class="confirmation"><strong>Verification</strong></li>`;
        
        $('.progressbar-identify-form').html(html);
    }
}

$(document).ready(function () {
    setAccountTypeProgressBar();
    setTimeout(function () {
        if(typeof selectedCountryId != "undefined" && selectedCountryId != '') {
            get_state_dropdown(selectedStateId,selectedCountryId,'#state_id');
        }
    },1000);   

    $('#country_id').change(function() {
        var countryId = $(this).val();
        if (countryId) {
            get_state_dropdown('', countryId, "#state_id")
        } else {
            $('#state_id').html('<option value="">Select Region / State / Province</option>');
        }

        if(countryId == 39 && selectedValue == 'individual'){
            $('.socialInsuranceNumberDiv').show();
        }else if(countryId == 39 && selectedValue == 'business'){
            $('.quebecBusinessNumberDiv').show();
            $('.federalBusinessNumberDiv').show();
        }else{
            $('.socialInsuranceNumberDiv').hide();
            $('.quebecBusinessNumberDiv').hide();
            $('.federalBusinessNumberDiv').hide();
        }
    });

    let removedCompanyCertificates = [];
    let removedOwnershipCertificates = [];

    $('body').on('click', '.certificate_remove_icon', function (e) {
        e.preventDefault();

        const certificateName = $(this).data('certificate-name');
        const type = $(this).data('type');

        //removed files by type
        if (type === 'company') {
            if (!removedCompanyCertificates.includes(certificateName)) {
                removedCompanyCertificates.push(certificateName);
            }
            $('#removed_company_certificates').val(JSON.stringify(removedCompanyCertificates));
        } else if (type === 'ownership') {
            if (!removedOwnershipCertificates.includes(certificateName)) {
                removedOwnershipCertificates.push(certificateName);
            }
            $('#removed_ownership_certificates').val(JSON.stringify(removedOwnershipCertificates));
        }

        // Remove icon/button and associated hidden input
        const fileWrapper = $(this).closest('.certificate_section');

        fileWrapper.remove();
    });

    // On issue_date change, set min for expiration_date
    $('#issue_date').on('change', function () {
        const issueDate = $(this).val();
        $('#expiration_date').attr('min', issueDate);
    });

    // Trigger once on page load if issue_date is already set
    const initialIssueDate = $('#issue_date').val();
    if (initialIssueDate) {
        $('#expiration_date').attr('min', initialIssueDate);
    }

    let expiration_confirmation = $('#expiration-confirm:checked').val();
    if(expiration_confirmation){
        $('input[name="expiration_date"]').prop('readonly', true);
    }
    $('#expiration-confirm').on('change', function() {
        if ($(this).is(':checked')) {
            $('input[name="expiration_date"]').val(null).prop('readonly', true);
        } else {
            $('input[name="expiration_date"]').prop('readonly', false);
        }
    });

    setProgressBar(current);

    $(".next").click(function () {
        current_fs = $(this).closest('fieldset')
        next_fs = $(this).closest('fieldset').next();
        let currentStep = null;
        let currentStepValue = $("input[name='step']").val();
        if(selectedValue != "business" && currentStepValue == "3"){
            currentStep = $("fieldset").index(current_fs);
        } else{
            currentStep = $("fieldset").index(current_fs) + 1;
        }
        fetchStepData(currentStep, current_fs, next_fs);
    });

    $(".previous").click(function () {
        let currentStepValue = $("input[name='step']").val();
        $("input[name='step']").val(parseInt(currentStepValue)-1);

        current_fs = $(this).closest('fieldset');
        previous_fs = $(this).closest('fieldset').prev();

        if(selectedValue != "business" && currentStepValue == "3"){
            previous_fs = $('#step_4').closest('fieldset').prev();
        }
        if(selectedValue != "business" && currentStepValue >= "3") {
            $("#progressbar li").eq($("fieldset").index(current_fs) - 1).removeClass("active");
        } else {
            $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");
        }
        showFieldset(previous_fs,true);
        setProgressBar(--current);
    });

    $(".submit").click(function () {
        return false;
    })
});

function fetchStepData(step, current_fs, next_fs) {
    if (selectedValue === "business") {
        switch (step) {
            case 1:
                fetchStep1Data(current_fs, next_fs);
                break;
            case 2:
                fetchStep2Data(current_fs, next_fs);
                break;
            case 3:
                fetchStep3Data(current_fs, next_fs);
                break;
            case 4:
                fetchStep4Data(current_fs, next_fs);
                break;
            case 5:
                fetchStep5Data(current_fs, next_fs);
                break;
            case 6:
                fetchStep6Data(current_fs, next_fs);
                break;
            default:
                console.log('Step not defined');
        }
    } else {
        switch (step) {
            case 1:
                fetchStep1Data(current_fs, next_fs);
                break;
            case 2:
                fetchStep2Data(current_fs, next_fs);
                break;
            case 3:
                fetchStep3Data(current_fs, next_fs);
                break;
            case 4:
                fetchStep5Data(current_fs, next_fs);
                break;
            case 5:
                fetchStep6Data(current_fs, next_fs);
                break;
            default:
                console.log('Step not defined');
        }
    }

}

function showFieldset(next_fs, isPrevCheck = false) {
    let currentStepValue = $("input[name='step']").val();

    if(!isPrevCheck) {
        if($("fieldset").index(next_fs) >= 5 && selectedValue != "business") {
            $("#progressbar li").eq($("fieldset").index(next_fs) - 1).addClass("active");
        } else {
            $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");
        }
    }

    if(!isPrevCheck && selectedValue != "business" && currentStepValue == "3"){
        current_fs = $('#step_3').closest('fieldset');
        next_fs = $('#step_4').closest('fieldset').next();
    }
      
    next_fs.show();
    current_fs.animate({
        opacity: 0
    }, {
        step: function (now) {
            let opacity = 1 - now;
            current_fs.css({
                'display': 'none',
                'position': 'relative'
            });
            next_fs.css({
                'opacity': opacity
            });
        },
        duration: 500
    });
}

function setProgressBar(curStep) {
    let steps = $("fieldset").length
    let percent = parseFloat(100 / steps) * curStep;
    percent = percent.toFixed();
    $(".progress-bar")
        .css("width", percent + "%")
}

function get_state_dropdown(selected_id,country_id,target_dropdown_id) {
    $.ajax({
        url: baseURL+'get-state',
        type: 'POST',
        data: {
            'country_id' : country_id,
            'selected_id' : selected_id,
        },
        headers: { 'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content') },
        success: function (response) {
            if(response.count > 0){
                $('.state-input').show();
            }else{
                $('.state-input').hide();
            }
            $(target_dropdown_id).html(response.html);
        },
        error: function () {
        }
    });
}

function fetchStep1Data(current_fs, next_fs) {
    let account_type = $('input[name="account_type"]:checked').val();
    let is_error = false;
    $('.error').text('');

    if(!account_type){
        $('.account_type_error').text('The Account Type field is required.');
        is_error = true;
    } 
    let confirmation = $('input[name="confirmation"]:checked').val();
    if(!confirmation){
        $('.confirmation_error').text('Please read message and agree with it.');
        is_error = true;
    }
    if(is_error == true){
        return;
    }
    $("input[name='step']").val(1);
    showFieldset(next_fs);
    setProgressBar(++current);
}


function fetchStep2Data(current_fs, next_fs) {
    let first_name = $('input[name="first_name"]:checked').val();
    let last_name = $('input[name="last_name"]:checked').val();
    let day = $('input[name="day"]').val().trim();
    let month = $('#month option:selected').val().trim();
    let year = $('input[name="year"]').val().trim();
    let gender = $('#gender option:selected').val();
    let address = $('input[name="address"]').val();
    let address_2 = $('input[name="address_2"]').val();
    let city = $('#city_id option:selected').val();
    let state = $('#state_id option:selected').val();
    let country = $('#country_id option:selected').val();
    let postal_code = $('input[name="postal_code"]').val();
    let company_name = $('input[name="company_name"]').val();
    let social_insurance_number = $('input[name="social_insurance_number"]').val();
    let quebec_business_number = $('input[name="quebec_business_number"]').val();
    let federal_business_number = $('input[name="federal_business_number"]').val();
    let currentYear = new Date().getFullYear();

    let is_error = false;
    $('.error').text('');

    if(first_name == ''){
        $('.first_name_error').text('The First Name field is required.');
        is_error = true;
    }
    if(last_name == ''){
        $('.last_name_error').text('The Last Name field is required.');
        is_error = true;
    }

    if (!day || !month || !year) {
        $(".date_of_birth_error").text("Please enter a complete date of birth.");
        is_error = true;
    } else if (!/^\d{4}$/.test(year)) {
        $(".date_of_birth_error").text("Please enter a valid 4-digit year.");
        is_error = true;
    } else {
        year = parseInt(year, 10);
        month = parseInt(month, 10);
        day = parseInt(day, 10);

        if (year < 1900 || year > currentYear) {
            $(".date_of_birth_error").text("Please enter a valid year (1900 - " + currentYear + ").");
            is_error = true;
        } else if (month < 1 || month > 12) {
            $(".date_of_birth_error").text("Please enter a valid month (1-12).");
            is_error = true;
        } else if (day < 1 || day > 31) {
            $(".date_of_birth_error").text("Please enter a valid day (1-31).");
            is_error = true;
        } else {
            let dob = new Date(year, month - 1, day);
            if (dob.getFullYear() !== year || dob.getMonth() + 1 !== month || dob.getDate() !== day) {
                $(".date_of_birth_error").text("Please enter a valid date.");
                is_error = true;
            } else {
                // Check age restriction (18+)
                let today = new Date();
                let age = today.getFullYear() - dob.getFullYear();
                let monthDiff = today.getMonth() - dob.getMonth();
                let dayDiff = today.getDate() - dob.getDate();

                if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
                    age--;
                }

                if (age < 18) {
                    $(".date_of_birth_error").text("You must be at least 18 years old.");
                    is_error = true;
                }
            }
        }
    }

    if(!gender) {
        $('.gender_error').text('The Gender field is required.');
        is_error = true;
    }
    if(address == "") {
        $('.address_error').text('The Street Name And House Number field is required.');
        is_error = true;
    }
    if(country == "") {
        $('.country_id_error').text('The Country field is required.');
        is_error = true;
    }
    let stateDropdown = document.getElementById("state_id");
    if (stateDropdown.options.length > 1) {
        if(!state){
            $('.state_id_error').text('The Region / State / Province field is required.');
            is_error = true;
        }
    }
  
    if(postal_code == "") {
        $('.postal_code_error').text('The Postcode / ZIP Code field is required.');
        is_error = true;
    }
    if (selectedValue === "business") {
        if(company_name == ''){
            $('.company_name_error').text('The Company Name field is required.');
            is_error = true;
        }
        if(country == '39'){
            if (quebec_business_number === '') {
                $('.quebec_business_number_error').text('The Quebec Business Number field is required.');
                is_error = true;
            } else if (!/^\d{10}$/.test(quebec_business_number)) {
                $('.quebec_business_number_error').text('The Quebec Business Number format is invalid.');
                is_error = true;
            }
    
            if(federal_business_number == ''){
                $('.federal_business_number_error').text('The Federal Business Number field is required.');
                is_error = true;
            }else if (!/^\d{9}$/.test(federal_business_number)) {
                $('.federal_business_number_error').text('The Federal Business Number format is invalid.');
                is_error = true;
            }
        }

    }else if(selectedValue === "individual" && country == '39'){
        if(social_insurance_number == ''){
            $('.social_insurance_number_error').text('The Social Insurance Number field is required.');
            is_error = true;
        }else if (!/^\d{9}$/.test(social_insurance_number)) {
            $('.social_insurance_number_error').text('The Social Insurance Number format is invalid.');
            is_error = true;
        }
    }
    if(is_error == true){
        return;
    }
   
    $("input[name='step']").val(2);
    showFieldset(next_fs);
    setProgressBar(++current);
}

function fetchStep3Data(current_fs, next_fs) {
    let doc_type = $('#doc_type option:selected').val();
    let doc_number = $('input[name="doc_number"]').val();
    let issue_country = $('#issue_country option:selected').val();
    let issue_date = $('input[name="issue_date"]').val();
    let expiration_date = $('input[name="expiration_date"]').val();
    let nationality = $('#nationality option:selected').val();
    let is_error = false;
    $('.error').text('');
    
    if(doc_type == ''){
        $('.doc_type_error').text('The Document Type field is required.');
        is_error = true;
    }
    if(doc_number == ''){
        $('.doc_number_error').text('The Document Number field is required.');
        is_error = true;
    }
    if(issue_country == ''){
        $('.issue_country_error').text('The Issuing Country field is required.');
        is_error = true;
    }
    if(issue_date == ''){
        $('.issue_date_error').text('The Issue Date field is required.');
        is_error = true;
    }

    var checkboxValue = $('#expiration-confirm').prop('checked');
    if(!checkboxValue && expiration_date == '') {
        $('.expiration_date_error').text('The Expire Date field is required.');
        is_error = true;
    } else if(!checkboxValue && issue_date >= expiration_date){
        $('.expiration_date_error').text('The Expiration Date should be after the issue date.');
        is_error = true;
    }
    if(nationality == ''){
        $('.nationality_error').text('The Nationality field is required.');
        is_error = true;
    }
    if(is_error == true){
        return;
    }
    if(selectedValue === 'business'){
        $('#step_4').show();
    }
    if(selectedValue != 'business'){
        $('#step_4').hide();

        $('input[name="company_certificate"]').val(null);
        $('input[name="ownership_certificate"]').val(null);
    }
    $("input[name='step']").val(3);
    showFieldset(next_fs);
    setProgressBar(++current);
}

function fetchStep4Data(current_fs, next_fs) {
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];
    const maxSize = 10 * 1024 * 1024;
    let is_error = false;
    $('.error').text('');

    if (selectedValue === 'business') {
        // COMPANY CERTIFICATE VALIDATION
        const existingCompanyCertificates = $('input[name="existing_company_certificate[]"]').map(function () {
            return $(this).val();
        }).get();

        const removedCompanyCertificates = JSON.parse($('#removed_company_certificates').val() || '[]');
        const uploadedCompanyCertificates = $('input[name="company_certificate[]"]');

        const hasCompanyUpload = Array.from(uploadedCompanyCertificates).some(input => input.files.length > 0);

        if (existingCompanyCertificates.length === removedCompanyCertificates.length && !hasCompanyUpload) {
            $('.company_certificate_error').text('The Certificate of Incorporation/Registration Of Your Company field is required.');
            is_error = true;
        }

        uploadedCompanyCertificates.each(function () {
            const file = this.files[0];
            if (file) {
                if (!allowedTypes.includes(file.type)) {
                    $('.company_certificate_error').text('Invalid file type for Certificate of Incorporation. Only JPG, JPEG, PNG, and PDF files are allowed.');
                    is_error = true;
                } else if (file.size > maxSize) {
                    $('.company_certificate_error').text('Certificate of Incorporation file size should not exceed 10MB.');
                    is_error = true;
                }
            }
        });

        // OWNERSHIP CERTIFICATE VALIDATION
        const existingOwnershipCertificates = $('input[name="existing_ownership_certificate[]"]').map(function () {
            return $(this).val();
        }).get();

        const removedOwnershipCertificates = JSON.parse($('#removed_ownership_certificates').val() || '[]');
        const uploadedOwnershipCertificates = $('input[name="ownership_certificate[]"]');

        const hasOwnershipUpload = Array.from(uploadedOwnershipCertificates).some(input => input.files.length > 0);

        if (existingOwnershipCertificates.length === removedOwnershipCertificates.length && !hasOwnershipUpload) {
            $('.ownership_certificate_error').text('The Shareholder Certificate Or Proof Of Ownership field is required.');
            is_error = true;
        }

        uploadedOwnershipCertificates.each(function () {
            const file = this.files[0];
            if (file) {
                if (!allowedTypes.includes(file.type)) {
                    $('.ownership_certificate_error').text('Invalid file type for Shareholder Certificate. Only JPG, JPEG, PNG, and PDF files are allowed.');
                    is_error = true;
                } else if (file.size > maxSize) {
                    $('.ownership_certificate_error').text('Shareholder Certificate file size should not exceed 10MB.');
                    is_error = true;
                }
            }
        });
        if(is_error == true){
            return;
        }
    }   
    $("input[name='step']").val(4);
    showFieldset(next_fs);
    setProgressBar(++current);
}

let is_not_pep = null;
let is_information_correct = null;
function fetchStep5Data(current_fs, next_fs) {
    is_not_pep = $('input[name="is_not_pep"]:checked').prop('checked');
    is_information_correct = $('input[name="is_information_correct"]:checked').prop('checked');
    let is_error = false;
    $('.error').text('');

    let submitBtn = $('.btn-submit');
    let submitBtnText = submitBtn.html();
    submitBtn.attr("disabled", true).html('<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;Loading...');
    $(".action-button-previous").attr("disabled", true);

    if(!is_information_correct) {
        $('.declaration_error').text('Please confirm that the information provided is complete and correct..');
        is_error = true;
    }
    if(is_error == true){
        $(".action-button-previous").attr("disabled", false);
        submitBtn.attr("disabled", false).html(submitBtnText);
        return;
    }
    const fid = 'identityform';
    let form = $('#' + fid);
    let formData = $('#' + fid)[0];
    let fd = new FormData(formData);

    is_not_pep ? fd.append('is_not_pep',1) : fd.append('is_not_pep',0);
    is_information_correct ? fd.append('is_information_correct',1) : fd.append('is_information_correct',0);
    fd.append('month',$('#month option:selected').val());
    fd.append('gender',$('#gender option:selected').val());

    $.ajax({
        url: form.attr('action'),
        type: "POST",
        data: fd,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
        },
        processData: false,
        contentType: false,
        success: function (data, textStatus, jqXHR) {
            $(".action-button-previous").attr("disabled", false);
            submitBtn.attr("disabled", false).html(submitBtnText);
            if (data.success == true) {
                swalMsg(data.msg, 'success')
                $("input[name='step']").val(4);
                const isMobile = window.matchMedia("(max-width: 375px)");
                if (isMobile.matches) {
                    window.location = data.verification_url;
                } else{
                    var qrCodeHtml = `<div class="text-center d-flex justify-content-center">
                        <img src="${data.base64QrCode}" alt="QR Code" />
                    </div>
                    <br>`;
                    $('.qr-code').html(qrCodeHtml);
                }
                showFieldset(next_fs);
                setProgressBar(++current);
            } else {
                swalMsg(data.msg, 'error')
            }
        },
        error: function (response) {
            $(".action-button-previous").attr("disabled", false);
            submitBtn.attr("disabled", false).html(submitBtnText);
            swalMsg(response.responseJSON.msg,'error')
        }
    });
}

function fetchStep6Data(current_fs, next_fs) {
    $("input[name='step']").val(5);
    showFieldset(next_fs);
    setProgressBar(++current);
}

$(".click_here").click(function () {
    const fid = 'identityform';
    let form = $('#' + fid);
    let formData = $('#' + fid)[0];
    let fd = new FormData(formData);

    is_not_pep ? fd.append('is_not_pep',1) : fd.append('is_not_pep',0);
    is_information_correct ? fd.append('is_information_correct',1) : fd.append('is_information_correct',0);
    fd.append('month',$('#month option:selected').val());
    fd.append('gender',$('#gender option:selected').val());

    let cilckHereBtn = $('.click_here');
    let cilckHereBtnText = cilckHereBtn.html();
    cilckHereBtn.attr("disabled", true).html('<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;Loading...');
    $(".action-button-previous").attr("disabled", true);
    
    $.ajax({
        url: form.attr('action'),
        type: "POST",
        data: fd,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
        },
        processData: false,
        contentType: false,
        success: function (data, textStatus, jqXHR) {
            if (data.success == true) {
                swalMsg(data.msg, 'success')
                $(".action-button-previous").attr("disabled", false);
                cilckHereBtn.attr("disabled", false).html(cilckHereBtnText);
                const isMobile = window.matchMedia("(max-width: 375px)");
                if (isMobile.matches) {
                    window.location = data.verification_url;
                } else{
                    var qrCodeHtml = `<div class="text-center d-flex justify-content-center">
                        <img src="${data.base64QrCode}" alt="QR Code" />
                    </div>
                    <br>`;
                    $('.qr-code').html(qrCodeHtml);
                }
            } else {
                $(".action-button-previous").attr("disabled", false);
                cilckHereBtn.attr("disabled", false).html(cilckHereBtnText);
                swalMsg(data.msg, 'error')
            }
        },
        error: function (response) {
            $(".action-button-previous").attr("disabled", false);
            cilckHereBtn.attr("disabled", false).html(cilckHereBtnText);
            swalMsg(response.responseJSON.msg,'error')
        }
    });
})
