<?php
add_shortcode('CSR-USER-WALLET','csr_user_balance_cb');
function csr_user_balance_cb(){
	$html = "";
	if( is_user_logged_in() ){

		global $wpdb;
        $transaction_history_table = $wpdb->prefix. 'csr_delivery_transaction_history';
		$user_id = get_current_user_id();

		$getCurrentMembers = $wpdb->get_results("SELECT * FROM $transaction_history_table WHERE 1 ORDER BY id DESC LIMIT 1");

		wp_enqueue_style( 'cip-css' );
		wp_enqueue_style( 'bs-table' );
		wp_enqueue_style( 'bs-sticky-header' );
		//wp_enqueue_style( 'bs-datepicker' );
		//wp_enqueue_style( 'daterangepicker-style' );
		wp_enqueue_script('bs-table');
		wp_enqueue_script('bs-sticky-header');
		wp_enqueue_script('bs-table-filter-control');
		wp_enqueue_script('tbl-ex-js');
		//wp_enqueue_script('jspdf');
		//wp_enqueue_script('pdf-autotable-js');
		//wp_enqueue_script('ex-js');
		//wp_enqueue_script('bs-datepicker');
		//wp_enqueue_style( 'select2' );
		//wp_enqueue_script('select2');
		//wp_enqueue_script('dr-moment');
		//wp_enqueue_script('daterangepicker-script');
        wp_enqueue_script('jszip');
		ob_start();


		?>
		<div class="container-fluid">
            <div class="table-responsive user_wallet_wrapper">
                <?php
                if( $getCurrentMembers ){
                    // Pending Withdrawals CSR
                    $pendingWithdrawals = $wpdb->get_row("SELECT
                            COUNT(*) AS no_of_requests,
                            SUM(withdrawal_amount) AS total_csr
                        FROM $transaction_history_table
                        WHERE type = 'withdrawal'
                        AND status IN (0, 1)
                        AND token = 'CSR'
                    ");
                    // Pending Withdrawals CSR25
                    $pendingWithdrawals_CSR25 = $wpdb->get_row("SELECT
                            COUNT(*) AS no_of_requests,
                            SUM(withdrawal_amount) AS total_csr
                        FROM $transaction_history_table
                        WHERE type = 'withdrawal'
                        AND status IN (0, 1)
                        AND token = 'CSR25'
                    ");


                    // Total Users Query CSR
                    $totalUsers = $wpdb->get_var("SELECT COUNT(DISTINCT email)
                        FROM $transaction_history_table
                        WHERE 1=1
                        AND token = 'CSR'
                    ");
                    // Total Users Query CSR25
                    $totalUsers_CSR25 = $wpdb->get_var("SELECT COUNT(DISTINCT email)
                        FROM $transaction_history_table
                        WHERE 1=1
                        AND token = 'CSR25'
                    ");

                    // Total CSR Query CSR
                    $totalCSR = $wpdb->get_var("SELECT
                        SUM(CASE
                            WHEN type = 'deposit' AND status = 0 THEN received_amount
                            ELSE 0
                        END) - SUM(CASE
                            WHEN type = 'withdrawal' AND status = 2 THEN withdrawal_amount
                            ELSE 0
                        END) AS total_csr
                    FROM $transaction_history_table
                    WHERE 1=1
                    AND token = 'CSR'
                    ");
                    // Total CSR Query CSR25
                    $totalCSR_CSR25 = $wpdb->get_var("SELECT
                        SUM(CASE
                            WHEN type = 'deposit' AND status = 0 THEN received_amount
                            ELSE 0
                        END) - SUM(CASE
                            WHEN type = 'withdrawal' AND status = 2 THEN withdrawal_amount
                            ELSE 0
                        END) AS total_csr
                    FROM $transaction_history_table
                    WHERE 1=1
                    AND token = 'CSR25'
                    ");

                    // Available CSR Query CSR
                    $availableCSR = $wpdb->get_var("SELECT
                        SUM(CASE
                            WHEN type = 'deposit' AND status = 0 THEN received_amount
                            ELSE 0
                        END) - SUM(CASE
                            WHEN type = 'withdrawal' AND status IN (0, 1, 2) THEN withdrawal_amount
                            ELSE 0
                        END) AS available_csr
                        FROM $transaction_history_table
                        WHERE 1=1
                        AND token = 'CSR'
                    ");
                    // Available CSR Query CSR25
                    $availableCSR_CSR25 = $wpdb->get_var("SELECT
                        SUM(CASE
                            WHEN type = 'deposit' AND status = 0 THEN received_amount
                            ELSE 0
                        END) - SUM(CASE
                            WHEN type = 'withdrawal' AND status IN (0, 1, 2) THEN withdrawal_amount
                            ELSE 0
                        END) AS available_csr
                        FROM $transaction_history_table
                        WHERE 1=1
                        AND token = 'CSR25'
                    ");


                    ?>
                     <div class="csr_filter">
                        <button class="btn btn-secondary filter-button token_csr csr_filter_selected" data-token="CSR">CSR</button>
                        <button class="btn btn-secondary filter-button token_csr_25" data-token="CSR25">CSR25</button>
                    </div>
                        <!-- Only CSR data -->
                    <div class="data_csr">
                        <div class="custom-table-container">
                            <table class="custom-table ">
                                <thead>
                                    <tr>
                                        <th></th>
                                        <th>Total</th>
                                        <th>Requested withdrawals</th>
                                        <th>Available</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><b>Users</b></td>
                                        <td><?php echo number_format($totalUsers); ?></td>
                                        <td><?php echo number_format($pendingWithdrawals->no_of_requests); ?></td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td><b>CSR</b></td>
                                        <td><?php echo number_format($totalCSR, 2); ?></td>
                                        <td><?php echo number_format($pendingWithdrawals->total_csr, 2); ?></td>
                                        <td><?php echo number_format($availableCSR, 2); ?></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                        <!-- Only CSR25 data -->
                    <div class="data_csr25">
                        <div class="custom-table-container">
                            <table class="custom-table ">
                                <thead>
                                    <tr>
                                        <th></th>
                                        <th>Total</th>
                                        <th>Requested withdrawals</th>
                                        <th>Available</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><b>Users</b></td>
                                        <td><?php echo number_format($totalUsers_CSR25); ?></td>
                                        <td><?php echo number_format($pendingWithdrawals_CSR25->no_of_requests); ?></td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td><b>CSR25</b></td>
                                        <td><?php echo number_format($totalCSR_CSR25, 2); ?></td>
                                        <td><?php echo number_format($pendingWithdrawals_CSR25->total_csr, 2); ?></td>
                                        <td><?php echo number_format($availableCSR_CSR25, 2); ?></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>



                    </div>



                    <!-- <button type="button" class="btn btn-primary user_wallet_export" title="Download"><i class="fa fa-download"></i></button> -->

                    <table id="user_wallet_table" class="user_wallet" data-search-time-out="800" 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="true" data-show-columns-toggle-all="true" data-show-export="false" data-click-to-select="true" class="table table-bordered" data-side-pagination="server" data-pagination="true" data-page-list="[10, 20, 50, 100]">
                        <thead>
                            <tr>
                                <th data-field="username" data-sortable="false" data-filter-control="input" class="username"><?php _e('Username',CIP_TXTDOMAIN); ?></th>
                                <th data-field="email" data-sortable="false" data-filter-control="input" class="email"><?php _e('Email',CIP_TXTDOMAIN); ?></th>
                                <th data-field="total_balance" data-sortable="false"  data-filter-control="input" class="total_balance"><?php _e('Total CSR',CIP_TXTDOMAIN); ?></th>
                                <th data-field="withdrawal_request" data-sortable="false" data-filter-control="input" class="withdrawal_request"><?php _e('Requested withdrawals',CIP_TXTDOMAIN); ?></th>
                                <th data-field="total_available_balance" data-sortable="false" data-filter-control="input" class="total_available_balance"><?php _e('Available CSR',CIP_TXTDOMAIN); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>

                <?php }else{ ?>
                <h2><?php _e('No results found',CIP_TXTDOMAIN); ?></h2>
                <?php } ?>
            </div>
	    </div>
	    <?php
	}
	$html .= ob_get_clean();
	return $html;
}

add_action('wp_ajax_user_wallet_loader','cip_user_wallet_loader_cb');
function cip_user_wallet_loader_cb(){
    global $wpdb;
    $token = 'CSR';
	$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
    $token = $_POST['token'];
    $limit = isset($_POST['limit']) ? $_POST['limit'] : 10;
    $offset = isset($_POST['offset']) ? $_POST['offset'] : 0;
    $orderby = isset($_POST['sort']) ? $_POST['sort'] : 'email';
    $order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';

    $whereFilterQry = "";
    $havingFilterQry = "";

    $filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
    $isNumericColumn = array( 'withdrawal_request', 'total_balance', 'total_available_balance' );

    if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'email' || $filterKey == 'username' ){
				$whereFilterQry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
				if( str_contains($filterData, '-') ){ //between
					$filterDataMinMax = explode('-', $filterData);
					$havingFilterQry .= " 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
                    //die('1');
					$havingFilterQry .= " AND `$filterKey` $filterData";
				}else{
                    //die('2');
					$havingFilterQry .= " AND `$filterKey` " . $filterData . "";
				}
			}
		}
	}

    // echo $filterKey;
    //total items
    $total_items = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*)
        FROM (
            SELECT
                email,
                username,
                SUM(CASE
                    WHEN type = 'withdrawal' AND status IN (0, 1) THEN withdrawal_amount
                    ELSE 0
                END) AS withdrawal_request,
                SUM(CASE
                    WHEN type = 'deposit' AND status = 0 THEN received_amount
                    ELSE 0
                END) - SUM(CASE
                    WHEN type = 'withdrawal' AND status = 2 THEN withdrawal_amount
                    ELSE 0
                END) AS total_balance,
                SUM(CASE
                    WHEN type = 'deposit' AND status = 0 THEN received_amount
                    ELSE 0
                END) - SUM(CASE
                    WHEN type = 'withdrawal' AND status IN (0, 1, 2) THEN withdrawal_amount
                    ELSE 0
                END) AS total_available_balance
            FROM
                $tableTransactionHistory
            WHERE
                1 $whereFilterQry
                AND token = '$token'
            GROUP BY
                email
            HAVING
               1 $havingFilterQry
        ) AS filtered_results;
    "));

    //main query
    $getResults = $wpdb->get_results("SELECT
        email,
        username,
        SUM(CASE
            WHEN type = 'withdrawal' AND status IN (0, 1) THEN withdrawal_amount
            ELSE 0
        END) AS withdrawal_request,
        GREATEST(
            SUM(CASE
                WHEN type = 'deposit' AND status = 0 THEN received_amount
                ELSE 0
            END) - SUM(CASE
                WHEN type = 'withdrawal' AND status = 2 THEN withdrawal_amount
                ELSE 0
            END),
            0
        ) AS total_balance,
        GREATEST(
            SUM(CASE
                WHEN type = 'deposit' AND status = 0 THEN received_amount
                ELSE 0
            END) - SUM(CASE
                WHEN type = 'withdrawal' AND status IN (0, 1, 2) THEN withdrawal_amount
                ELSE 0
            END),
            0
        ) AS total_available_balance
        FROM
            $tableTransactionHistory
        WHERE
            1 $whereFilterQry
            AND token = '$token'
        GROUP BY
            email
        HAVING
            1 $havingFilterQry
        ORDER BY
            `$orderby` $order
        LIMIT
            $limit OFFSET $offset
    ");

    $rows = array();

    if( $getResults ){
        $sno= $_REQUEST['offset'] + 1;
        foreach( $getResults as $getResult ){
            $row = array();
            $columnsArr = array(
				'email'					    =>	__('email', CIP_TXTDOMAIN),
				'username'				    =>	__('username', CIP_TXTDOMAIN),
				'withdrawal_request'	    =>	__('withdrawal_request', CIP_TXTDOMAIN),
				'total_balance'				=>	__('total_balance', CIP_TXTDOMAIN),
				'total_available_balance'   =>	__('total_available_balance', CIP_TXTDOMAIN),
			);
            foreach( $columnsArr as $columnKey => $columnsVal ){
                $columnsDataVal = $getResult->$columnKey;

                if( in_array( $columnKey, $isNumericColumn ) ){
                    $columnsDataVal = number_format( $columnsDataVal );
                }

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

        if($filterKey != '' && $filterData != '' ){
            $current_user_id = get_current_user_id();
            $user_info = get_userdata($current_user_id);
            // Get ID and Email
            $user_id = $user_info->ID;
            $user_email = $user_info->user_email;

            if($filterKey == 'withdrawal_request'){
                $column_search = 'Requested withdrawals';
            }else if($filterKey == 'total_balance'){
                $column_search = 'Total CSR';
            }else if ($filterKey == 'total_available_balance'){
                $column_search = 'Available CSR';
            }else if ($filterKey == 'username'){
                $column_search = 'Username';
            }else if ($filterKey == 'email'){
                $column_search = 'Email';
            }
            $message =sprintf( __('SA %s search for %s %s at %s', CIP_TXTDOMAIN), $user_email, $column_search, $filterData, date_i18n('d/m/Y H:i A') );
            create_cip_logs_entery($current_user_id, 'user wallet', '','sm',  $message, true );
        }
    }
    $out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
	);
	echo wp_json_encode( $out );
	exit;
}

//Export user wallet data to CSV
// add_action('wp_ajax_export_user_wallet', 'export_user_wallet');
function export_user_wallet(){
    global $wpdb;

    $token = 'CSR';
	$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
    $token = $_POST['token'];
    $limit = isset($_POST['limit']) ? $_POST['limit'] : 10;
    $offset = isset($_POST['offset']) ? $_POST['offset'] : 0;
    $orderby = isset($_POST['sort']) ? $_POST['sort'] : 'email';
    $order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';

    $whereFilterQry = "";
    $havingFilterQry = "";

    $filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
    $isNumericColumn = array( 'withdrawal_request', 'total_balance', 'total_available_balance' );

    if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'email' || $filterKey == 'username' ){
				$whereFilterQry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
				if( str_contains($filterData, '-') ){ //between
					$filterDataMinMax = explode('-', $filterData);
					$havingFilterQry .= " 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
                    //die('1');
					$havingFilterQry .= " AND `$filterKey` $filterData";
				}else{
                    //die('2');
					$havingFilterQry .= " AND `$filterKey` " . $filterData . "";
				}
			}
		}
	}

    //main query
    $getTHsData = $wpdb->get_results("SELECT
        email,
        username,
        SUM(CASE
            WHEN type = 'withdrawal' AND status IN (0, 1) THEN withdrawal_amount
            ELSE 0
        END) AS withdrawal_request,
        GREATEST(
            SUM(CASE
                WHEN type = 'deposit' AND status = 0 THEN received_amount
                ELSE 0
            END) - SUM(CASE
                WHEN type = 'withdrawal' AND status = 2 THEN withdrawal_amount
                ELSE 0
            END),
            0
        ) AS total_balance,
        GREATEST(
            SUM(CASE
                WHEN type = 'deposit' AND status = 0 THEN received_amount
                ELSE 0
            END) - SUM(CASE
                WHEN type = 'withdrawal' AND status IN (0, 1, 2) THEN withdrawal_amount
                ELSE 0
            END),
            0
        ) AS total_available_balance
        FROM
            $tableTransactionHistory
        WHERE
            1 $whereFilterQry
            AND token = '$token'
        GROUP BY
            email
        HAVING
            1 $havingFilterQry
        ORDER BY
            `$orderby` $order
    ");

    $exportFile = fopen('php://memory', 'w');
	$columnHeader = array( 'username','email','total_balance','withdrawal_request','total_available_balance');
    fputcsv($exportFile, $columnHeader);
    if( $getTHsData ){
		foreach( $getTHsData as $getTHData ){
			$redemption_date_formatted = "";
			if( $getTHData->redemption_date ){
				$formattedRDate = DateTime::createFromFormat( 'd/m/Y', $getTHData->redemption_date );
				if( $formattedRDate ){
					$redemption_date_formatted = $formattedRDate->format('d/m/Y');
				}
			}
			$claim_date_formatted = "";
			if( $getTHData->claim_date ){
				$formattedCDate = DateTime::createFromFormat( 'd/m/Y', $getTHData->claim_date );
				if( $formattedCDate ){
					$claim_date_formatted = $formattedCDate->format('d/m/Y');
				}
			}
			$rowData = array( $getTHData->username, $getTHData->email, $getTHData->total_balance, $getTHData->withdrawal_request, $getTHData->total_available_balance);
			fputcsv($exportFile, $rowData);
			$excelRow++;
		}
	}
    $current_user = wp_get_current_user();
	$logs = sprintf( __('User wallet data is exported by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
	create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
	fseek($exportFile, 0);
	$file_name = 'UserWallet-'.date_i18n('d-m-Y H-i-s');
	header('content-type:application/csv;charset=UTF-8');
	header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
	fpassthru($exportFile);
	fclose($exportFile);
	exit;
}

add_action('wp_footer','csr_user_wallet_script');
function csr_user_wallet_script(){
    $user_wallet_url = add_query_arg( [
		'action'	=>	'user_wallet_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
    ?>

    <script>
        jQuery(document).ready(function($){
            if( $('#user_wallet_table').length > 0 ){
                var user_wallet_url = "<?php echo $user_wallet_url ?>";
                var $tableUserwallet = $('#user_wallet_table');
                var params = {};
                var isRequestInProgress = false;
                var token = 'CSR';
                var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

                $('.filter-button').on('click', function () {
                    token = $(this).data('token');
                    $('.filter-button').removeClass('csr_filter_selected');
                    $(this).addClass('csr_filter_selected');
                    if(token == 'CSR'){
                        $('.data_csr').show();
                        $('.data_csr25').hide();
                        $('.total_balance .th-inner').text('Total CSR');
                        $('.total_available_balance .th-inner').text('Available CSR');
                    }else{
                        $('.data_csr').hide();
                        $('.data_csr25').show();
                        $('.total_balance .th-inner').text('Total CSR25');
                        $('.total_available_balance .th-inner').text('Available CSR25');
                    }
                    $('#user_wallet_table').bootstrapTable('refresh');
                });

                $(document).on('click', '.user_wallet_export', function() {
                    const table = $('#user_wallet_table');
                    const options = table.bootstrapTable('getOptions');
                    const filterValues = options.valuesFilterControl;
                    var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
                    $.blockUI(block_config);
                    var appliedFilters = {}
                    if (filterValues) {
                        appliedFilters = Object.fromEntries(
                            Object.entries(filterValues)
                            .filter(([key, value]) => value.value !== undefined && value.value !== '')
                            .map(([key, value]) => {
                                return [value.field, value.value];
                            })
                        );
                    }
                    $.ajax({
                        method: "POST",
                        url: cipscript.ajax_url,
                        data: { action: "export_user_wallet" ,
                            'columnfilter': JSON.stringify(appliedFilters),
                            token : token,
                        },
                        success: async function (response) {

                            var today = new Date();
                            var date = today.getDate() + "-" + (today.getMonth() + 1) + "-" + today.getFullYear();
                            var time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds();

                            var fileName = "User wallet " + date + " " + time + ".csv";
                            var zipFileName = "User wallet " + date + " " + time + ".zip";

                            var csvData = response;
                            var zip = new JSZip();

                            zip.file(fileName, csvData);
                            zip.generateAsync({ type: "blob" }).then(function (content) {
                                var downloadLink = document.createElement("a");
                                var url = URL.createObjectURL(content);

                                downloadLink.href = url;
                                downloadLink.download = zipFileName;

                                document.body.appendChild(downloadLink);
                                downloadLink.click();
                                document.body.removeChild(downloadLink);

                                // Unblock UI
                                $.unblockUI();
                            }).catch(function (error) {
                                console.error("Error generating ZIP:", error);
                                $.unblockUI();
                            });
                        },
                        error: function () {
                            $.unblockUI();
                        }
                    });
                });

                $tableUserwallet.bootstrapTable({
                    method: 'post',
                    contentType: 'application/x-www-form-urlencoded',
                    url: user_wallet_url,
                    filterControl: true,
                    //showFooter: true, // Enable the footer

                    queryParams: function (p) {
                        if (isRequestInProgress) {
                            return false; // Prevent new request if one is already in progress
                        }

                        isRequestInProgress = true; // Mark request as in progress
                        params = p.filter;
                        return {
                            columnfilter: p.filter,
                            limit: p.limit,
                            offset: p.offset,
                            sort: p.sort,
                            order: p.order,
                            token : token,
                        };

                    },
                    stickyHeader: false,
                    onSort: function(name, order) {
                        $.blockUI( block_config );
                    },
                    onFilter: function(filter) {
                        $.blockUI( block_config );
                    },
                    onLoadSuccess: function(response) {
                    $.unblockUI();
                    isRequestInProgress = false; // Reset the request flag
                    if (response.rows.length == 0) {
                        $tableUserwallet.find('tbody').html('<tr><td colspan="5" class="text-center">No matching records found</td></tr>');
                    }
                },
                    onSearch: function(search) {
                        // Show loader during search
                        $.blockUI( block_config );
                    },
                    onPostBody: function() {
                        $.unblockUI();
                    },
                });

            }

            // Show value textbox on dropdown change
            $('.user_wallet_filter_modal_wrapper select[name="filter_condition_type"]').on('change', function () {
                const operator = $(this).val();
                const formId = $(this).closest('form').attr('id');
                console.log(formId);

                if (operator !== 'none') {
                    $('#'+formId).find('input[name="filter_condition_value"]').show(); // Show value input
                } else {
                    $('#'+formId).find('input[name="filter_condition_value"]').hide(); // Hide value input
                    $('#'+formId).find('input[name="filter_condition_value"]').val(''); // Clear the input field
                }
            });

            // Handle filter application
            $('.user_wallet_filter_modal_wrapper .filter_user_wallet_ok').on('click', function (e) {
                e.preventDefault(); // Prevent form default submission
                var formId = $(this).closest('form').attr('id').replace('filter_by_', '').trim();
                const operator = $('#' + formId + '#filter-operator').val();
                const value = $('#' + formId + '#filter-value').val();
                const column = currentColumn; // Get the column being filtered

                // if (operator === 'none') {
                //     alert('Please select a valid operator!');
                //     return;
                // }

                // if (!value) {
                //     alert('Please enter a value to filter!');
                //     return;
                // }

                // Prepare data to send to the server

                $('#user_wallet_table').bootstrapTable('refresh');

                // Uncomment this to send AJAX request
                // $.ajax({
                //     url: cipscript.ajax_url, // WordPress global AJAX URL
                //     type: 'POST',
                //     data: data,
                //     success: function (response) {
                //         console.log('Filter applied:', response);
                //     },
                //     error: function (xhr, status, error) {
                //         console.error('Error applying filter:', error);
                //     },
                // });

                // Close the popup
                $('#'+formId+'UserWalletFilterModal').modal('hide');
            });
        });
    </script>

    <style>
        tr[data-index="10"] td {
            font-weight: bold;
        }
        body .balance_report_wrapper .filter_user_wallet_ok {
            padding: 10px 20px !important;
            border: 1px solid #572181 !important;
        }
        form#filter_by_total_balance .filter_user_wallet_ok {
            padding: 6px 20px !important;
            border: 1px solid #572181 !important;
        }
        .user_wallet_wrapper p {
            margin-bottom: 5px;
        }
        .info_box_pending,
        .info_box_total {
            margin-bottom: 15px;
        }

        .csr_summary_wrapper {
            width: 100%;
            background-color: hsla(0,0%,50.2%,.0705882353);
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            font-family: Montserrat, Sans-serif;
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
        }

        .csr_summary_header h3 {
            font-size: 24px;
            color: #333;
            margin-bottom: 10px;
        }

        .csr_summary_info {
            display: flex;
            justify-content: space-between;
        }

        .info_item {
            display: flex;
            justify-content: space-between;
            width: 45%;
        }
        .information .info_item {
            display: flex;
            justify-content: space-between;
            width: 30%;
        }

        .info_label {
            font-weight: bold;
            color: #555;
        }

        .info_value {
            font-size: 16px;
            color: #333;
            text-align: right;
        }

        .csr_summary_actions {
            text-align: center;
        }
        .csr_summary_header {
            margin-bottom: 20px;
        }
        .total_csr .info_value, .total_user .info_value, .numb_req .info_value{
            border-right: 3px solid #dee2e6;
            padding-right: 10%;
        }
        .csr_filter_selected{
            font-weight: bold;
            font-size: 18px;
        }

        .data_csr25{
            display: none;
        }
        .csr_filter {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
        }

        .filter-button {
            text-align: center;
        }
        .filter-button {
            color: #fff;
            font-family: "Montserrat", Sans-serif;
            background-image: none !important;
            background-color: #572181 !important;
            background-color: #572181 !important;
            border-color: #572181 !important;
        }
        .data_csr, .data_csr25{
            font-family: "Montserrat", Sans-serif;
        }



        .custom-table-container {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 20px auto;
        }

        .custom-table {
            border-collapse: collapse;
            width: 80%;
            max-width: 600px;
            text-align: center;
        }

        .custom-table th,
        .custom-table td {
            border: 1px solid #dee2e6;
            padding: 10px;
            font-size: 16px;
        }

        .custom-table th {
            background-color: #f4f4f4;
            font-weight: bold;
        }

        button.btn.btn-primary.user_wallet_export{
            position: absolute;
            right: 4%;
            padding: 11px !important;
            margin-top: 10px;
        }

    </style>
    <?php
}