$(document).ready(function(){
    $("#entry_no").select2(select2_default({
        url:`payment/get_select2_entry_no`,
        placeholder:'VOUCHER NO',
    })).on('change', () => trigger_search());
    $("#_party_id").select2(select2_default({
        url:`payment/get_select2_party_id`,
        placeholder:'PARTY NAME',
    })).on('change', () => trigger_search());
    $("#date_from, #date_to").on('change', () => trigger_search());
	$("#vm_group").on('change', () => $('#vm_party_id').val(null).trigger('change'));
    $("#vm_party_id").select2(select2_default({
        url:`common/get_select2_account`,
        placeholder:'NAME',
        param:()=>$('#vm_group').val(),
    })).on('change', () => get_account_balance());

    disable_enable_background(false);
});
const get_type = group => {
	let path= `${base_url}/voucher/common/get_type/${group}`;   
	ajaxCall('GET',path,'','JSON',resp =>{
        let {status, flag, data, msg} = resp;
	        if(status){
	            if(flag == 1){
	            	if(data && data.length != 0){
	            		let options = data.map(temp => {
	            			return `<option value="${temp.acc_id}">${temp.acc_name.toUpperCase()}</option>`
	            		})
	            		$('#vm_acc_id').html(options);
	            	}else{
	            		$('#vm_acc_id').html("<option value='0'>NO TYPE ADDED</option>");
	            	}
	            }else{
	                response_error(flag, msg)
	            }
	        }else{
	            session_expired()               
	        }                
	    },errmsg => {
    });
}
const set_default = () => {
	$('#vm_credit_amt, #vm_credited_amt, #vm_balance, #vm_total_amt, #vm_round_off, #vm_dollar_rate, #vm_usd_amt').val(0);
	$('#vm_balance_type').val('');
	$('#vm_balance_show').val('0 TO PAY');
	$('#voucher_material_wrapper').html('');
	let total_amt = parseFloat( ('0' + $(`#vm_total_amt`).val()).replace(/[^0-9-\.]/g, ''), 10 );
	if(isNaN(total_amt) || total_amt == '') total_amt = 0;
	if(total_amt > 0){
		$('.master_block_btn').prop('disabled', false)
	}else{
		$('.master_block_btn').prop('disabled', true)
	}
}
const get_account_balance = () =>{
	set_default();
	const type  	= $('#vm_type').val();
	const group 	= $('#vm_group').val();
	const acc_id 	= $('#vm_acc_id').val();
	const party_id  = $('#vm_party_id').val();
    if(party_id != null && party_id != ''){
		let path= `${base_url}/voucher/common/get_account_balance/${group}/${acc_id}/${party_id}`;   
    	ajaxCall('GET',path,'','JSON',resp =>{
	        let {status, flag, data, msg} = resp;
	        if(status){
	            if(flag == 1){
	            	if(data['bal_data']){
	            		$('#vm_credit_amt').val(data['bal_data'].credited_amt);
	            		$('#vm_credited_amt').val(data['bal_data'].debited_amt);
	                	$('#vm_balance').val(`${data['bal_data'].amt}`)
	                	$('#vm_balance_type').val(data['bal_data'].type)
	                	$('#vm_balance_show').val(`${data['bal_data'].amt} ${data['bal_data'].type}`)

                        $('#vm_dollar_rate').val(data['bal_data'].vm_dollar_rate);
                        $('#vm_usd_amt').val(data['bal_data'].vm_usd_amt);
	                }
                    if(data['trans_data'] && data['trans_data'].length != 0){
                        add_payment_wrapper(data['trans_data']);
                    }
	            }else{
	                response_error(flag, msg)
	            }
	        }else{
	            session_expired()               
	        }                
	    },errmsg => {
	    });
    }
}
const calculate_master_balance = () =>{
	let acc_id = $(`#vm_acc_id`).val();

	let bal_amt = $(`#vm_balance`).val();
	if(isNaN(bal_amt) || bal_amt == '') bal_amt = 0;

	let total_amt = parseFloat( ('0' + $(`#vm_total_amt`).val()).replace(/[^0-9-\.]/g, ''), 10 );
	if(isNaN(total_amt) || total_amt == '') total_amt = 0;

	let round_off = parseFloat( ('0' + $(`#vm_round_off`).val()).replace(/[^0-9-\.]/g, ''), 10 );
	if(isNaN(round_off) || round_off == '') round_off = 0;

	let bal_type = $(`#vm_balance_type`).val();
	let close_amt = 0;
	if(bal_type == 'TO PAY'){
		close_amt = parseFloat(bal_amt) - (parseFloat(total_amt) + parseFloat(round_off));
	}else{
		close_amt = parseFloat(bal_amt) + (parseFloat(total_amt) + parseFloat(round_off));
	}
	if(isNaN(close_amt) || close_amt == '') close_amt = 0;
	if(close_amt < 0){
		close_amt = Math.abs(close_amt)
		if(bal_type == 'TO PAY'){
			bal_type = 'TO RECEIVE'
		}else{
			bal_type = 'TO PAY'
		}
	}

	$('#vm_balance_show').val(`${close_amt} ${bal_type}`);

	if(total_amt > 0){
		$('.master_block_btn').prop('disabled', false)
	}else{
		$('.master_block_btn').prop('disabled', true)
	}
}
const add_update_payment = (id) =>{
    let check   	= true;
    if($("#vm_party_id").val() == null){
        $("#vm_party_id").css({'border-color':'red'});
        $("#vm_party_id").addClass('shake');
        $('#vm_party_id').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
            $('#vm_party_id').delay(200).removeClass('shake');
        });
        check = false;
    }else{
    	$("#vm_party_id").css({'border-color':'#550a06'});
    }
    if($("#vm_total_amt").val() <= 0){
    	$("#vm_total_amt").css({'border-color':'red'});
        $("#vm_total_amt").addClass('shake');
        $('#vm_total_amt').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
            $('#vm_total_amt').delay(200).removeClass('shake');
        });
        check = false;
    }else{
    	$("#vm_total_amt").css({'border-color':'#550a06'});
    }
    if($("#vm_prepared_id").val() == 0){
    	$("#vm_prepared_id").css({'border-color':'red'});
        $("#vm_prepared_id").addClass('shake');
        $('#vm_prepared_id').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
            $('#vm_prepared_id').delay(200).removeClass('shake');
        });
        check = false;
    }else{
    	$("#vm_prepared_id").css({'border-color':'#550a06'});
    }
    if($("#vm_checked_id").val() == 0){
    	$("#vm_checked_id").css({'border-color':'red'});
        $("#vm_checked_id").addClass('shake');
        $('#vm_checked_id').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
            $('#vm_checked_id').delay(200).removeClass('shake');
        });
        check = false;
    }else{
    	$("#vm_checked_id").css({'border-color':'#550a06'});
    }
    if(!check){
        display_alert_popup('err','Oh snap ! You forgot to enter some information');
        $("body, html").animate({'scrollTop':0},1000);
    }else{
        let path        = `${base_url}/voucher/payment/add_update/${id}`;   
        let form_data   = $("#payment_form").serialize();
        ajaxCall('POST',path,form_data,'JSON',resp =>{
            let {status, flag, data, msg} = resp;
            if(status){
                if(flag == 1){
                    if(id == 0) {
                    } else {
                    }
                    display_alert_popup('succ',msg);
                    $("body, html").animate({'scrollTop':0},1000);
                    // window.open(`${base_url}/voucher/payment?action=print&id=${data.id}`, '_blank', 'width=1024, height=768');
                    setTimeout(function(){window.location.reload(); },1000); 
                }else{
                    response_error(flag, msg)
                }
            }else{
                session_expired()               
            }                
        },errmsg => {
        });
    }
}
const delete_payment = path =>{
    let ans = confirm("Are you sure? You want to delete item.");
    if(ans == true){
        ajaxCall('GET',path,'','JSON',resp =>{
            const {status, flag, msg} = resp;
            if(status){
                if(flag == 1){
                    $("#table_reload").load(window.location + " #table_tbody");
                    $("#count_reload").load(window.location + " #total_rows");
                    display_alert_popup('succ',msg);
                }else{
                    response_error(flag, msg)
                }
            }else{
                session_expired();
            }
        },errmsg=>{});
    }
}

























