<?php
function get_sm_csr_saving(){
    global $wpdb;
    $_SESSION['sessionSavingsSelectionData'] = array();
    $html = "";
    ob_start();
	if( current_user_can('supportmanager') || current_user_can( 'supportagent' ) ){
        $columnsArr = array(
            'status'            =>  __('Status', CIP_TXTDOMAIN),
            'username'         	=>  __('Username', CIP_TXTDOMAIN),
            'reference'         =>  __('Reference', CIP_TXTDOMAIN),
            'email'             =>  __('Email', CIP_TXTDOMAIN),
            'saving_start_date' =>  __('Start Date', CIP_TXTDOMAIN),
            'saving_end_date' 	=>  __('Date of maturity', CIP_TXTDOMAIN),
            'saving_periods'    =>  __('Duration', CIP_TXTDOMAIN),
            'saving_interest'   =>  __('%', CIP_TXTDOMAIN),
            'saved_amount'      =>  __('Amount', CIP_TXTDOMAIN),
            'interest_amount'   =>  __('Interest', CIP_TXTDOMAIN),
        );
    ?>
    <div class="csr_delivery_summary_savings">
        <div class="d-flex" style="column-gap:30px;">
            <div>
                <h6 class="m-0"><?php _e('CSR Savings Summary', CIP_TXTDOMAIN ); ?></h6>
                <p class="text-left mb-0"> <?php _e('Filtered Total Amount: ', CIP_TXTDOMAIN ); ?><span class="total_amount_saved_label"></span> </p>
                <p class="text-left mb-0"> <?php _e('Filtered Selected Total Amount: ', CIP_TXTDOMAIN ); ?><span class="total_selected_amount_saved_label"></span> </p>
                <p class="text-left mb-0"> <?php _e('Filtered Selected Interest Amount: ', CIP_TXTDOMAIN ); ?><span class="total_selected_interest_amount_label"></span> </p>
            </div>
            <div>
                <button type="button" class="btn btn-primary csr_saving_paid" style="padding: 10px 10px !important;"><?php _e('Process', CIP_TXTDOMAIN); ?></button>
            </div>
        </div>
    </div>
    <table id="sm_csr_savings_list" data-toolbar="false" data-filter-control="true" data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="true" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" class="table table-bordered" data-side-pagination="server" data-page-size="20" data-page-list="[20, 30, 50, 100]" data-response-handler="responseHandlerCsrSavings" data-query-params="queryParams">
        <thead>
        <tr>
            <th data-field="rowiddata" data-switchable="false"><input type="checkbox" name="toggleCsrSaveAll" id="toggleCsrSaveAll" /></th>
            <th data-field="id" class="id"><?php _e('Id',CIP_TXTDOMAIN); ?></th>
            <?php
            if( $columnsArr ){
                foreach( $columnsArr as $columnKey => $columnsVal ){
                    $filter_attr = 'data-filter-control="input"';
                    $filterData_attr = '';
                    if( $columnKey == 'status'  ){
                        $filterData_attr = ' data-filter-data="var:filterSavingsStatus"';
                        $filter_attr = 'data-filter-control="select" class="'.$columnKey.'"'.$filterData_attr;
                    }
                ?>
                <th data-field="<?php echo $columnKey ?>" data-sortable="true" <?php echo $filter_attr; ?> class="<?php echo $columnKey ?>"><?php echo $columnsVal; ?></th>
                <?php
                }
            }
            ?>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <div class="modal fade" id="csrSavingPaidModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body">
                    <div class="container-fluid">
                        <span class="withdrawal_close_btn close" data-dismiss="modal">&times;</span>

                        <div class="csrSavingPaidBody"></div>

                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php
	}
	$html .= ob_get_clean();
	return $html;
}
add_action('wp_head','bst_filter_var_declarations_csr_saving_table');
function bst_filter_var_declarations_csr_saving_table(){
    $filterSavingsStatus = array(
		'active' 	=>	'Active',
		'matured'   =>	'Matured',
		'paid'	    =>	'Paid',
	);
    ?><script>var filterSavingsStatus = <?php echo json_encode( $filterSavingsStatus ); ?>;</script><?php
}
add_action('wp_footer','init_bs_paging_ajax_csr_saving_table_script');
function init_bs_paging_ajax_csr_saving_table_script(){
    $sm_csr_savings_list_url = add_query_arg( [
		'action'	=>	'sm_csr_savings_list_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
    ?>
    <script>
    jQuery(document).ready(function($){
        if( $('#sm_csr_savings_list').length > 0 ){		
            var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

            var sm_csr_savings_list_url = "<?php echo $sm_csr_savings_list_url ?>";
            var $tableCsrSavings = $('#sm_csr_savings_list');
            var params = {};
            var thisRows = [];
            var isSelectAll = 0;
            $tableCsrSavings.bootstrapTable({
                method: 'post',
                contentType: 'application/x-www-form-urlencoded',
                url: sm_csr_savings_list_url,
                searchOnEnterKey: true,
                queryParams: function (p) {
                    params = p.filter;
                    if( $('#sm_csr_savings_list input[name="toggleCsrSaveAll"]').is(':checked') ){
                        isSelectAll = 1;
                    }else{
                        isSelectAll = 0;
                    }
                    
                    return {
                        columnfilter: p.filter,
                        limit: p.limit,
                        offset: p.offset,
                        sort: p.sort,
                        order: p.order,
                        isSelectAll: isSelectAll,
                    };
                },
                stickyHeader: false,
                onPostBody: function (){
                    if( $('[data-toggle-tt="tooltip"]').length > 0 ){
                        $('[data-toggle-tt="tooltip"]').tooltip();
                    }
                    $('.filter-control input.search-input').prop('readonly',false);
                    $('.filter-control select.form-control').removeClass('pointerEno');
                    $('.csr_saving_paid').removeClass('disabled').prop('disabled', false);
                },
                onSearch: function( search ){
                    $('.filter-control input.search-input').prop('readonly',true);
                    $('.filter-control select.form-control').addClass('pointerEno');
                    $('.total_amount_due_label').html('-');
                    $('.total_selected_amount_due_label').html('-');
                    $('.csr_saving_paid').addClass('disabled').prop('disabled', true);
                },
                onLoadSuccess: function( search ){
                }
            });
            //store toggle column
            let ls_saving_name = '-hideColumn-sm_csr_savings_list'
            let hideColumn = JSON.parse(localStorage.getItem(ls_saving_name)) || [];
            let th = $tableCsrSavings.find('thead tr th');
            th.each(function (index) {
                let attrTitle = $(this).attr('data-field')
                if (hideColumn.includes(attrTitle)) {
                    $tableCsrSavings.bootstrapTable('hideColumn', attrTitle);
                }
            })
            $tableCsrSavings.on("column-switch.bs.table", function (e, field, checked) {
                if (checked && hideColumn.includes(field)) {
                    // remove form local storage
                    const index = hideColumn.indexOf(field);
                    if (index > -1) {
                        hideColumn.splice(index, 1);
                        localStorage.setItem(ls_saving_name, JSON.stringify(hideColumn))
                    }
                } else if (!checked) {
                    if (hideColumn.includes(field)) {} else {
                        hideColumn.push(field);
                        localStorage.setItem(ls_saving_name, JSON.stringify(hideColumn))
                    }
                }
            });
            $("body").on("change", ".toggle-all", function () {
                let $this = $(this);
                let div = $this.parent().parent()[0];
                $(div).find("input[type=checkbox]").each(function (index) {
                    let checked = $(this).is(":checked");
                    let field = $(this).attr("data-field");
                    if (checked && hideColumn.includes(field)) {
                        // remove form local storage
                        const index = hideColumn.indexOf(field);
                        if (index > -1) {
                            hideColumn.splice(index, 1);
                            localStorage.setItem(
                                ls_saving_name,
                                JSON.stringify(hideColumn)
                            );
                        }
                    } else if (!checked) {
                        if (hideColumn.includes(field)) {
                            // hands up nothing needed
                        } else {
                            // add in LS for nexttime
                            hideColumn.push(field);
                            localStorage.setItem(
                                ls_saving_name,
                                JSON.stringify(hideColumn)
                            );
                        }
                    }
                });
            });
            //store toggle column end

            $('body').on('change', 'input[name="toggleCsrSaveAll"]', function(){
                let eve = jQuery.Event("keyup");
                eve.which = 13
                eve.keyCode = 13
                $('#sm_csr_savings_list thead th .filter-control .search-input:first').trigger(eve);
                var isSelectAll = 0;
                if( $('#sm_csr_savings_list input[name="toggleCsrSaveAll"]').is(':checked') ){
                    isSelectAll = 1;
                }else{
                    isSelectAll = 0;
                }
            });
            $('body').on('click', 'button.csr_saving_paid', function(){
                var $tableCsrSavings = $('#sm_csr_savings_list');
                var isSelectAll = 0;
                if( $('#sm_csr_savings_list input[name="toggleCsrSaveAll"]').is(':checked') ){
                    isSelectAll = 1;
                }else{
                    isSelectAll = 0;
                }
                
                var data = { 'action' : 'checkingCsrSavingPaid', 'thisParams' : params, 'isSelectAll' : isSelectAll, '_micro' : "<?php echo wp_create_nonce('_XyCheckCSRSavingPaidyX_'); ?>" };
                $.blockUI(block_config);
                $.post(cipscript.ajax_url, data, function(response) {
                    var obj = JSON.parse( response );
                    if( obj.error == 0 ){
                        $('#csrSavingPaidModal .csrSavingPaidBody').html('');
                        $('#csrSavingPaidModal').modal({backdrop: 'static',keyboard: false});
                        $('#csrSavingPaidModal .csrSavingPaidBody').html( obj.html );
                    }else{
                        swalToast({ type: 'error', title: obj.msg });
                    }
                    $.unblockUI();
                });
                return false;
            });

            
            $("#csrSavingPaidModal").on('hide.bs.modal', function () {
                $('#csrSavingPaidModal .csrSavingPaidBody').html('');
            });

            $('body').on('submit', '#csrsavingpaid_frm', function(){
                $form = $(this);
                var isSelectAll = 0;
                if( $('#sm_csr_savings_list input[name="toggleCsrSaveAll"]').is(':checked') ){
                    isSelectAll = 1;
                }else{
                    isSelectAll = 0;
                }
                if( $(this).find('input[name="sasm_ga_otp"]').val() == "" ){
                    swalToast({ type: 'error', title: 'Please enter 6-digit google authenticator code.' });
                    return false;
                }
                var data = $(this).serialize() + '&thisParams='+params+'&isSelectAll='+isSelectAll;
                $form.block( block_config );
                $.post(cipscript.ajax_url, data, function(response) {
                    var obj = JSON.parse( response );
                    if( obj.error == 0 ){
                        swalToast({ type: 'success', title: obj.msg });
                        $("#csrSavingPaidModal").modal('hide');
						setTimeout(() => {
							window.location.reload();
						}, 2000);
                    }else{
                        swalToast({ type: 'error', title: obj.msg });
                    }
                    $form.unblock();
                });
                return false;
            });

            if( $('#sm_csr_savings_list .saving_start_date').length > 0 ){
                let dateFormatWD = 'DD/MM/YYYY';
                $('input.bootstrap-table-filter-control-saving_start_date[type="search"]')
                .daterangepicker({
                        autoUpdateInput: false,
                        locale: {
                            format: dateFormatWD,
                            separator: ' - ',
                            firstDay: 1
                        },
                        opens: 'left',
                        cancelButtonClasses: 'btn-default'
                    },
                );
                jQuery('input.bootstrap-table-filter-control-saving_start_date[type="search"]').on('apply.daterangepicker', function(ev, picker) {
                    $(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
                    let eve = jQuery.Event("keyup");
                    eve.which = 13
                    eve.keyCode = 13
                    $('.bootstrap-table-filter-control-saving_start_date').trigger(eve);
                });
                $('input.bootstrap-table-filter-control-saving_start_date[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
                    $(this).val('');
                    let eve = jQuery.Event("keyup");
                    eve.which = 13
                    eve.keyCode = 13
                    $('.bootstrap-table-filter-control-saving_start_date').trigger(eve);
                });
            }
            if( $('#sm_csr_savings_list .saving_end_date').length > 0 ){
                let dateFormatWD = 'DD/MM/YYYY';
                $('input.bootstrap-table-filter-control-saving_end_date[type="search"]')
                .daterangepicker({
                        autoUpdateInput: false,
                        locale: {
                            format: dateFormatWD,
                            separator: ' - ',
                            firstDay: 1
                        },
                        opens: 'left',
                        cancelButtonClasses: 'btn-default'
                    },
                );
                jQuery('input.bootstrap-table-filter-control-saving_end_date[type="search"]').on('apply.daterangepicker', function(ev, picker) {
                    $(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
                    let eve = jQuery.Event("keyup");
                    eve.which = 13
                    eve.keyCode = 13
                    $('.bootstrap-table-filter-control-saving_end_date').trigger(eve);
                });
                $('input.bootstrap-table-filter-control-saving_end_date[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
                    $(this).val('');
                    let eve = jQuery.Event("keyup");
                    eve.which = 13
                    eve.keyCode = 13
                    $('.bootstrap-table-filter-control-saving_end_date').trigger(eve);
                });
            }

            $('body').on('change', '#sm_csr_savings_list input.rowiddata', function(){
    
                var selectedAllOption = 0;
                var thisRowSelected = 0;
                if( $('#sm_csr_savings_list input[name="toggleCsrSaveAll"]').is(':checked') ){
                    selectedAllOption = 1;
                }
                if( $(this).is(':checked') ){
                    thisRowSelected = 1;
                }
    
                var $tableElem = $('#sm_csr_savings_list');
                $tableElem.block( block_config );
    
                $('.csr_partial_delivery').addClass('disabled').prop('disabled', true);
                var data = {'action':'cip_wd_selection_storing_act', 'thisId':$(this).val(), 'selectedAllOption':selectedAllOption, 'thisRowSelected':thisRowSelected};
                var container = $(this).closest('tr');
                $.post(cipscript.ajax_url, data)
                .fail(function() {
                    swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
                    if( thisRowSelected == 1 ){
                        $(this).prop('checked', false);
                    }else{
                        $(this).prop('checked', true);
                    }
                })
                .done(function(response) {
                    if( response.error == 0 ){
    
                        /* let eve = jQuery.Event("keyup");
                        eve.which = 13
                        eve.keyCode = 13
                        $('#sm_csr_savings_list thead th .filter-control .search-input:first').trigger(eve); */
    
                        var $tableCsrSavings = $('#sm_csr_savings_list');
                        $tableCsrSavings.bootstrapTable('refresh');
    
    
                        //saved, nothing to do
                        if( partial_delivery_total > 0 && partial_delivery_total <= 15 ){
                            $('.csr_partial_delivery').removeClass('disabled').prop('disabled', false);
                        }
                    }else{
                        swalToast({ type: 'error', title: response.msg });
                        if( thisRowSelected == 1 ){
                            $(this).prop('checked', false);
                        }else{
                            $(this).prop('checked', true);
                        }
                    }
                    $(container).unblock();
                })
                .always(function(response) {
                    if (!response.isReset) {
                        $(container).find('input, button').prop('disabled', false);
                        $(container).removeClass('working');
                        $(container).unblock();
                    }
                    $tableElem.unblock();
                });
            });
            
            $('body').on('change', '#sm_csr_savings_list input.rowiddata', function(){
    
                var selectedAllOption = 0;
                var thisRowSelected = 0;
                if( $('#sm_csr_savings_list input[name="toggleCsrSaveAll"]').is(':checked') ){
                    selectedAllOption = 1;
                }
                if( $(this).is(':checked') ){
                    thisRowSelected = 1;
                }
    
                var $tableElem = $('#sm_csr_savings_list');
                $tableElem.block( block_config );
    
                $('.csr_saving_paid').addClass('disabled').prop('disabled', true);
                var data = {'action':'cip_csr_saving_selection_storing_act', 'thisId':$(this).val(), 'selectedAllOption':selectedAllOption, 'thisRowSelected':thisRowSelected};
                var container = $(this).closest('tr');
                $.post(cipscript.ajax_url, data)
                .fail(function() {
                    swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
                    if( thisRowSelected == 1 ){
                        $(this).prop('checked', false);
                    }else{
                        $(this).prop('checked', true);
                    }
                })
                .done(function(response) {
                    if( response.error == 0 ){
    
                        var $tableCsrSavings = $('#sm_csr_savings_list');
                        $tableCsrSavings.bootstrapTable('refresh');
    
                    }else{
                        swalToast({ type: 'error', title: response.msg });
                        if( thisRowSelected == 1 ){
                            $(this).prop('checked', false);
                        }else{
                            $(this).prop('checked', true);
                        }
                    }
                    $(container).unblock();
                })
                .always(function(response) {
                    if (!response.isReset) {
                        $(container).find('input, button').prop('disabled', false);
                        $(container).removeClass('working');
                        $(container).unblock();
                    }
                    $tableElem.unblock();
                });
            });

            $('body').on('change', 'input[name="toggleCsrSaveAll"]', function(){
                var thisRowSelected = 0;
                if( $(this).is(':checked') ){
                    thisRowSelected = 1;
                }
                var data = {'action':'cip_csr_saving_selection_clearing_act'};
                var container = $(this).closest('tr');
                $.post(cipscript.ajax_url, data)
                .fail(function() {
                    swalToast({ type: 'error', title: 'Something went wrong. Please try again.' });
                    if( thisRowSelected == 1 ){
                        $(this).prop('checked', false);
                    }else{
                        $(this).prop('checked', true);
                    }
                })
                .done(function(response) {
                    if( response.error == 0 ){
                        //saved, nothing to do
                    }else{
                        swalToast({ type: 'error', title: response.msg });
                        if( thisRowSelected == 1 ){
                            $(this).prop('checked', false);
                        }else{
                            $(this).prop('checked', true);
                        }
                    }
                    $(container).unblock();
                })
                .always(function(response) {
                    if (!response.isReset) {
                        $(container).find('input, button').prop('disabled', false);
                        $(container).removeClass('working');
                        $(container).unblock();
                    }
                });
            });

        }

    });
    function responseHandlerCsrSavings(res){
        if( res.total_saved_amount ){
            $('.total_amount_saved_label').show().html( res.total_saved_amount );
            $('.total_selected_amount_saved_label').show().html( res.total_selected_saved_amount );
            $('.total_selected_interest_amount_label').show().html( res.total_selected_interest );
        }else{
            $('.total_amount_saved_label').html('-');
            $('.total_selected_amount_saved_label').html('-');
            $('.total_selected_interest_amount_label').html('-');
        }
        return res;
    }
    </script>
    <?php
}
add_action('wp_ajax_sm_csr_savings_list_loader','cip_sm_csr_savings_list_loader_cb');
function cip_sm_csr_savings_list_loader_cb(){
    global $wpdb;
	$tableCsrSavings = $wpdb->prefix.'csr_savings';
	$user_id = get_current_user_id();

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrSavings WHERE 1 ORDER BY `id` DESC");

    $limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 20;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : "`status`='matured' desc, `status`='active' desc, `status`='paid' desc, STR_TO_DATE(`saving_end_date`,'%d/%m/%Y')";
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';
	$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;

    $sessionSavingsSelectionDataEncrypt = ( isset( $_SESSION['sessionSavingsSelectionData'] ) && !empty( $_SESSION['sessionSavingsSelectionData'] ) ) ? $_SESSION['sessionSavingsSelectionData'] : array();
	$sessionSavingsSelectionData = array();
	if( !empty( $sessionSavingsSelectionDataEncrypt ) ){
		foreach( $sessionSavingsSelectionDataEncrypt as $encryptId ){
			$decryptedIdRaw = base64_decode( $encryptId );
			$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_CSavingSelection_PIC') ), '', $decryptedIdRaw);
			$sessionSavingsSelectionData[] = $decryptedUserId;
		}
	}

    $filter_qry = "";

	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
    
    $isNumericColumn = array('saving_periods', 'saving_interest', 'saved_amount');
    $isDateColumn = array('saving_start_date', 'saving_end_date');

	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'status'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
				if( str_contains($filterData, '-') ){ //between
					$filterDataMinMax = explode('-', $filterData);
					$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
				}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
					$filter_qry .= " AND `$filterKey` $filterData";
				}else{
					$filter_qry .= " AND `$filterKey` = " . $filterData . "";
				}
			}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
				if( str_contains($filterData, ' - ') ){
					$filterDataMinMax = explode(' - ', $filterData);
					$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
				}else{
					$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
				}
			}else{				
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrSavings WHERE 1 $filter_qry ORDER BY `id` DESC");
	}
	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%d/%m/%Y')";
	}
	
	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableCsrSavings WHERE 1 $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");
	
	
	$saUserData = get_user_by( 'id', $user_id );
	
    $columnsArr = array(
        'status'            =>  __('Status', CIP_TXTDOMAIN),
        'username'          =>  __('Username', CIP_TXTDOMAIN),
        'reference'         =>  __('Reference', CIP_TXTDOMAIN),
        'email'             =>  __('Email', CIP_TXTDOMAIN),
        'saving_start_date' =>  __('Start Date', CIP_TXTDOMAIN),
        'saving_end_date' 	=>  __('Date of maturity ', CIP_TXTDOMAIN),
        'saving_periods'    =>  __('Duration', CIP_TXTDOMAIN),
        'saving_interest'   =>  __('%', CIP_TXTDOMAIN),
        'saved_amount'      =>  __('Amount', CIP_TXTDOMAIN),
        'interest_amount'   =>  __('Interest', CIP_TXTDOMAIN),
    );

	$total_saved_amount = 0;
	$getAmountDue = $wpdb->get_row("SELECT SUM(`saved_amount`) as `total_saved_amount` FROM $tableCsrSavings WHERE 1 $filter_qry");
	if( $getAmountDue ){
		$total_saved_amount = $getAmountDue->total_saved_amount;
	}

	$sessionDataQry = "";
	if( $isSelectAll == 1 && !empty( $sessionSavingsSelectionData ) ){
		$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSavingsSelectionData) .')';
	}else if( $isSelectAll == 0 && !empty( $sessionSavingsSelectionData ) ){
		$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSavingsSelectionData) .')';
	}
    
	$total_selected_saved_amount = 0;
	$total_selected_interest = 0;
	if( $isSelectAll != 0 || !empty( $sessionSavingsSelectionData ) ){
		$getSelectedSavedAmount = $wpdb->get_row("SELECT SUM(`saved_amount`) as `total_selected_saved_amount` FROM $tableCsrSavings WHERE 1 $filter_qry $sessionDataQry");
		$getSelectedInterestAmount = $wpdb->get_row("SELECT SUM( ( `saved_amount` * `saving_interest` ) / 100 ) as `total_selected_interest` FROM $tableCsrSavings WHERE 1 $filter_qry $sessionDataQry");
		if( $getSelectedSavedAmount ){
			$total_selected_saved_amount = $getSelectedSavedAmount->total_selected_saved_amount;
		}
		if( $getSelectedInterestAmount ){
			$total_selected_interest = $getSelectedInterestAmount->total_selected_interest;
		}
	}
	
	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			
			if( $isSelectAll == 1 ){
				$currentSelected = 1;
			}else if( $isSelectAll == 0 ){
				$currentSelected = 0;
			}
			$rowEncryptId = base64_encode( $getCurrentMember->id . md5('CIP_CSavingSelection_PIC') );
			$partialDeliverIds[] = $rowEncryptId;
			
			$sessionSavingsSelectionData = ( isset( $_SESSION['sessionSavingsSelectionData'] ) && !empty( $_SESSION['sessionSavingsSelectionData'] ) ) ? $_SESSION['sessionSavingsSelectionData'] : array();
			if( $isSelectAll == 1 && in_array( $rowEncryptId, $sessionSavingsSelectionData ) ){
				$currentSelected = 0;
			}else if( $isSelectAll == 0 && !in_array( $rowEncryptId, $sessionSavingsSelectionData ) ){
				$currentSelected = 1;
			}

			$row['rowiddata'] = '<input type="checkbox" name="rowiddata" class="rowiddata" data-savedamount="'. $getCurrentMember->saved_amount .'" value="'.$rowEncryptId.'" '.checked( $isSelectAll, $currentSelected, false ).' />';
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					
					if($columnKey == 'saved_amount'){
						$row[$columnKey] =  number_format( round( $columnsDataVal ) );
					}else if($columnKey == 'status'){
						$row[$columnKey] =  ucfirst( $columnsDataVal );
					}else if($columnKey == 'saving_interest'){
						$row[$columnKey] =  $columnsDataVal.'%';
					}else if($columnKey == 'interest_amount'){

                        $interest_amount = 0;
                        try {
                            $interest_amount = ( $getCurrentMember->saved_amount * $getCurrentMember->saving_interest ) / 100;
                        } catch (\Throwable $th) {
                            
                        }

                        $columnsDataVal = number_format( round( $interest_amount ) );

						$row[$columnKey] =  $columnsDataVal;
					}else{
						$row[$columnKey] = $columnsDataVal;
					}
				}
			}
			
			$rows[] = $row;
			$sno=$sno+1;
		}
	}

	$out = array(
		'total'		                    =>	$total_items,
		'rows'		                    =>	$rows,
		'total_saved_amount'	        =>	number_format( round( $total_saved_amount ) ),
		'total_selected_saved_amount'	=>	number_format( round( $total_selected_saved_amount ) ),
		'total_selected_interest'	    =>	number_format( round( $total_selected_interest ) )
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_csr_saving_selection_storing_act', 'cip_csr_saving_selection_storing_act_callback');
function cip_csr_saving_selection_storing_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		$selectedAllOption = $_POST['selectedAllOption'];
		$thisId = $_POST['thisId'];
		$thisRowSelected = $_POST['thisRowSelected'];
		$sessionSavingsSelectionData = ( isset( $_SESSION['sessionSavingsSelectionData'] ) && !empty( $_SESSION['sessionSavingsSelectionData'] ) ) ? $_SESSION['sessionSavingsSelectionData'] : array();
		if( $selectedAllOption == 1 ){
			if( $thisRowSelected == 0 ){
				$sessionSavingsSelectionData[] = $thisId;
				$_SESSION['sessionSavingsSelectionData'] = array_unique( $sessionSavingsSelectionData );
			}else{
				$key = array_search($thisId, $sessionSavingsSelectionData, true);
				if ($key !== false) {
					unset($sessionSavingsSelectionData[$key]);
					$_SESSION['sessionSavingsSelectionData'] = array_unique( $sessionSavingsSelectionData );
				}
			}
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
		}else if( $selectedAllOption == 0 ){
			if( $thisRowSelected == 1 ){
				$sessionSavingsSelectionData[] = $thisId;
				$_SESSION['sessionSavingsSelectionData'] = array_unique( $sessionSavingsSelectionData );
			}else{
				$key = array_search($thisId, $sessionSavingsSelectionData, true);
				if ($key !== false) {
					unset($sessionSavingsSelectionData[$key]);
					$_SESSION['sessionSavingsSelectionData'] = array_unique( $sessionSavingsSelectionData );
				}
			}
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
		}
	}
	wp_send_json($out);
	exit;
}
add_action('wp_ajax_cip_csr_saving_selection_clearing_act', 'cip_csr_saving_selection_clearing_act_callback');
function cip_csr_saving_selection_clearing_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		$_SESSION['sessionSavingsSelectionData'] = array();
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
	}
	wp_send_json($out);
	exit;
}
add_action( 'wp_ajax_checkingCsrSavingPaid', 'checkingCsrSavingPaid_callback' );
function checkingCsrSavingPaid_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCheckCSRSavingPaidyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$sessionSavingsSelectionDataEncrypt = ( isset( $_SESSION['sessionSavingsSelectionData'] ) && !empty( $_SESSION['sessionSavingsSelectionData'] ) ) ? $_SESSION['sessionSavingsSelectionData'] : array();
		$sessionSavingsSelectionData = array();
		if( !empty( $sessionSavingsSelectionDataEncrypt ) ){
			foreach( $sessionSavingsSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_CSavingSelection_PIC') ), '', $decryptedIdRaw);
				$sessionSavingsSelectionData[] = $decryptedUserId;
			}
		}
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		
        $google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;
		
		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSavingsSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSavingsSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSavingsSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSavingsSelectionData) .')';
		}
		global $wpdb;
		$tableCsrSavings = $wpdb->prefix.'csr_savings';
		
		$filter_qry = "";
		
		$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
		
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrSavings WHERE 1 AND `saved_amount` > 0 AND `status` = 'matured' $sessionDataQry");
		$total_items_active_status = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrSavings WHERE 1 AND `status` != 'matured' $sessionDataQry");

		$isNumericColumn = array( 'saving_periods', 'saving_interest', 'saved_amount' );
		$isDateColumn = array( 'saving_start_date', 'saving_end_date' );
		if( !empty( $filters ) ){
			foreach( $filters as $filterKey => $filterData ){
				if( $filterKey == 'status'  ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
					if( str_contains($filterData, '-') ){ //between
						$filterDataMinMax = explode('-', $filterData);
						$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
					}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
						$filter_qry .= " AND `$filterKey` $filterData";
					}else{
						$filter_qry .= " AND `$filterKey` = " . $filterData . "";
					}
				}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
					if( str_contains($filterData, ' - ') ){
						$filterDataMinMax = explode(' - ', $filterData);
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
					}else{
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
					}
				}else{
					$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
				}
			}
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrSavings WHERE 1 $filter_qry AND `saved_amount` > 0 AND `status`='matured' $sessionDataQry");
			$total_items_active_status = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrSavings WHERE 1 $filter_qry AND `status` != 'matured' $sessionDataQry");
		}

        if( $total_items_active_status ){
            $out = array( "error" => 1,'msg' => __('Current selection have other then Matured status records.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
        }

		$total_saved_amount = 0;
		$getAmountDue = $wpdb->get_row("SELECT SUM(`saved_amount`) as `total_saved_amount` FROM $tableCsrSavings WHERE 1 $filter_qry AND `saved_amount` > 0 AND `status`='matured' $sessionDataQry");
		if( $getAmountDue ){
			$total_saved_amount = $getAmountDue->total_saved_amount;
		}
		
        $total_interest_amount = 0;
		$getInterestAmount = $wpdb->get_row("SELECT SUM( ( `saved_amount` * `saving_interest` ) / 100 ) as `total_interest_amount` FROM $tableCsrSavings WHERE 1 $filter_qry AND `saved_amount` > 0 AND `status`='matured' $sessionDataQry");
		if( $getInterestAmount ){
			$total_interest_amount = $getInterestAmount->total_interest_amount;
		}

		if( $total_saved_amount <= 0 ){
			$out = array( "error" => 1,'msg' => __('No CSR available for Saving with current selection.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$html = "";
		ob_start();
		?>
		<form name="csrsavingpaid_frm" id="csrsavingpaid_frm">
			<div class="csr_delivery_summary_modal">
				<div class="d-flex" style="column-gap:30px;">
					<div>
						<h6 class="mb-1"><?php _e('CSR Savings Summary', CIP_TXTDOMAIN ); ?></h6>
						<p class="text-left mb-1"> <?php _e('Filtered Total Amount: ', CIP_TXTDOMAIN ); ?><span><?php echo number_format( round( $total_saved_amount ) ); ?></span> </p>
						<p class="text-left mb-1"> <?php _e('Filtered Total Interest Amount: ', CIP_TXTDOMAIN ); ?><span><?php echo number_format( round( $total_interest_amount ) ); ?></span> </p>
						<p class="text-left mb-1"> <?php _e('Rows to update: ', CIP_TXTDOMAIN ); ?><span><?php echo number_format( $total_items ); ?></span> </p>
					</div>
				</div>
			</div>
			<input type="hidden" name="action" value="csrSavingPaidAction" />
			<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_XyCSRSavingPaidyCSRX_') ?>" />
			<hr class="mt-1 mb-1">
			<div class="otp_section pb-3">
				<label for="sasm_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
				<input type="text" name="sasm_ga_otp" id="sasm_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
				<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
			</div>
			<input type="submit" class="btn btn-primary" name="submit" value="<?php _e('Submit', CIP_TXTDOMAIN); ?>" />
		</form>
		<?php
		$html .= ob_get_clean();
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_csrSavingPaidAction', 'csrSavingPaidAction_callback' );
function csrSavingPaidAction_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCSRSavingPaidyCSRX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$sessionSavingsSelectionDataEncrypt = ( isset( $_SESSION['sessionSavingsSelectionData'] ) && !empty( $_SESSION['sessionSavingsSelectionData'] ) ) ? $_SESSION['sessionSavingsSelectionData'] : array();
		$sessionSavingsSelectionData = array();
		if( !empty( $sessionSavingsSelectionDataEncrypt ) ){
			foreach( $sessionSavingsSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_CSavingSelection_PIC') ), '', $decryptedIdRaw);
				$sessionSavingsSelectionData[] = $decryptedUserId;
			}
		}
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSavingsSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSavingsSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSavingsSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSavingsSelectionData) .')';
		}
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;
		
		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		if( !empty( $_POST['sasm_ga_otp'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['sasm_ga_otp'], 0) ){
				global $wpdb;
				$tableCsrSavings = $wpdb->prefix.'csr_savings';
				$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
				$tableTokenHolder = $wpdb->prefix.'token_holder';
				$filter_qry = "";
				
				$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
				
				$isNumericColumn = array('saving_periods', 'saving_interest', 'saved_amount');
				$isDateColumn = array('saving_start_date', 'saving_end_date');
				
				if( !empty( $filters ) ){
					foreach( $filters as $filterKey => $filterData ){
						if( $filterKey == 'status'  ){
							$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
						}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
							if( str_contains($filterData, '-') ){ //between
								$filterDataMinMax = explode('-', $filterData);
								$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
							}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
								$filter_qry .= " AND `$filterKey` $filterData";
							}else{
								$filter_qry .= " AND `$filterKey` = " . $filterData . "";
							}
						}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
							if( str_contains($filterData, ' - ') ){
								$filterDataMinMax = explode(' - ', $filterData);
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
							}else{
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
							}
						}else{				
							$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
						}
					}
				}
	
				$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableCsrSavings WHERE 1 $filter_qry AND `saved_amount` > 0 AND `status` = 'matured' $sessionDataQry");
				
				if( $getCurrentMembers ){
					
					$uniqueReference = uniqidReal();
					foreach( $getCurrentMembers as $getCurrentMember ){
						$saved_amount = $getCurrentMember->saved_amount;
						if( $saved_amount > 0 ){

							$username = $getCurrentMember->username;

							$logs = sprintf( __('CSR Savings Paid. username: %s, email: %s, reference: %s, saved_amount: %s by %s at %s', 'corsair-login'), $username, $getCurrentMember->email, $getCurrentMember->reference, $saved_amount, $current_user->user_email, date_i18n('d/m/Y H:i A') );
							
							$userData = get_user_by('email', $getCurrentMember->email);
							
							$holder_user_id = 0;
							if( $userData ){
								$holder_user_id = $userData->ID;
							}
							$transactionData = array(
								'user_id'			=>	$holder_user_id,
								'txn_id'			=>	$getCurrentMember->reference,
								'email'				=>	$getCurrentMember->email,
								'username'			=>	$username,
								'withdrawal_amount'	=>	0,
								'received_amount'	=>	$saved_amount,
								'withdrawal_fee'	=>	0,
								'type'				=>	'deposit',
								'description'		=>	$logs,
								'short_description'	=>	__('Matured CSR saving', CIP_TXTDOMAIN),
								'_date'				=>	date_i18n('Y-m-d H:i:s'),
								'status'			=>	0
							);
							$transInsert = $wpdb->insert( $tableTransactionHistory, $transactionData );

							if( $transInsert ){
								create_cip_logs_entery( $user_id, 'wallet_saving_deposit', '','sm', $logs, true  );

                                $deliveryBatchId = get_option('saving_delivery_batch_id');
                                if( !empty( $deliveryBatchId ) ){
                                    $deliveryBatchId = $deliveryBatchId + 1;
                                }else{
                                    $deliveryBatchId = 1;
                                }
                                $note_8 = $deliveryBatchId;

								$interest_amount = 0;
								try {
									$interest_amount = round( ( $getCurrentMember->saved_amount * $getCurrentMember->saving_interest ) / 100 );

								} catch (\Throwable $th) {
									
								}

								$interestLogs = sprintf( __('CSR Savings Interest Paid. username: %s, email: %s, reference: %s, saved_interest_amount: %s by %s at %s', 'corsair-login'), $username, $getCurrentMember->email, $getCurrentMember->reference.'-i', $interest_amount, $current_user->user_email, date_i18n('d/m/Y H:i A') );
								$interestTransactionData = array(
									'user_id'			=>	$holder_user_id,
									'txn_id'			=>	$getCurrentMember->reference.'-i',
									'email'				=>	$getCurrentMember->email,
									'username'			=>	$username,
									'withdrawal_amount'	=>	0,
									'received_amount'	=>	round( $interest_amount, 2 ),
									'withdrawal_fee'	=>	0,
									'type'				=>	'deposit',
									'description'		=>	$interestLogs,
									'short_description'	=>	__('CSR Saving interest', CIP_TXTDOMAIN),
									'_date'				=>	date_i18n('Y-m-d H:i:s'),
									'status'			=>	0
								);
								$interestTransInsert = $wpdb->insert( $tableTransactionHistory, $interestTransactionData );
								if( $interestTransInsert ){
									create_cip_logs_entery( $user_id, 'wallet_saving_deposit', '','sm', $interestLogs, true  );
								}

								//update status to paid
								$wpdb->query( $wpdb->prepare( "UPDATE $tableCsrSavings SET `status` = '%s' WHERE `id` = %d", 'paid', $getCurrentMember->id ) );


                                //update record to token holder from saved csr to delivered + add interest new entry
                                $getTokenHolderDatabyRef = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE `reference`='". $getCurrentMember->reference ."' LIMIT 1");
                                
                                if( $getTokenHolderDatabyRef ){
                                    
                                    $updateNoteArr = array();
                                    $rowNotes = explode("|",$getTokenHolderDatabyRef->notes_external);

                                    $updateNoteArr[] = 'Matured CSR saving.';

                                    if( !empty( $rowNotes ) ){
                                        foreach( $rowNotes as $rowNote){
                                            $rowNote = trim( $rowNote );
                                            if( !empty( $rowNote ) ){
                                                $updateNoteArr[] = $rowNote;
                                            }
                                        }
                                    }
                                    if( !empty( $updateNoteArr ) ){
                                        foreach( $updateNoteArr as $key => $updateNote ){
                                            if( $updateNote == 'Saved CSR.' || $updateNote == 'Saved CSR' ){
                                                unset( $updateNoteArr[ $key ] );
                                            }
                                        }
                                    }

                                    $notesString = "";
                                    $updateNoteArr = array_unique($updateNoteArr);
                                    if( !empty( $updateNoteArr ) ){
                                        foreach( $updateNoteArr as $updateNoteArrVal ){
                                            $notesString .= '| '. $updateNoteArrVal .' |';
                                        }
                                        $notesString = notes_trim_pipe( $notesString );
                                    }

                                    $updateSavedCsr = $wpdb->query( $wpdb->prepare( "UPDATE $tableTokenHolder SET `corp_approved` = '%s', `notes_external` = '%s', `date_1` = '%s', `note_8` = '%s' WHERE `id` = %d AND `reference` = '%s'", 'Delivered', $notesString, date_i18n('d/m/Y'), $note_8, $getTokenHolderDatabyRef->id, $getCurrentMember->reference ) );
                                    if( $updateSavedCsr ){
                                        $savingLogs = sprintf( 'Token holder Ref(%s) updated saving to delivered', $getCurrentMember->reference );
                                        create_cip_logs_entery( $user_id, 'wallet_saving_deposit', '','sm', $savingLogs, true  );


                                        $duplicateRowData = array(
                                            'reference'                 =>  $getTokenHolderDatabyRef->reference.'-i',
                                            'eth_address'               =>  $getTokenHolderDatabyRef->eth_address,
                                            'occurs_times'              =>  $getTokenHolderDatabyRef->occurs_times,
                                            'csr_amount_initial'        =>  round( $interest_amount, 2 ),
                                            'csramount_by_ethaddress'   =>  $getTokenHolderDatabyRef->csramount_by_ethaddress,
                                            'csr_amount_issued'         =>  round( $interest_amount, 2 ),
                                            'amount_due'                =>  0,
                                            'username'                  =>  $getTokenHolderDatabyRef->username,
                                            'csramount_byusername'      =>  $getTokenHolderDatabyRef->csramount_byusername,
                                            'occurs_times_user'         =>  $getTokenHolderDatabyRef->occurs_times_user,
                                            'first_name'                =>  $getTokenHolderDatabyRef->first_name,
                                            'last_name'                 =>  $getTokenHolderDatabyRef->last_name,
                                            'redemption_date'           =>  $getTokenHolderDatabyRef->redemption_date,
                                            'claim_date'                =>  $getTokenHolderDatabyRef->claim_date,
                                            'email'                     =>  $getTokenHolderDatabyRef->email,
                                            '_user_status'              =>  $getTokenHolderDatabyRef->_user_status,
                                            'kyc_status'                =>  $getTokenHolderDatabyRef->kyc_status,
                                            'pool_ref'                  =>  $getTokenHolderDatabyRef->pool_ref,
                                            'approvedkyc'               =>  $getTokenHolderDatabyRef->approvedkyc,
                                            'corp_approved'             =>  'Delivered',
                                            'notes_external'            =>  '| Saved CSR interest |',
                                            'notes_internal'            =>  $getTokenHolderDatabyRef->notes_internal,
                                            'position'                  =>  $getTokenHolderDatabyRef->position,
                                            'text_1'                    =>  $getTokenHolderDatabyRef->text_1,
                                            'text_2'                    =>  $getTokenHolderDatabyRef->text_2,
                                            'text_3'                    =>  $getTokenHolderDatabyRef->text_3,
                                            'text_4'                    =>  $getTokenHolderDatabyRef->text_4,
                                            'text_5'                    =>  $getTokenHolderDatabyRef->text_5,
                                            'text_6'                    =>  $getTokenHolderDatabyRef->text_6,
                                            'text_7'                    =>  $getTokenHolderDatabyRef->text_7,
                                            'text_8'                    =>  $getTokenHolderDatabyRef->text_8,
                                            'text_9'                    =>  $getTokenHolderDatabyRef->text_9,
                                            'text_10'                   =>  $getTokenHolderDatabyRef->text_10,
                                            'date_1'                    =>  date_i18n('d/m/Y'),
                                            'date_2'                    =>  $getTokenHolderDatabyRef->date_2,
                                            'date_3'                    =>  $getTokenHolderDatabyRef->date_3,
                                            'date_4'                    =>  $getTokenHolderDatabyRef->date_4,
                                            'date_5'                    =>  $getTokenHolderDatabyRef->date_5,
                                            'date_6'                    =>  $getTokenHolderDatabyRef->date_6,
                                            'date_7'                    =>  $getTokenHolderDatabyRef->date_7,
                                            'date_8'                    =>  $getTokenHolderDatabyRef->date_8,
                                            'date_9'                    =>  $getTokenHolderDatabyRef->date_9,
                                            'date_10'                   =>  $getTokenHolderDatabyRef->date_10,
                                            'int_1'                     =>  $getTokenHolderDatabyRef->int_1,
                                            'int_2'                     =>  $getTokenHolderDatabyRef->int_2,
                                            'int_3'                     =>  $getTokenHolderDatabyRef->int_3,
                                            'int_4'                     =>  $getTokenHolderDatabyRef->int_4,
                                            'int_5'                     =>  $getTokenHolderDatabyRef->int_5,
                                            'int_6'                     =>  $getTokenHolderDatabyRef->int_6,
                                            'int_7'                     =>  $getTokenHolderDatabyRef->int_7,
                                            'int_8'                     =>  $getTokenHolderDatabyRef->int_8,
                                            'int_9'                     =>  $getTokenHolderDatabyRef->int_9,
                                            'int_10'                    =>  $getTokenHolderDatabyRef->int_10,
                                            'note_1'                    =>  $getTokenHolderDatabyRef->note_1,
                                            'note_2'                    =>  $getTokenHolderDatabyRef->note_2,
                                            'note_3'                    =>  $getTokenHolderDatabyRef->note_3,
                                            'note_4'                    =>  $getTokenHolderDatabyRef->note_4,
                                            'note_5'                    =>  $getTokenHolderDatabyRef->note_5,
                                            'note_6'                    =>  $getTokenHolderDatabyRef->note_6,
                                            'note_7'                    =>  $getTokenHolderDatabyRef->note_7,
                                            'note_8'                    =>  $note_8,
                                            'note_9'                    =>  $getTokenHolderDatabyRef->note_9,
                                            'note_10'                   =>  $getTokenHolderDatabyRef->note_10,
                                            'saved_amount'              =>  $getTokenHolderDatabyRef->saved_amount,
                                            'saving_date'               =>  $getTokenHolderDatabyRef->saving_date,
                                            'saving_start_date'         =>  $getTokenHolderDatabyRef->saving_start_date,
                                            'saving_interest'           =>  $getTokenHolderDatabyRef->saving_interest,
                                            'saving_periods'            =>  $getTokenHolderDatabyRef->saving_periods,
                                            'saving_state'              =>  $getTokenHolderDatabyRef->saving_state,
                                            'sign_verify'               =>  $getTokenHolderDatabyRef->sign_verify,
                                            'transhash'                 =>  $getTokenHolderDatabyRef->transhash,
                                            'contract_address'          =>  $getTokenHolderDatabyRef->contract_address,
                                            'receiver_address'          =>  $getTokenHolderDatabyRef->receiver_address,
                                            'last_update'               =>  $getTokenHolderDatabyRef->last_update
                                        );
                                        $insertDuplicate = $wpdb->insert( $tableTokenHolder, $duplicateRowData );

                                        if( $insertDuplicate ){
                                            $savingLogs = sprintf( 'Saving interest added Ref(%s)', $getTokenHolderDatabyRef->reference.'-i' );
                                            create_cip_logs_entery( $user_id, 'wallet_saving_deposit', '','sm', $savingLogs, true  );
                                        }else{
                                            $savingLogs = sprintf( 'Error at adding saving interest Ref(%s): %s', $getTokenHolderDatabyRef->reference.'-i', $wpdb->last_error );
                                            create_cip_logs_entery( $user_id, 'wallet_saving_deposit', '','sm', $savingLogs, true  );
                                        }
                                        

                                    }else{
                                        $savingLogs = sprintf( 'Error at updating token holder Ref(%s) saving to delivered: %s', $getCurrentMember->reference, $wpdb->last_error );
                                        create_cip_logs_entery( $user_id, 'wallet_saving_deposit', '','sm', $savingLogs, true  );
                                    }

                                }else{
                                    $savingLogs = sprintf( 'Error at updating token holder Ref(%s) saving to delivered: %s', $getCurrentMember->reference, 'No reference found in tokan holder data' );
                                    create_cip_logs_entery( $user_id, 'wallet_saving_deposit', '','sm', $savingLogs, true  );
                                }

                                update_option( 'saving_delivery_batch_id', $deliveryBatchId );

							}
						}
					}
					$out = array( "error" => 0,'msg' => __('CSR Savings Paid',CIP_TXTDOMAIN) );
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_savings_active_to_matured_script','cip_savings_active_to_matured_script_cb');
add_action('wp_ajax_nopriv_savings_active_to_matured_script','cip_savings_active_to_matured_script_cb');
function cip_savings_active_to_matured_script_cb(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableCsrSavings = $wpdb->prefix.'csr_savings';
	if( isset( $_GET['cronmicro'] ) && $_GET['cronmicro'] === md5( '_2024CipSavingsActiveMatureCip2024_' ) ){
		$matureDate = date( 'd/m/Y' );
		$getMaturingSavings = $wpdb->get_results( "SELECT `id`,`reference`,`username`,`email`,`saved_amount`,`saving_start_date`,`saving_end_date` FROM $tableCsrSavings WHERE 1 AND `saving_end_date`='". $matureDate ."' AND `status`='active'" );
		
        if( $getMaturingSavings ){
            foreach( $getMaturingSavings as $getMaturingSaving ){
                $update = $wpdb->query( $wpdb->prepare( "UPDATE $tableCsrSavings SET `status` = '%s' WHERE `id` = %d AND `saving_end_date`='%s' AND `status`='active'", 'matured', $getMaturingSaving->id, $matureDate ) );
                if( $update ){
                    $logs = sprintf( __('Saving is matured. reference: %s, username: %s, email: %s, saved_amount: %s, saving date: %s, mature date: %s', CIP_TXTDOMAIN), $getMaturingSaving->reference, $getMaturingSaving->username, $getMaturingSaving->email, $getMaturingSaving->saved_amount, $getMaturingSaving->saving_start_date, $getMaturingSaving->saving_end_date );
                    create_cip_logs_entery( 0, 'saving_matured', '','auto', $logs, true );
                }
            }
		}
        
	}
	exit;
}