const get_pending_purchase = () =>{
    const type      = $('#vm_type').val();
    const group     = $('#vm_group').val();
    const acc_id    = $('#vm_acc_id').val();
    const party_id  = $('#vm_party_id').val();
    if(party_id != null && party_id != ''){
        let path= `${base_url}voucher/common/get_account_balance/${group}/${acc_id}/${party_id}`;   
        ajaxCall('GET',path,'','JSON',resp =>{
            let {status, flag, data, msg} = resp;
            if(status){
                if(flag == 1){
                    if(data['trans_data'] && data['trans_data'].length != 0){
                        add_payment_wrapper(data['trans_data']);
                    }
                }else{
                    response_error(flag, msg)
                }
            }else{
                session_expired()               
            }                
        },errmsg => {
        });
    }
}
const select_deselect = (count = 0) =>{
    let total_tr        = $('#payment_material_wrapper tr').length;
    for (let i = 1; i <= total_tr; i++){
        let id = $('#payment_material_wrapper tr:nth-child('+i+')').attr('id');
        let lastunderscore = id.lastIndexOf("_");
        let cnt = id.substring(lastunderscore+1);
        let balance_amt = $(`#vt_balance_amt_${cnt}`).val();
        if(count == 0){
            let parent_checked = $(`#parent_checkbox`).is(':checked');
            $(`#child_checkbox_${cnt}`).prop('checked', parent_checked)
        }
        if(count == 0 || cnt == count){
            if($(`#child_checkbox_${cnt}`).is(':checked')){
                $(`#vt_bill_clear_${cnt}`).val('YES')
                // total_checked++; 
            }else{
                $(`#vt_bill_clear_${cnt}`).val('NO')
                $(`#vt_adjust_amt_${cnt}`).val(0)
            }
        }
    }
    let total_checked   = $('.checkboxes:checked').length;
    $(`#parent_checkbox`).prop('checked', total_tr == total_checked);
    calculate_master_total()
}
const calculate_single_trans = cnt => {
    let final_amt       = $(`#vt_total_amt_${cnt}`).val();
    let allocated_amt   = $(`#vt_allocated_amt_${cnt}`).val();
    let balance_amt     = $(`#vt_balance_amt_${cnt}`).val();

    let adjust_amt      = parseFloat( ('0' + $(`#vt_adjust_amt_${cnt}`).val()).replace(/[^0-9-\.]/g, ''), 10 )
    if(isNaN(adjust_amt) || adjust_amt == '') adjust_amt = 0;
    
    let bal_amt = parseFloat(final_amt) - parseFloat(adjust_amt);
    if(isNaN(bal_amt) || bal_amt == '') bal_amt = 0;
    $(`#vt_balance_amt_show_${cnt}`).val(bal_amt.toFixed(2));       
    if(bal_amt < 0){
        $(`#vt_balance_amt_show_${cnt}`).css({'color':'red'});              
    }else{
        $(`#vt_balance_amt_show_${cnt}`).css({'color':'#000'});             
    }

    // 🔥 GET TOTAL ADJUST AMOUNT HERE
    // let total_adjust = calculate_total_adjust_amt();
    // $("#vm_total_amt").val(total_adjust.toFixed(2));
    
    // $("#child_checkbox_"+cnt).prop("checked", true);
    // $(`#vt_bill_clear_${cnt}`).val("YES");
    
    // let total_tr        = $('#payment_material_wrapper tr').length;
    // let total_checked   = $('.checkboxes:checked').length;
    // $(`#parent_checkbox`).prop('checked', total_tr == total_checked);

    // if(isNaN(total_adjust) || total_adjust == '') total_adjust = 0;
    // if(total_adjust > 0){
    //     $('.master_block_btn').prop('disabled', false)
    // }else{
    //     $('.master_block_btn').prop('disabled', true)
    // }
}

const calculate_total_adjust_amt = () => {
    let total = 0;

    $("[id^='vt_adjust_amt_']").each(function () {
        let val = parseFloat(('0' + $(this).val()).replace(/[^0-9-\.]/g, ''));

        if (!isNaN(val)) total += val;
    });

    return total;
};

const calculate_master_total = () =>{
    let acc_id                  = $('#vm_acc_id').val();
    let total_tr                = $('#payment_material_wrapper tr').length;
    let total_adjust_amt        = 0;
    for (let i = 1; i <= total_tr; i++){
        let id = $('#payment_material_wrapper tr:nth-child('+i+')').attr('id');
        let lastunderscore = id.lastIndexOf("_");
        let cnt = id.substring(lastunderscore+1);

        if($(`#child_checkbox_${cnt}`).is(':checked')){
            let adjust_amt = $(`#vt_adjust_amt_${cnt}`).val();
            if(isNaN(adjust_amt) || adjust_amt == '') adjust_amt = 0;
            
            total_adjust_amt = parseFloat(total_adjust_amt) + parseFloat(adjust_amt);
            if(isNaN(total_adjust_amt) || total_adjust_amt == '') total_adjust_amt = 0;
        }
    }

    let bal_amt = $('#vm_balance').val();
    if(isNaN(bal_amt) || bal_amt == '') bal_amt = 0;        

    let total_amt = $('#vm_total_amt').val();
    if(isNaN(total_amt) || total_amt == '') total_amt = 0;      

    let pending_total_amt = parseFloat(total_amt) - parseFloat(total_adjust_amt);
    if(isNaN(pending_total_amt) || pending_total_amt == '') pending_total_amt = 0;

    for (let i = 1; i <= total_tr; i++){
        let id = $('#payment_material_wrapper tr:nth-child('+i+')').attr('id');
        let lastunderscore = id.lastIndexOf("_");
        let cnt = id.substring(lastunderscore+1);

        if($(`#child_checkbox_${cnt}`).is(':checked')){
            let bal_amt = parseFloat( ('0' + $(`#vt_balance_amt_${cnt}`).val()).replace(/[^0-9-\.]/g, ''), 10 );
            if(isNaN(bal_amt) || bal_amt == '') bal_amt = 0;                    

            let adjust_amt = parseFloat( ('0' + $(`#vt_adjust_amt_${cnt}`).val()).replace(/[^0-9-\.]/g, ''), 10 );
            if(isNaN(adjust_amt) || adjust_amt == '') adjust_amt = 0;                   

            if(adjust_amt < 1){
                if(bal_amt <= pending_total_amt){
                    $(`#vt_adjust_amt_${cnt}`).val(bal_amt > 0 ?  bal_amt.toFixed(2) : 0);
                    pending_total_amt = parseFloat(pending_total_amt) - parseFloat(bal_amt);
                    if(isNaN(pending_total_amt) || pending_total_amt == '') pending_total_amt = 0;
                }else{
                    $(`#vt_adjust_amt_${cnt}`).val(pending_total_amt > 0 ? pending_total_amt.toFixed(2) : 0);
                    pending_total_amt = parseFloat(pending_total_amt) - parseFloat(pending_total_amt);
                    if(isNaN(pending_total_amt) || pending_total_amt == '') pending_total_amt = 0;
                }
            }
            let temp = parseFloat(bal_amt) - parseFloat($(`#vt_adjust_amt_${cnt}`).val());
            if(isNaN(temp) || temp == '') temp = 0;
        }
        calculate_single_trans(cnt)
    }   

    calculate_master_balance();
}
const add_payment_wrapper = purchases => {
    console.log(purchases);
    let data = `
        <thead>
            <tr style="font-size: 15px;">
                <th width="2%"><input type="checkbox" id="parent_checkbox" onclick="select_deselect()" /></th>
                <th width="8%">PURCHASE NO</th>
                <th width="10%">PURCHASE DATE</th>
                <th width="10%">DOLLAR RATE</th>
                <th width="10%">BALANCE AMT</th>
                <th width="10%">ALLOCATED AMT</th>
                <th width="10%">ADJUST AMT</th>
                <th width="10%">CURRENT BAL. AMT</th>
            </tr>
        </thead>
        <tbody id="payment_material_wrapper">
    `;
    purchases.forEach((purchase, index) => {
        const {per_id, am_id, per_entry_no, per_entry_date, per_current_dollar_rate, per_balance, per_allocated_amt} = purchase
        let sr_no = index +1;
        data += `
            <tr id="rowid_${sr_no}" class="floating-form">
                <td class="floating-label">
                    <input type="hidden" id="vt_id_${sr_no}" name="vt_id[]" value="0" />
                    <input type="hidden" id="vt_bill_clear_${sr_no}" name="vt_bill_clear[]" value="NO" />
                    <input type="checkbox" class="checkboxes" id="child_checkbox_${sr_no}" onclick="select_deselect(${sr_no})" />
                </td>
                <td class="floating-label">
                    <input type="hidden" id="vt_purchase_id_${sr_no}" name="vt_purchase_id[]" value="${per_id}" />
                    <input type="hidden" id="vt_am_id_${sr_no}" name="vt_am_id[]" value="${am_id}" />
                    <input type="text" class="form-control floating-input" name="vt_entry_no[]" id="vt_entry_no_${sr_no}" value="${per_entry_no}" readonly />
                </td>
                <td class="floating-label">
                    <input type="text" class="form-control floating-input" name="vt_entry_date[]" id="vt_entry_date_${sr_no}" value="${per_entry_date}" readonly />
                </td>
                <td class="floating-label">
                    <input type="number" class="form-control floating-input" name="vt_dollar_rate[]" id="vt_dollar_rate_${sr_no}" value="${per_current_dollar_rate}" readonly />
                </td>
                <td class="floating-label">
                    <input type="number" class="form-control floating-input" name="vt_total_amt[]" id="vt_total_amt_${sr_no}" value="${per_balance}" readonly />
                </td>
                <td class="floating-label">
                    <input type="number" class="form-control floating-input" name="vt_allocated_amt[]" id="vt_allocated_amt_${sr_no}" value="${per_allocated_amt}" readonly />
                </td>
                <td class="floating-label">
                    <input type="number" class="form-control floating-input" name="vt_adjust_amt[]" id="vt_adjust_amt_${sr_no}" value="0" min="0" oninput="this.value = Math.abs(this.value)" onkeyup="calculate_single_trans(${sr_no})" />
                </td>
                <td class="floating-label">
                    <input type="number" class="form-control floating-input" id="vt_balance_amt_show_${sr_no}" value="${per_balance}" readonly />
                    <input type="hidden" id="vt_balance_amt_${sr_no}" value="${per_balance}" readonly />
                </td>
            </tr>
        `;
    })
    data +=`
        </tbody>
    `;
    $('#voucher_material_wrapper').html(data)
}
const is_amt_matched = (master, trans) =>{
    let master_amt = $(`#${master}`).val();
    if(isNaN(master_amt) || master_amt == '') master_amt = 0;
    let total_trans_amt = 0;
    let total_tr        = $('#payment_material_wrapper tr').length;
    for (let i = 1; i <= total_tr; i++){
        let id = $('#payment_material_wrapper tr:nth-child('+i+')').attr('id');
        let lastunderscore = id.lastIndexOf("_");
        let cnt = id.substring(lastunderscore+1);

        if($(`#child_checkbox_${cnt}`).is(':checked')){
            let trans_amt = $(`#${trans}_${cnt}`).val();
            if(isNaN(trans_amt) || trans_amt == '') trans_amt = 0;
            
            total_trans_amt = parseFloat(total_trans_amt) + parseFloat(trans_amt);
            if(isNaN(total_trans_amt) || total_trans_amt == '') total_trans_amt = 0;
        }    
    }

    if(master_amt == total_trans_amt) return true;
    return false;
}
const check_current_balance = () =>{
    let total_tr        = $('#payment_material_wrapper tr').length;
    for (let i = 1; i <= total_tr; i++){
        let id = $('#payment_material_wrapper tr:nth-child('+i+')').attr('id');
        let lastunderscore = id.lastIndexOf("_");
        let cnt = id.substring(lastunderscore+1);

        if($(`#child_checkbox_${cnt}`).is(':checked')){
            let bal_amt = parseFloat( ('0' + $(`#vt_balance_amt_${cnt}`).val()).replace(/[^0-9-\.]/g, ''), 10 );
            if(isNaN(bal_amt) || bal_amt == '') bal_amt = 0;                    

            let total_amt = parseFloat( ('0' + $(`#vt_total_amt_${cnt}`).val()).replace(/[^0-9-\.]/g, ''), 10 );
            if(isNaN(total_amt) || total_amt == '') total_amt = 0;                  

            let adjust_amt = parseFloat( ('0' + $(`#vt_adjust_amt_${cnt}`).val()).replace(/[^0-9-\.]/g, ''), 10 );
            if(isNaN(adjust_amt) || adjust_amt == '') adjust_amt = 0;                   

            let return_amt = parseFloat( ('0' + $(`#vt_return_amt_${cnt}`).val()).replace(/[^0-9-\.]/g, ''), 10 );
            if(isNaN(return_amt) || return_amt == '') return_amt = 0;                   

            let balance_amt = parseFloat(bal_amt) - parseFloat(adjust_amt);
            if(isNaN(balance_amt) || balance_amt == '') balance_amt = 0;

            if(balance_amt < 0) return false;                   
        }    
    }
    return true;
}