<?php
add_shortcode('CIP-AAWARD-REPORT','cip_award_report_cb');
function cip_award_report_cb(){
    $html = "";
	if( is_user_logged_in() ){
		global $wpdb;
		$tableName = $wpdb->prefix.'token_holder';
		$user_id = get_current_user_id();

		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="award-report-table-wrapper">

			<?php echo do_shortcode('[AWARDS-POOL-SUMMARY-REPORT]'); ?>
			<div class="award_report_filter_seleted"></div>
			<div class="custom_btn_wrapper_award_report">
				<button type="button" class="btn btn-primary award_report_advance_filter" title="Advance Filter"><i class="fa fa-filter"></i></button>
				<button type="button" class="btn btn-primary award_report_export" title="Download"><i class="fa fa-download"></i></button>
			</div>

            <table id="award_report_table" class="award_report_table" 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="false" 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]" data-response-handler="responseHandlerAwardReport">
                <thead>
                    <tr>
                        <th data-field="id" data-sortable="true" data-filter-control="input" class="id"><?php _e('Id',CIP_TXTDOMAIN); ?></th>
                        <th data-field="reference" data-sortable="true"  data-filter-control="input" class="reference"><?php _e('Reference',CIP_TXTDOMAIN); ?></th>
                        <th data-field="eth_address" data-sortable="true" data-filter-control="input" class="eth_address"><?php _e('CSR Wallet Address',CIP_TXTDOMAIN); ?></th>
                        <th data-field="csr_amount_initial" data-sortable="true"  data-filter-control="input" class="csr_amount_initial"><?php _e('CSR Initial Amount',CIP_TXTDOMAIN); ?></th>
                        <th data-field="csr_amount_issued" data-sortable="true" data-filter-control="input" class="csr_amount_issued"><?php _e('CSR Distributed',CIP_TXTDOMAIN); ?></th>
                        <th data-field="amount_due" data-sortable="true"  data-filter-control="input" class="amount_due"><?php _e('CSR Amount due',CIP_TXTDOMAIN); ?></th>
                        <th data-field="username" data-sortable="true" data-filter-control="input" class="username"><?php _e('Username',CIP_TXTDOMAIN); ?></th>
                        <th data-field="first_name" data-sortable="true"  data-filter-control="input" class="first_name"><?php _e('First Name',CIP_TXTDOMAIN); ?></th>
                        <th data-field="last_name" data-sortable="true" data-filter-control="input" class="last_name"><?php _e('Last Name',CIP_TXTDOMAIN); ?></th>
                        <th data-field="redemption_date" data-sortable="true"  data-filter-control="input" class="redemption_date"><?php _e('Redemption Date',CIP_TXTDOMAIN); ?></th>
                        <th data-field="claim_date" data-sortable="true"  data-filter-control="input" class="claim_date"><?php _e('Application Date',CIP_TXTDOMAIN); ?></th>
                        <th data-field="email" data-sortable="true"  data-filter-control="input" class="email"><?php _e('Email',CIP_TXTDOMAIN); ?></th>
                        <th data-field="pool_ref" data-sortable="true"  data-filter-control="input" class="pool_ref"><?php _e('Pool Reference',CIP_TXTDOMAIN); ?></th>
                        <th data-field="corp_approved" data-sortable="true"  data-filter-control="select" data-filter-data="var:filterCorpApprovedStatus" class="status"><?php _e('Status',CIP_TXTDOMAIN); ?></th>
                        <th data-field="notes_external" data-sortable="true"  data-filter-control="input" class="notes_external"><?php _e('Notes/Comments',CIP_TXTDOMAIN); ?></th>
                        <th data-field="notes_internal" data-sortable="true"  data-filter-control="input" class="notes_internal"><?php _e('Corp Notes/Comments',CIP_TXTDOMAIN); ?></th>
                        <th data-field="text_1" data-sortable="true"  data-filter-control="input" class="text_1"><?php _e('Original Position',CIP_TXTDOMAIN); ?></th>
                        <th data-field="text_2" data-sortable="true"  data-filter-control="input" class="text_2"><?php _e('Distribution Position',CIP_TXTDOMAIN); ?></th>
                        <th data-field="text_9" data-sortable="true"  data-filter-control="input" class="text_9"><?php _e('Source',CIP_TXTDOMAIN); ?></th>
						<th data-field="token"
							data-sortable="true"
							data-filter-control="select"
							data-filter-data="var:filterCoin"
							class="token">
							<?php _e('Token', CIP_TXTDOMAIN); ?>
						</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>

			<!-- Advance filter HTML -->
			<div class="modal fade" id="awardReportadvanceFilterModal" tabindex="-1" role="dialog" aria-labelledby="awardReportadvanceFilterModal" aria-hidden="true">
				<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
					<div class="modal-content">
						<div class="modal-body">
							<div class="modal-header p-3 d-flex justify-content-between align-self-center"><h3>Advance Filter</h3> <div class="d-flex justify-content-between align-self-center"><button type="button" class="btn btn-secondary award_filter_clear mr-2"><?php _e('Clean Filters', CIP_TXTDOMAIN); ?></button><button type="button" class="btn btn-secondary award_report_filter_ok"><?php _e('Apply Filters', CIP_TXTDOMAIN); ?></button><button type="button" class="close" data-dismiss="modal">×</button></div></div>
							<div class="form-group m-0">

								<div id="award_report_advancefilter" class="px-3">
									<div class="row">
										<?php
										global $defaultColumnsArr;
										$needColumns = array('pool_ref', 'corp_approved', 'amount_due','coin');
										$columnOrders = (array)get_option('cip_sm_column_order');
										$columnsLabelArr = (array)get_option('cip_sm_column_labels');
										$columnsArr = array();
										$i = 0;
										if( !empty( $columnOrders ) && is_array( $columnOrders ) ){
											foreach( $columnOrders as $columnOrder ){
												$columnsArr[$columnOrder] = $defaultColumnsArr[$columnOrder];
											}
										}
										if( empty( $columnsArr ) ){
											$columnsArr = $defaultColumnsArr;
										}
										?>
										<div class="col-12 col-lg-4 py-3  ">
											<?php
											foreach( $columnsArr as $columnKey => $columnLabel ){
												if( in_array( $columnKey, $needColumns ) ){
													$cLabel = ( !empty( $columnsLabelArr[ $columnKey ] ) ) ? $columnsLabelArr[ $columnKey ] : $columnLabel;
													?>
													<a href="javascript:void(0);" class="ad_filter_label bg-light d-flex justify-content-between align-items-center <?php echo ($i == 0) ? 'active' : '' ; ?>" advance-filter="accodian_<?php echo $columnKey; ?>"><div><?php echo $cLabel; ?></div><span class="filter-changed-indicator-award active_<?php echo $columnKey; ?>" style="display: none;">*</span><i class="fa fa-angle-right"></i></a>
													<?php
													$i++;
												}
											}
											?>
										</div>
										<div class="col-12 col-lg-8 py-3 ad_filter_body_container bg-light">
											<?php
												$i = 0;
												global $wpdb;
												$tableName = $wpdb->prefix.'token_holder';

												foreach( $columnsArr as $columnKey => $columnLabel ){
													if( in_array( $columnKey, $needColumns ) ){
													$cLabel = ( !empty( $columnsLabelArr[ $columnKey ] ) ) ? $columnsLabelArr[ $columnKey ] : $columnLabel;
													?>
													<div id="accodian_<?php echo $columnKey; ?>" class="ad_filter_body <?php echo ($i == 0) ? 'show' : '' ; ?>">
														<div class="form-group">
															<label for="<?php echo $columnKey; ?>" class="heading-ad-filter mr-sm-2"><?php echo $cLabel; ?></label>
															<?php if( $columnKey == 'pool_ref' || $columnKey == 'corp_approved'){ ?>
																<form class="filter_by_<?php echo $columnKey; ?>" name="filter_by_<?php echo $columnKey; ?>" id="filter_by_<?php echo $columnKey; ?>">
																	<select class="mb-2 mr-sm-2" name="<?php echo $columnKey; ?>[]" id="<?php echo $columnKey; ?>"  multiple>
																		<option></option>
																	</select>
																</form>

															<?php }elseif($columnKey == 'coin'){ ?>
																<form class="filter_by_<?php echo $columnKey; ?>" name="filter_by_<?php echo $columnKey; ?>" id="filter_by_<?php echo $columnKey; ?>">
																<select class="form-control" name="filter_condition_type" id="filter_condition_value">
																	<option value="none"><?php _e('None', CIP_TXTDOMAIN); ?></option>
																	<option value="CSR">CSR</option>
																	<option value="CSR25">CSR25</option>
																</select>

															</form>
													<?php }else{ ?>
															<form class="filter_by_<?php echo $columnKey; ?>" name="filter_by_<?php echo $columnKey; ?>" id="filter_by_<?php echo $columnKey; ?>">
																<div class="form-group">
																	<label for="filter_by_condition">Filter by condition</label>
																	<?php
																		if ($columnKey == 'amount_due') {
																	?>
																		<select class="form-control" name="filter_condition_type" id="filter_condition_value">
																			<option value="none"><?php _e('None', CIP_TXTDOMAIN); ?></option>
																			<option value="is_empty"><?php _e('Is Empty', CIP_TXTDOMAIN); ?></option>
																			<option value="is_not_empty"><?php _e('Is Not Empty', CIP_TXTDOMAIN); ?></option>
																			<option value="greater_than">></option>
																			<option value="greater_than_equal">>=</option>
																			<option value="less_than"><</option>
																			<option value="less_than_equal"><=</option>
																			<option value="equal_to">=</option>
																		</select>

																	<?php } ?>


																	<input type="text" class="form-control mt-2" name="filter_condition_value" id="filter_condition_value" placeholder="<?php _e('Value', CIP_TXTDOMAIN); ?>" style="display: none;" />
																</div>
															</form>
															<?php } ?>
														</div>
													</div>
													<?php
													$i++;
													}
												}
											?>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<!-- Advance filter END -->

        </div>
        <?php
    }

}

add_action('wp_ajax_award_report_loader','cip_award_report_loader_cb');
function cip_award_report_loader_cb(){
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$user_id = get_current_user_id();

	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';
	$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;

	$filter_qry = "";
	$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
	$filterBy = "";
	$filterByValue = "";
	if( !empty( $filterByConditions ) ){
		$filterBy = $filterByConditions['filter_condition_type'];
		$filterByValue = $filterByConditions['filter_condition_value'];
	}
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( $filterBy != 'none' ){
		$filters['notes_external'] = trim( $filterByValue );
	}

	//Pool reference
	$filterByConditionPool_ref = json_decode( stripslashes( $_REQUEST['filterByConditionPool_ref'] ), true );
	$filterByPoolRef = "";
	$filterByValuePoolRef = "";
	if( !empty( $filterByConditionPool_ref ) ){
		$filterByPoolRef = $filterByConditionsPoolRef['filter_condition_type'];$filterByValuePoolRef = $filterByConditionsPoolRef['filter_condition_value'];
	}

	//Corp approved / Status
	$filterByConditionCorp_approved = json_decode( stripslashes( $_REQUEST['filterByConditionCorp_approved'] ), true );
	$filterByCorp_approved = "";
	$filterByValueCorp_approved = "";
	if( !empty( $filterByConditionCorp_approved ) ){
		$filterByCorp_approved = $filterByConditionCorp_approved['filter_condition_type'];$filterByValueCorp_approved = $filterByConditionCorp_approved['filter_condition_value'];
	}

	//CSR Amount due
	$filterByConditionAmount_due = json_decode( stripslashes( $_REQUEST['filterByConditionAmount_due'] ), true );
	$amount_duefilterBy = "";
	$amount_duefilterByValue = "";
	if( !empty( $filterByConditionAmount_due ) ){
		$amount_duefilterBy = $filterByConditionAmount_due['filter_condition_type'];
		$amount_duefilterByValue = $filterByConditionAmount_due['filter_condition_value'];
	}

	//coin
	$filterByConditionCoin = json_decode( stripslashes( $_REQUEST['filter_by_coin'] ), true );
	$filterByCoin = "";
	$filterByValueCoin = "";
	if( !empty( $filterByConditionCoin ) ){
		$filterByCoin = $filterByConditionCoin['filter_condition_type'];
		$filterByValueCoin = $filterByConditionCoin['filter_condition_value'];
	}

	if( !empty($filterByConditionPool_ref['pool_ref']) ){
		$filters['pool_ref_filter'] = $filterByValuePoolRef;
	}
	if(!empty($filterByConditionCorp_approved['corp_approved'])){
		$filters['corp_approved_filter'] = $filterByValueCorp_approved;
	}
	if( $amount_duefilterBy != 'none' && $amount_duefilterBy != '' ){
		$filters['amount_due_filter'] = trim( $amount_duefilterByValue );
	}
	if( $filterByCoin != 'none' && $filterByCoin != '' ){
		$filters['coin_filter'] = trim( $filterByValueCoin );
	}
	// $filters['filterBy'] = $filterBy;
	// $filters['filterByValue'] = $filterByValue;

	$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
	$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date', 'saving_start_date');

	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else if( $filterKey == 'username' ){
				$filter_qry .= " AND `$filterKey` like '" . $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, '!=') || 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 if( $filterKey == 'notes_external' ){
				if( $filterBy != 'none' ){
					if( $filterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $filterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $filterBy == 'contains_text' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
					}else if( $filterBy == 'does_not_contains_text' ){
						$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
					}else if( $filterBy == 'starts_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
					}else if( $filterBy == 'ends_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
					}else if( $filterBy == 'is_exactly' ){
						$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
					}
				}
			}else if( $filterKey == 'pool_ref_filter' ){
				$filterKey = 'pool_ref';
				if( !empty($filterByConditionPool_ref['pool_ref']) ){
					$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterByConditionPool_ref['pool_ref']) . "')";
				}
			}else if( $filterKey == 'corp_approved_filter' ){
				if( !empty($filterByConditionCorp_approved['corp_approved']) ){
                    $filterKey = 'corp_approved';
					//die('++ crop');
					//print_r($filterByConditionCorp_approved['corp_approved']);
					$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterByConditionCorp_approved['corp_approved']) . "')";

				}
			}else if( $filterKey == 'amount_due_filter' ){
				$filterKey = 'amount_due';
				if( $amount_duefilterBy != 'none' && $amount_duefilterBy != ''){
					if( $amount_duefilterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $amount_duefilterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $amount_duefilterBy == 'greater_than' ){
						$filter_qry .= " AND `$filterKey` > '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'greater_than_equal' ){
						$filter_qry .= " AND `$filterKey` >= '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'less_than' ){
						$filter_qry .= " AND `$filterKey` < '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'less_than_equal' ){
						$filter_qry .= " AND `$filterKey` <= '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'equal_to' ){
						$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
					}
				}
			}else if( $filterKey == 'coin_filter' ){
				if( $filterByCoin != 'none' ){
					$filterKey = 'token';
					if( $filterByCoin == 'CSR' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterByCoin . "%'";
					}else if( $filterByCoin == 'CSR25' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterByCoin . "%'";
					}
				}
				// 237 - advance filter END
			}else{

				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
	}
	$total_items = $wpdb->get_var(
		"SELECT COUNT(id)
		FROM $tableName
		WHERE 1
		AND pool_ref IN ('C', 'E', 'F', 'H', 'J')
		$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 $tableName WHERE 1 AND pool_ref IN ('C', 'E', 'F', 'H', 'J')  $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");

	$columnHeader = array('reference', 'eth_address', 'csr_amount_initial', 'csr_amount_issued', 'amount_due', 'username', 'first_name', 'last_name', 'redemption_date', 'claim_date', 'email', 'pool_ref','corp_approved', 'notes_external', 'notes_internal', 'text_1', 'text_2', 'text_9','token');

	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			if( $columnHeader ){
				foreach( $columnHeader as $columnKey ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					if( in_array( $columnKey, $isNumericColumn ) && is_numeric( $columnsDataVal ) ){
						$columnsDataVal = number_format( $columnsDataVal );
					}else if( $columnKey == 'notes_internal' || $columnKey == 'notes_external' ){
                        $columnsDataVal = '<div class="width_length_20_hr">' . $columnsDataVal . '</div>';
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}

	$getAllAwardPoolRecords = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 AND pool_ref IN ('C', 'E', 'F', 'H', 'J')  $filter_qry");

	$poolRecords = array();
	$sum_of_csr_due = 0;
	if( $getAllAwardPoolRecords ){
		foreach( $getAllAwardPoolRecords as $getAllAwardPoolRecord ){
			$poolRecords[ $getAllAwardPoolRecord->reference ] = $getAllAwardPoolRecord->csr_amount_initial;
			$sum_of_csr_due += $getAllAwardPoolRecord->amount_due;
		}
	}

	$groupedAmounts = [];
	$allowedPrefixes = ['PNP', 'BNS', 'DIS'];
	if( $poolRecords ){
		foreach( $poolRecords as $record => $amount ){
			$prefix = substr($record, 0, 3);

			if (in_array($prefix, $allowedPrefixes)) {
				$adjustedRecord = substr($record, strpos($record, '-') + 1, 14);
			} else {
				$adjustedRecord = substr($record, 0, 14);
			}

			if (!isset($groupedAmounts[$adjustedRecord])) {
				$groupedAmounts[$adjustedRecord] = $amount;
			} else {
				$groupedAmounts[$adjustedRecord] = max($groupedAmounts[$adjustedRecord], $amount);
			}
		}
	}

	$uniqueGroupCount = count($groupedAmounts);
	$totalHighestAmounts = array_sum($groupedAmounts);


	// ===========================================================================START
	$holdRecords = [];
	$pendingRecords = [];
	$securityHoldRecords = [];
	$sum_of_csr_due_hold = 0;
	$sum_of_csr_due_pending = 0;
	$count_of_rows_hold = 0;
	$count_of_rows_pending = 0;

	if ($getAllAwardPoolRecords) {
		foreach ($getAllAwardPoolRecords as $getAllAwardPoolRecord) {
			$prefix = substr($getAllAwardPoolRecord->reference, 0, 3);

			// Adjust record for grouping
			if (in_array($prefix, ['PNP', 'BNS', 'DIS'])) {
				$adjustedRecord = substr($getAllAwardPoolRecord->reference, strpos($getAllAwardPoolRecord->reference, '-') + 1, 14);
			} else {
				$adjustedRecord = substr($getAllAwardPoolRecord->reference, 0, 14);
			}

			if ($getAllAwardPoolRecord->corp_approved === 'Hold') {
				if (!isset($holdRecords[$adjustedRecord])) {
					$holdRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$holdRecords[$adjustedRecord] = max($holdRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_hold += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_hold++;
			} elseif ($getAllAwardPoolRecord->corp_approved === 'Pending') {
				if (!isset($pendingRecords[$adjustedRecord])) {
					$pendingRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$pendingRecords[$adjustedRecord] = max($pendingRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_pending += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_pending++;
			}elseif ($getAllAwardPoolRecord->corp_approved === 'Security Hold') {
				if (!isset($securityHoldRecords[$adjustedRecord])) {
					$securityHoldRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$securityHoldRecords[$adjustedRecord] = max($securityHoldRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_security_hold += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_security_hold++;
			}elseif ($getAllAwardPoolRecord->corp_approved === 'Application received') {
				if (!isset($applicationReceivedRecords[$adjustedRecord])) {
					$applicationReceivedRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$applicationReceivedRecords[$adjustedRecord] = max($applicationReceivedRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_application_received += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_application_received++;
			}elseif ($getAllAwardPoolRecord->corp_approved === 'Delivered') {
				if (!isset($deliveredRecords[$adjustedRecord])) {
					$deliveredRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$deliveredRecords[$adjustedRecord] = max($deliveredRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_delivered += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_delivered++;
			}elseif ($getAllAwardPoolRecord->corp_approved === 'Deleted') {
				if (!isset($deletedRecords[$adjustedRecord])) {
					$deletedRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$deletedRecords[$adjustedRecord] = max($deletedRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_deleted += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_deleted++;
			}elseif ($getAllAwardPoolRecord->corp_approved === 'Under review') {
				if (!isset($underReviewRecords[$adjustedRecord])) {
					$underReviewRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$underReviewRecords[$adjustedRecord] = max($underReviewRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_under_review += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_under_review++;
			}elseif ($getAllAwardPoolRecord->corp_approved === 'Rejected') {
				if (!isset($rejectedRecords[$adjustedRecord])) {
					$rejectedRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$rejectedRecords[$adjustedRecord] = max($rejectedRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_rejected += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_rejected++;
			}elseif ($getAllAwardPoolRecord->corp_approved === 'Issued') {
				if (!isset($issuedRecords[$adjustedRecord])) {
					$issuedRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$issuedRecords[$adjustedRecord] = max($issuedRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_issued += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_issued++;
			}elseif ($getAllAwardPoolRecord->corp_approved === 'In Process') {
				if (!isset($inProcessRecords[$adjustedRecord])) {
					$inProcessRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$inProcessRecords[$adjustedRecord] = max($inProcessRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_inProcess += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_inProcess++;
			}elseif ($getAllAwardPoolRecord->corp_approved === 'Partially Delivered') {
				if (!isset($partiallydeliveredRecords[$adjustedRecord])) {
					$partiallydeliveredRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$partiallydeliveredRecords[$adjustedRecord] = max($partiallydeliveredRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_partially_delivered += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_partially_delivered++;
			}elseif ($getAllAwardPoolRecord->corp_approved === 'CSRnow member') {
				if (!isset($csrnowMemberRecords[$adjustedRecord])) {
					$csrnowMemberRecords[$adjustedRecord] = $getAllAwardPoolRecord->csr_amount_initial;
				} else {
					$csrnowMemberRecords[$adjustedRecord] = max($csrnowMemberRecords[$adjustedRecord], $getAllAwardPoolRecord->csr_amount_initial);
				}
				$sum_of_csr_due_csrnow_member += $getAllAwardPoolRecord->amount_due;
				$count_of_rows_csrnow_member++;
			}
		}
	}

	// Calculate totals for Hold
	$uniqueHoldGroupCount = count($holdRecords);
	$totalHoldHighestAmounts = array_sum($holdRecords);

	// Calculate totals for Pending
	$uniquePendingGroupCount = count($pendingRecords);
	$totalPendingHighestAmounts = array_sum($pendingRecords);

	// Calculate totals for Security Hold
	$uniqueSecurityHoldGroupCount = count($securityHoldRecords);
	$totalSecurityHoldHighestAmounts = array_sum($securityHoldRecords);

	// Calculate totals for Application received
	$uniqueApplicationReceivedGroupCount = count($applicationReceivedRecords);
	$totalApplicationReceivedHighestAmounts = array_sum($applicationReceivedRecords);

	// Calculate totals for Delivered
	$uniqueDeliveredGroupCount = count($deliveredRecords);
	$totalDeliveredHighestAmounts = array_sum($deliveredRecords);

	// Calculate totals for Deleted
	$uniqueDeletedGroupCount = count($deletedRecords);
	$totalDeletedHighestAmounts = array_sum($deletedRecords);

	// Calculate totals for Under review
	$uniqueUnderReviewGroupCount = count($underReviewRecords);
	$totalUnderReviewHighestAmounts = array_sum($underReviewRecords);

	// Calculate totals for Rejected
	$uniqueRejectedGroupCount = count($rejectedRecords);
	$totalRejectedHighestAmounts = array_sum($rejectedRecords);

	// Calculate totals for Issued
	$uniqueIssuedGroupCount = count($issuedRecords);
	$totalIssuedHighestAmounts = array_sum($issuedRecords);

	// Calculate totals for In Process
	$uniqueInProcessGroupCount = count($inProcessRecords);
	$totalInProcessHighestAmounts = array_sum($inProcessRecords);

	// Calculate totals for Partially Delivered
	$uniquePartiallyDeliveredGroupCount = count($partiallydeliveredRecords);
	$totalPartiallyDeliveredHighestAmounts = array_sum($partiallydeliveredRecords);

	// Calculate totals for CSRnow member
	$uniqueCSRnowMemberGroupCount = count($csrnowMemberRecords);
	$totalCSRnowMemberHighestAmounts = array_sum($csrnowMemberRecords);

	// Store Hold and Pending data in $holdData
	$holdData = array(
		'count_of_records' => number_format($uniqueHoldGroupCount),
		'count_of_rows'    => number_format($count_of_rows_hold),
		'sum_of_csr'       => number_format($totalHoldHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_hold)
	);
	$pendingData = array(
		'count_of_records' => number_format($uniquePendingGroupCount),
		'count_of_rows'    => number_format($count_of_rows_pending),
		'sum_of_csr'       => number_format($totalPendingHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_pending),
	);
	$securityHoldData = array(
		'count_of_records' => number_format($uniqueSecurityHoldGroupCount),
		'count_of_rows'    => number_format($count_of_rows_security_hold),
		'sum_of_csr'       => number_format($totalSecurityHoldHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_security_hold),
	);
	$applicationReceivedData = array(
		'count_of_records' => number_format($uniqueApplicationReceivedGroupCount),
		'count_of_rows'    => number_format($count_of_rows_application_received),
		'sum_of_csr'       => number_format($totalApplicationReceivedHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_application_received),
	);
	$deliveredData = array(
		'count_of_records' => number_format($uniqueDeliveredGroupCount),
		'count_of_rows'    => number_format($count_of_rows_delivered),
		'sum_of_csr'       => number_format($totalDeliveredHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_delivered),
	);
	$deletedData = array(
		'count_of_records' => number_format($uniqueDeletedGroupCount),
		'count_of_rows'    => number_format($count_of_rows_deleted),
		'sum_of_csr'       => number_format($totalDeletedHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_deleted),
	);
	$UnderReviewData = array(
		'count_of_records' => number_format($uniqueUnderReviewGroupCount),
		'count_of_rows'    => number_format($count_of_rows_under_review),
		'sum_of_csr'       => number_format($totalUnderReviewHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_under_review),
	);
	$rejectedData = array(
		'count_of_records' => number_format($uniqueRejectedGroupCount),
		'count_of_rows'    => number_format($count_of_rows_rejected),
		'sum_of_csr'       => number_format($totalRejectedHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_rejected),
	);
	$issuedData = array(
		'count_of_records' => number_format($uniqueIssuedGroupCount),
		'count_of_rows'    => number_format($count_of_rows_issued),
		'sum_of_csr'       => number_format($totalIssuedHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_issued),
	);
	$inProcessData = array(
		'count_of_records' => number_format($uniqueInProcessGroupCount),
		'count_of_rows'    => number_format($count_of_rows_inProcess),
		'sum_of_csr'       => number_format($totalInProcessHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_inProcess),
	);
	$partiallyDeliveredData = array(
		'count_of_records' => number_format($uniquePartiallyDeliveredGroupCount),
		'count_of_rows'    => number_format($count_of_rows_partially_delivered),
		'sum_of_csr'       => number_format($totalPartiallyDeliveredHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_partially_delivered),
	);
	$csrnowMemberData = array(
		'count_of_records' => number_format($uniqueCSRnowMemberGroupCount),
		'count_of_rows'    => number_format($count_of_rows_csrnow_member),
		'sum_of_csr'       => number_format($totalCSRnowMemberHighestAmounts),
		'sum_of_csr_due'   => number_format($sum_of_csr_due_csrnow_member),
	);
	// ============================================================================== END


	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows,
		'count_of_records'		=>	number_format( $uniqueGroupCount ),
		'count_of_rows'		=>	number_format( count( $getAllAwardPoolRecords ) ),
		'sum_of_csr'		=>	number_format( $totalHighestAmounts ),
		'sum_of_csr_due'		=>	number_format( $sum_of_csr_due ),
		'holdData'          => $holdData,
		'pendingData'          => $pendingData,
		'securityHoldData'          => $securityHoldData,
		'applicationReceivedData'          => $applicationReceivedData,
		'deliveredData'          => $deliveredData,
		'deletedData'          => $deletedData,
		'underReviewData'          => $UnderReviewData,
		'rejectedData'          => $rejectedData,
		'issuedData'          => $issuedData,
		'inProcessData'          => $inProcessData,
		'partiallyDeliveredData'          => $partiallyDeliveredData,
		'csrnowMemberData'          => $csrnowMemberData,


	);
	echo wp_json_encode( $out );
	exit;
}

add_action('wp_ajax_export_award_report', 'export_award_report');
function export_award_report(){

	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );

	$filter_qry = "";
	$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
	//Pool reference
	$filterByConditionPool_ref = json_decode( stripslashes( $_REQUEST['filterByConditionPool_ref'] ), true );
	$filterByPoolRef = "";
	$filterByValuePoolRef = "";
	if( !empty( $filterByConditionPool_ref ) ){
		$filterByPoolRef = $filterByConditionsPoolRef['filter_condition_type'];$filterByValuePoolRef = $filterByConditionsPoolRef['filter_condition_value'];
	}

	//Corp approved / Status
	$filterByConditionCorp_approved = json_decode( stripslashes( $_REQUEST['filterByConditionCorp_approved'] ), true );
	$filterByCorp_approved = "";
	$filterByValueCorp_approved = "";
	if( !empty( $filterByConditionCorp_approved ) ){
		$filterByCorp_approved = $filterByConditionCorp_approved['filter_condition_type'];$filterByValueCorp_approved = $filterByConditionCorp_approved['filter_condition_value'];
	}

	//CSR Amount due
	$filterByConditionAmount_due = json_decode( stripslashes( $_REQUEST['filterByConditionAmount_due'] ), true );
	$amount_duefilterBy = "";
	$amount_duefilterByValue = "";
	if( !empty( $filterByConditionAmount_due ) ){
		$amount_duefilterBy = $filterByConditionAmount_due['filter_condition_type'];
		$amount_duefilterByValue = $filterByConditionAmount_due['filter_condition_value'];
	}
	//coin
	$filterByConditionCoin = json_decode( stripslashes( $_REQUEST['filter_by_coin'] ), true );
	$filterByCoin = "";
	$filterByValueCoin = "";
	if( !empty( $filterByConditionCoin ) ){
		$filterByCoin = $filterByConditionCoin['filter_condition_type'];
		$filterByValueCoin = $filterByConditionCoin['filter_condition_value'];
	}

	if( !empty($filterByConditionPool_ref['pool_ref']) ){
		$filters['pool_ref_filter'] = $filterByValuePoolRef;
	}
	if(!empty($filterByConditionCorp_approved['corp_approved'])){
		$filters['corp_approved_filter'] = $filterByValueCorp_approved;
	}
	if( $amount_duefilterBy != 'none' && $amount_duefilterBy != '' ){
		$filters['amount_due_filter'] = trim( $amount_duefilterByValue );
	}
	if( $filterByCoin != 'none' && $filterByCoin != '' ){
		$filters['coin_filter'] = trim( $filterByValueCoin );
	}
	$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
	$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date', 'saving_start_date');


	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){

			if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			// 237 advance filter - add reference, email, notes_internal, notes_external,eth_address
			}else if( $filterKey == 'username' || $filterKey == 'reference' || $filterKey == 'email' || $filterKey == 'eth_address' ){
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}else if( $filterKey == 'notes_internal' || $filterKey == 'notes_external' ){
				$filter_qry .= " AND `$filterKey` like '%" . $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, '!=') || 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 if( $filterKey == 'notes_external' ){
				if( $filterBy != 'none' ){
					if( $filterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $filterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $filterBy == 'contains_text' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
					}else if( $filterBy == 'does_not_contains_text' ){
						$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
					}else if( $filterBy == 'starts_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
					}else if( $filterBy == 'ends_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
					}else if( $filterBy == 'is_exactly' ){
						$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
					}
				}
			}else if( $filterKey == 'pool_ref_filter' ){
				$filterKey = 'pool_ref';
				if( !empty($filterByConditionPool_ref['pool_ref']) ){
					$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterByConditionPool_ref['pool_ref']) . "')";
				}
			}else if( $filterKey == 'corp_approved_filter' ){
				if( !empty($filterByConditionCorp_approved['corp_approved']) ){
                    $filterKey = 'corp_approved';
					//die('++ crop');
					//print_r($filterByConditionCorp_approved['corp_approved']);
					$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterByConditionCorp_approved['corp_approved']) . "')";

				}
			}else if( $filterKey == 'amount_due_filter' ){
				$filterKey = 'amount_due';
				if( $amount_duefilterBy != 'none' && $amount_duefilterBy != ''){
					if( $amount_duefilterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $amount_duefilterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $amount_duefilterBy == 'greater_than' ){
						$filter_qry .= " AND `$filterKey` > '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'greater_than_equal' ){
						$filter_qry .= " AND `$filterKey` >= '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'less_than' ){
						$filter_qry .= " AND `$filterKey` < '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'less_than_equal' ){
						$filter_qry .= " AND `$filterKey` <= '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'equal_to' ){
						$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
					}
				}
			}else if( $filterKey == 'coin_filter' ){
				if( $filterByCoin != 'none' ){
					$filterKey = 'token';
					if( $filterByCoin == 'CSR' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterByCoin . "%'";
					}else if( $filterByCoin == 'CSR25' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterByCoin . "%'";
					}
				}
				// 237 - advance filter END
			}else{

				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
	}

	// echo $filter_qry;
	// die('+++');
	$needColumns = array('reference', 'username', 'email', 'eth_address', 'pool_ref', 'text_1', 'text_2', 'text_3', 'text_4', 'text_5', 'text_6', 'text_7', 'text_8', 'text_9', 'text_10', 'corp_approved');
	$columnOrders = (array)get_option('cip_sm_column_order');
	$columnsLabelArr = (array)get_option('cip_sm_column_labels');
	$columnsArr = array();
	if( !empty( $columnOrders ) && is_array( $columnOrders ) ){
		foreach( $columnOrders as $columnOrder ){
			if( in_array( $columnOrder, $needColumns ) ){
				$columnsArr[$columnOrder] = $defaultColumnsArr[$columnOrder];
			}
		}
	}
	if( empty( $columnsArr ) ){
		$columnsArr = $defaultColumnsArr;
	}
	global $wpdb;
	$sheetCounter = 0;

	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%d/%m/%Y')";
	}


    // Set the file name and headers for CSV download
    $file_name = 'AwardReport-' . date_i18n('d-m-Y H-i-s') . '.csv';
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $file_name . '"');
    header('Pragma: no-cache');
    header('Expires: 0');

    // Open the output stream for writing to the browser
    $output = fopen('php://output', 'w');

    // Column headers for the CSV
    $columnHeader = array('reference', 'eth_address', 'csr_amount_initial', 'csr_amount_issued', 'amount_due', 'username', 'first_name', 'last_name', 'redemption_date', 'claim_date', 'email', 'pool_ref','corp_approved', 'notes_external', 'notes_internal', 'text_1', 'text_2', 'text_9','token');
    fputcsv($output, $columnHeader);

    // Define the batch size
    $batch_size = 10000;
    $offset = 0;

    // Loop through and fetch data in batches, processing each batch
    while (true) {
        // Fetch a batch of records from the database
        // $getTHsData = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}token_holder LIMIT %d OFFSET %d", $batch_size, $offset));

		$getTHsData = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}token_holder WHERE 1 AND pool_ref IN ('C', 'E', 'F', 'H', 'J') $filter_qry LIMIT %d OFFSET %d",
				$batch_size,
				$offset
			)
		);

        // If no data is returned, break the loop
        if (empty($getTHsData)) {
            break;
        }

        // Process each row and output it to the CSV file
        foreach ($getTHsData as $getTHData) {
            // Format the dates if necessary
            $redemption_date_formatted = $getTHData->redemption_date ? DateTime::createFromFormat('d/m/Y', $getTHData->redemption_date)->format('d/m/Y') : '';
            $claim_date_formatted = $getTHData->claim_date ? DateTime::createFromFormat('d/m/Y', $getTHData->claim_date)->format('d/m/Y') : '';
            // Prepare the data row for the CSV
            $rowData = array(
                $getTHData->reference, $getTHData->eth_address, $getTHData->csr_amount_initial, $getTHData->csr_amount_issued, $getTHData->amount_due, $getTHData->username,
                $getTHData->first_name, $getTHData->last_name, $redemption_date_formatted, $claim_date_formatted, $getTHData->email, $getTHData->pool_ref,  $getTHData->corp_approved,
                $getTHData->notes_external, $getTHData->notes_internal, $getTHData->text_1, $getTHData->text_2, $getTHData->text_9,$getTHData->token
            );

            // Write the row to the CSV file
            fputcsv($output, $rowData);
        }

        // Increase the offset for the next batch
        $offset += $batch_size;
    }

    // Close the output stream after all data has been processed
    fclose($output);
    $current_user = wp_get_current_user();
    $logs = sprintf( __('Award report downloaded 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 );
    exit;

}
/**
 * Award report summary
 */
add_shortcode('AWARDS-POOL-SUMMARY-REPORT', 'awards_pool_summary_report_callback');
function awards_pool_summary_report_callback(){
	$html = "";
	ob_start();


	echo "<div class='award_summary'>";
	echo "<table id='award_summary_table' border='1' cellpadding='5' cellspacing='0' border-collapse: collapse;'>";
		echo "<thead>";
		echo "<tr>";
		echo "<th>Status</th>";
		echo "<th>Count of records</th>";
		echo "<th>Count of rows</th>";
		echo "<th>Sum of CSR Initial</th>";
		echo "<th>Sum of CSR Due</th>";
		echo "</tr>";
		echo "</thead>";
		echo "<tbody>";

		echo "<tr class='tr_status_hold'>";
		echo "<td class='status_hold'><b>Hold</b></td>";
		echo "<td class='count_of_records_hold'>-</td>";
		echo "<td class='count_of_rows_hold'>-</td>";
		echo "<td class='sum_of_csr_hold'>-</td>";
		echo "<td class='sum_of_csr_due_hold'>-</td>";
		echo "</tr>";

		echo "<tr class='tr_status_issued'>";
		echo "<td class='status_issued'><b>Issued</b></td>";
		echo "<td class='count_of_records_issued'>-</td>";
		echo "<td class='count_of_rows_issued'>-</td>";
		echo "<td class='sum_of_csr_issued'>-</td>";
		echo "<td class='sum_of_csr_due_issued'>-</td>";
		echo "</tr>";

		echo "<tr class='tr_status_security_hold'>";
		echo "<td class='status_security_hold'><b>Security Hold</b></td>";
		echo "<td class='count_of_records_security_hold'>-</td>";
		echo "<td class='count_of_rows_security_hold'>-</td>";
		echo "<td class='sum_of_csr_security_hold'>-</td>";
		echo "<td class='sum_of_csr_due_security_hold'>-</td>";
		echo "</tr>";

		echo "<tr class='tr_status_application_received'>";
		echo "<td class='status_application_received'><b>Application received</b></td>";
		echo "<td class='count_of_records_application_received'>-</td>";
		echo "<td class='count_of_rows_application_received'>-</td>";
		echo "<td class='sum_of_csr_application_received'>-</td>";
		echo "<td class='sum_of_csr_due_application_received'>-</td>";
		echo "</tr>";

		echo "<tr class='tr_status_delivered'>";
		echo "<td class='status_delivered'><b>Delivered</b></td>";
		echo "<td class='count_of_records_delivered'>-</td>";
		echo "<td class='count_of_rows_delivered'>-</td>";
		echo "<td class='sum_of_csr_delivered'>-</td>";
		echo "<td class='sum_of_csr_due_delivered'>-</td>";
		echo "</tr>";

		echo "<tr class='tr_status_deleted'>";
		echo "<td class='status_deleted'><b>Deleted</b></td>";
		echo "<td class='count_of_records_deleted'>-</td>";
		echo "<td class='count_of_rows_deleted'>-</td>";
		echo "<td class='sum_of_csr_deleted'>-</td>";
		echo "<td class='sum_of_csr_due_deleted'>-</td>";
		echo "</tr>";

		echo "<tr class='tr_status_under_review'>";
		echo "<td class='status_under_review'><b>Under review</b></td>";
		echo "<td class='count_of_records_under_review'>-</td>";
		echo "<td class='count_of_rows_under_review'>-</td>";
		echo "<td class='sum_of_csr_under_review'>-</td>";
		echo "<td class='sum_of_csr_due_under_review'>-</td>";
		echo "</tr>";

		echo "<tr class='tr_status_rejected'>";
		echo "<td class='status_rejected'><b>Rejected</b></td>";
		echo "<td class='count_of_records_rejected'>-</td>";
		echo "<td class='count_of_rows_rejected'>-</td>";
		echo "<td class='sum_of_csr_rejected'>-</td>";
		echo "<td class='sum_of_csr_due_rejected'>-</td>";
		echo "</tr>";

		echo "<tr class='tr_status_pending'>";
		echo "<td class='status_pending'><b>Pending</b></td>";
		echo "<td class='count_of_records_pending'>-</td>";
		echo "<td class='count_of_rows_pending'>-</td>";
		echo "<td class='sum_of_csr_pending'>-</td>";
		echo "<td class='sum_of_csr_due_pending'>-</td>";
		echo "</tr>";

		echo "<tr class='tr_status_in_process'>";
		echo "<td class='status_in_process'><b>In Process</b></td>";
		echo "<td class='count_of_records_in_process'>-</td>";
		echo "<td class='count_of_rows_in_process'>-</td>";
		echo "<td class='sum_of_csr_in_process'>-</td>";
		echo "<td class='sum_of_csr_due_in_process'>-</td>";
		echo "</tr>";

		echo "<tr class='tr_status_partially_delivered'>";
		echo "<td class='status_partially_delivered'><b>Partially Delivered</b></td>";
		echo "<td class='count_of_records_partially_delivered'>-</td>";
		echo "<td class='count_of_rows_partially_delivered'>-</td>";
		echo "<td class='sum_of_csr_partially_delivered'>-</td>";
		echo "<td class='sum_of_csr_due_partially_delivered'>-</td>";
		echo "</tr>";

		echo "<tr class='tr_status_csrnow_member'>";
		echo "<td class='status_csrnow_member'><b>CSRnow member</b></td>";
		echo "<td class='count_of_records_csrnow_member'>-</td>";
		echo "<td class='count_of_rows_csrnow_member'>-</td>";
		echo "<td class='sum_of_csr_csrnow_member'>-</td>";
		echo "<td class='sum_of_csr_due_csrnow_member'>-</td>";
		echo "</tr>";

		echo "</tbody>";
	echo "</table>";
	echo "</div>";

	$html .= ob_get_clean();
	return $html;
}
add_action('wp_ajax_get_holder_options_data_award_report_select2_options', 'get_holder_options_data_award_report_select2_options');
function get_holder_options_data_award_report_select2_options() {
    global $wpdb;
    $table = $wpdb->prefix.'token_holder';     // Table name
    $column = sanitize_text_field($_GET['column']);    // Column name
    $search = sanitize_text_field($_GET['search']);    // Search value

    // Validate inputs
    if (empty($table) || empty($column) || empty($search)) {
        wp_send_json_error(['message' => 'Invalid parameters.'], 400);
    }

    // Build the SQL query dynamically (sanitize table and column names)
    $table = esc_sql($table);
    $column = esc_sql($column);
    $like = $wpdb->esc_like($search) . '%';

    // Execute query to fetch results
    // $results = $wpdb->get_col($wpdb->prepare(
    //     "SELECT DISTINCT `$column` FROM `$table` WHERE `$column` LIKE %s LIMIT 100",
    //     $like
    // ));

	$results = $wpdb->get_col($wpdb->prepare(
		"SELECT DISTINCT `$column` FROM `$table` WHERE `$column` LIKE %s AND pool_ref IN ('C', 'E', 'F', 'H', 'J') LIMIT 100",
		$like
	));

    // Send results back to the frontend
    if (!empty($results)) {
		// $formatted_results = array_map(function($result) {
		// 	return [
		// 		'id' => $result->text,
		// 		'text' => $result->text
		// 	];
		// }, $results);
		// wp_send_json_success($formatted_results);

        wp_send_json_success($results);
    } else {
        wp_send_json_error(['message' => 'No results found.'], 404);
    }
}
add_action('wp_head','filter_dec');
function filter_dec(){
	$filterCoinOptions = array(
		'CSR'=>'CSR',
		'CSR25'=>'CSR25'
	);
	$filterCorpApprovedOptions = array(
		'Hold' => 'Hold',
		'Issued' => 'Issued',
		'Security Hold' => 'Security Hold',
		'Application received' => 'Application received',
		'Delivered' => 'Delivered',
		'Deleted' => 'Deleted',
		'Under review' => 'Under review',
		'Rejected' => 'Rejected',
		'Pending' => 'Pending',
		'In Process' => 'In Process',
		'Partially Delivered' => 'Partially Delivered',
		'CSRnow member' => 'CSRnow member',
	);
	$CoinJson = json_encode($filterCoinOptions);
	$CorpApprovedJson = json_encode($filterCorpApprovedOptions);
	?><script>var filterCoin = <?php echo $CoinJson; ?>; var filterCorpApprovedStatus = <?php echo $CorpApprovedJson; ?>;</script><?php
}

add_action('wp_footer','cip_award_report_script');
function cip_award_report_script(){

	$award_report_url = add_query_arg( [
		'action'	=>	'award_report_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );

    ?>
    <script>
        jQuery(document).ready(function($){


			$(document).on('click', '.award_report_advance_filter', function() {
				$('#awardReportadvanceFilterModal').modal({ backdrop: 'static', keyboard: false });
			});

            $(document).on('click', '.award_report_export', function() {
                const table = $('#award_report_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 = {}
				var filterByConditionPool_ref = {};
				var filterByConditionCorp_approved = {};
				var filterByConditionAmount_due = {};
				var filterByConditionCoin = {};

				filterByConditionPool_ref = convertFormToJSON( '#awardReportadvanceFilterModal #filter_by_pool_ref' );
                filterByConditionCorp_approved = convertFormToJSON( '#awardReportadvanceFilterModal #filter_by_corp_approved' );
				filterByConditionAmount_due = convertFormToJSON( '#awardReportadvanceFilterModal #filter_by_amount_due' );
				filterByConditionCoin = convertFormToJSON( '#filter_by_coin' );

                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_award_report" ,
                        'columnfilter': JSON.stringify(appliedFilters),
						'filterByConditionPool_ref': filterByConditionPool_ref,
						'filterByConditionCorp_approved': filterByConditionCorp_approved,
						'filterByConditionAmount_due': filterByConditionAmount_due,
						'filter_by_coin': filterByConditionCoin
                    },
                    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 = "Award Report " + date + " " + time + ".csv";
                        var zipFileName = "Award Report " + 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();
                    }
                });
            });

            if( $('#award_report_table').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 award_report_url = "<?php echo $award_report_url ?>";
                var $tableAwardReport = $('#award_report_table');
                var params = {};
				var filterByConditionPool_ref = {};
				var filterByConditionCorp_approved = {};
				var filterByConditionAmount_due = {};
				var filterByConditionCoin = {};

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

                    queryParams: function (p) {
                        params = p.filter;
						filterByConditionPool_ref = convertFormToJSON( '#awardReportadvanceFilterModal #filter_by_pool_ref' );
                    	filterByConditionCorp_approved = convertFormToJSON( '#awardReportadvanceFilterModal #filter_by_corp_approved' );
						filterByConditionAmount_due = convertFormToJSON( '#awardReportadvanceFilterModal #filter_by_amount_due' );
						filterByConditionCoin = convertFormToJSON( '#filter_by_coin' );
                        return {
                            columnfilter: p.filter,
                            limit: p.limit,
                            offset: p.offset,
                            sort: p.sort,
                            order: p.order,
							'filterByConditionPool_ref': filterByConditionPool_ref,
                        	'filterByConditionCorp_approved': filterByConditionCorp_approved,
							'filterByConditionAmount_due': filterByConditionAmount_due,
							'filter_by_coin': filterByConditionCoin
                        };

                    },
                    stickyHeader: false,
                    // responseHandler: function(response) {
                    //     console.log(response.filters)
                    //     response.rows.push(response.coloum_totals);
                    //     return response;
                    // },
                    onSort: function(name, order) {
                        // Show loader when sorting starts
                        $.blockUI( block_config );
                    },
                    onFilter: function(filter) {
                        // Show loader when filtering starts
                        $.blockUI( block_config );
                    },
                    onLoadSuccess: function(response) {
						if(response.total != 0){
							$('#award_summary_table').show();
						}else{
							$('#award_summary_table').hide();
						}
                        $.unblockUI();
                    },
                    onSearch: function(search) {
                        // Show loader during search
                        $.blockUI( block_config );
                    },
                    onPostBody: function() {
                        // Optionally hide loader here if needed
                        $.unblockUI();
                    },
                });


				let dateFormat = 'DD/MM/YYYY';
				var $redemption_date = $('input.bootstrap-table-filter-control-redemption_date[type="search"]');
				var $claim_date = $('input.bootstrap-table-filter-control-claim_date[type="search"]');
				var $date_1 = $('input.bootstrap-table-filter-control-date_1[type="search"]');
				var $date_2 = $('input.bootstrap-table-filter-control-date_2[type="search"]');
				var $date_3 = $('input.bootstrap-table-filter-control-date_3[type="search"]');
				var $date_4 = $('input.bootstrap-table-filter-control-date_4[type="search"]');
				var $date_5 = $('input.bootstrap-table-filter-control-date_5[type="search"]');
				var $date_6 = $('input.bootstrap-table-filter-control-date_6[type="search"]');
				var $date_7 = $('input.bootstrap-table-filter-control-date_7[type="search"]');
				var $date_8 = $('input.bootstrap-table-filter-control-date_8[type="search"]');
				var $date_9 = $('input.bootstrap-table-filter-control-date_9[type="search"]');
				var $date_10 = $('input.bootstrap-table-filter-control-date_10[type="search"]');
				var $saving_date = $('input.bootstrap-table-filter-control-saving_date[type="search"]');
				var $saving_start_date = $('input.bootstrap-table-filter-control-saving_start_date[type="search"]');
				var $notes_external = $('input.bootstrap-table-filter-control-notes_external[type="search"]');

				if( $redemption_date.length > 0 ){
					$redemption_date.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$redemption_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$redemption_date.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$redemption_date.trigger(eve);
					});
					$redemption_date.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$redemption_date.trigger(eve);
					});
				}
				if( $claim_date.length > 0 ){
					$claim_date.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$claim_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$claim_date.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$claim_date.trigger(eve);
					});
					$claim_date.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$claim_date.trigger(eve);
					});
				}
				if( $date_1.length > 0 ){
					$date_1.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$date_1.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$date_1.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_1.trigger(eve);
					});
					$date_1.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_1.trigger(eve);
					});
				}
				if( $date_2.length > 0 ){
					$date_2.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$date_2.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$date_2.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_2.trigger(eve);
					});
					$date_2.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_2.trigger(eve);
					});
				}
				if( $date_3.length > 0 ){
					$date_3.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$date_3.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$date_3.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_3.trigger(eve);
					});
					$date_3.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_3.trigger(eve);
					});
				}
				if( $date_4.length > 0 ){
					$date_4.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$date_4.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$date_4.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_4.trigger(eve);
					});
					$date_4.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_4.trigger(eve);
					});
				}
				if( $date_5.length > 0 ){
					$date_5.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$date_5.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$date_5.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_5.trigger(eve);
					});
					$date_5.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_5.trigger(eve);
					});
				}
				if( $date_6.length > 0 ){
					$date_6.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$date_6.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$date_6.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_6.trigger(eve);
					});
					$date_6.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_6.trigger(eve);
					});
				}
				if( $date_7.length > 0 ){
					$date_7.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$date_7.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$date_7.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_7.trigger(eve);
					});
					$date_7.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_7.trigger(eve);
					});
				}
				if( $date_8.length > 0 ){
					$date_8.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$date_8.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$date_8.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_8.trigger(eve);
					});
					$date_8.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_8.trigger(eve);
					});
				}
				if( $date_9.length > 0 ){
					$date_9.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$date_9.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$date_9.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_9.trigger(eve);
					});
					$date_9.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_9.trigger(eve);
					});
				}
				if( $date_10.length > 0 ){
					$date_10.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$date_10.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$date_10.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_10.trigger(eve);
					});
					$date_10.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$date_10.trigger(eve);
					});
				}
				if( $saving_date.length > 0 ){
					$saving_date.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$saving_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$saving_date.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$saving_date.trigger(eve);
					});
					$saving_date.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$saving_date.trigger(eve);
					});
				}
				if( $saving_start_date.length > 0 ){
					$saving_start_date.daterangepicker({
							autoUpdateInput: false,
							locale: {
								format: dateFormat,
								separator: ' - ',
								firstDay: 2
							},
							opens: 'left',
							cancelButtonClasses: 'btn-default cancelButton_daterangepicker'
						},
						function(start, end) {
							startDate = start.format(dateFormat);
							endDate = end.format(dateFormat);
							let dates = [ startDate, endDate ];
							$saving_start_date.val(start.format(dateFormat) + ' - ' + end.format(dateFormat));
						}
					);
					$saving_start_date.on('apply.daterangepicker', function(ev, picker) {
						$(this).val(picker.startDate.format(dateFormat) + ' - ' + picker.endDate.format(dateFormat));
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$saving_start_date.trigger(eve);
					});
					$saving_start_date.on('cancel.daterangepicker', function(ev, picker) {
						$(this).val('');
						let eve = jQuery.Event("keyup");
						eve.which = 13
						eve.keyCode = 13
						$saving_start_date.trigger(eve);
					});
				}

            }



        });
		function responseHandlerAwardReport(res){
            if( res.count_of_records ){
				$('.count_of_records').html( res.count_of_records );
			}
			if( res.count_of_rows ){
				$('.count_of_rows').html( res.count_of_rows );
			}
			if( res.sum_of_csr ){
				$('.sum_of_csr').html( res.sum_of_csr );
			}
			if( res.sum_of_csr_due ){
				$('.sum_of_csr_due').html( res.sum_of_csr_due );
			}

			//hold
			if( res?.holdData?.count_of_records !=0){
				$('.count_of_records_hold').html(res?.holdData?.count_of_records);
			}else{
				$('.count_of_records_hold').html('-');
			}
			if( res?.holdData?.count_of_rows !=0 ){
				$('.count_of_rows_hold').html( res?.holdData?.count_of_rows);
			}else{
				$('.count_of_rows_hold').html('-');
			}
			if( res?.holdData?.sum_of_csr !=0){
				$('.sum_of_csr_hold').html(res?.holdData?.sum_of_csr);
			}else{
				$('.sum_of_csr_hold').html('-');
			}
			if( res?.holdData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_hold').html(res?.holdData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_hold').html('-');
			}
			if(res?.holdData?.count_of_records ==0 && res?.holdData?.count_of_rows ==0 && res?.holdData?.sum_of_csr ==0 && res?.holdData?.sum_of_csr_due ==0 ){
				$('.tr_status_hold').hide();
			}else{
				$('.tr_status_hold').show();
			}

			//Pending
			if( res?.pendingData?.count_of_records !=0){
				$('.count_of_records_pending').html(res?.pendingData?.count_of_records);
			}else{
				$('.count_of_records_pending').html('-');
			}
			if( res?.pendingData?.count_of_rows !=0 ){
				$('.count_of_rows_pending').html( res?.pendingData?.count_of_rows);
			}else{
				$('.count_of_rows_pending').html('-');
			}
			if( res?.pendingData?.sum_of_csr !=0){
				$('.sum_of_csr_pending').html(res?.pendingData?.sum_of_csr);
			}else{
				$('.sum_of_csr_pending').html('-');
			}
			if( res?.pendingData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_pending').html(res?.pendingData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_pending').html('-');
			}
			if(res?.pendingData?.count_of_records ==0 && res?.pendingData?.count_of_rows ==0 && res?.pendingData?.sum_of_csr ==0 && res?.pendingData?.sum_of_csr_due ==0 ){
				$('.tr_status_pending').hide();
			}else{
				$('.tr_status_pending').show();
			}

			//Security Hold
			if( res?.securityHoldData?.count_of_records !=0){
				$('.count_of_records_security_hold').html(res?.securityHoldData?.count_of_records);
			}else{
				$('.count_of_records_security_hold').html('-');
			}
			if( res?.securityHoldData?.count_of_rows !=0 ){
				$('.count_of_rows_security_hold').html( res?.securityHoldData?.count_of_rows);
			}else{
				$('.count_of_rows_security_hold').html('-');
			}
			if( res?.securityHoldData?.sum_of_csr !=0){
				$('.sum_of_csr_security_hold').html(res?.securityHoldData?.sum_of_csr);
			}else{
				$('.sum_of_csr_security_hold').html('-');
			}
			if( res?.securityHoldData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_security_hold').html(res?.securityHoldData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_security_hold').html('-');
			}
			if(res?.securityHoldData?.count_of_records ==0 && res?.securityHoldData?.count_of_rows ==0 && res?.securityHoldData?.sum_of_csr ==0 && res?.securityHoldData?.sum_of_csr_due ==0 ){
				$('.tr_status_security_hold').hide();
			}else{
				$('.tr_status_security_hold').show();
			}

			//Application Received
			if( res?.applicationReceivedData?.count_of_records !=0){
				$('.count_of_records_application_received').html(res?.applicationReceivedData?.count_of_records );
			}else{
				$('.count_of_records_application_received').html('-');
			}
			if( res?.applicationReceivedData?.count_of_rows !=0 ){
				$('.count_of_rows_application_received').html( res?.applicationReceivedData?.count_of_rows);
			}else{
				$('.count_of_rows_application_received').html( '-' );
			}
			if( res?.applicationReceivedData?.sum_of_csr !=0){
				$('.sum_of_csr_application_received').html(res?.applicationReceivedData?.sum_of_csr);
			}else{
				$('.sum_of_csr_application_received').html('-');
			}
			if( res?.applicationReceivedData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_application_received').html(res?.applicationReceivedData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_application_received').html('-');
			}
			if(res?.applicationReceivedData?.count_of_records ==0 && res?.applicationReceivedData?.count_of_rows ==0 && res?.applicationReceivedData?.sum_of_csr ==0 && res?.applicationReceivedData?.sum_of_csr_due ==0 ){
				$('.tr_status_application_received').hide();
			}else{
				$('.tr_status_application_received').show();
			}

			 //issued
			if( res?.issuedData?.count_of_records !=0){
				$('.count_of_records_issued').html(res?.issuedData?.count_of_records );
			}else{
				$('.count_of_records_issued').html('-');
			}
			if( res?.issuedData?.count_of_rows !=0 ){
				$('.count_of_rows_issued').html( res?.issuedData?.count_of_rows );
			}else{
				$('.count_of_rows_issued').html( '-' );
			}
			if( res?.issuedData?.sum_of_csr !=0){
				$('.sum_of_csr_issued').html(res?.issuedData?.sum_of_csr);
			}else{
				$('.sum_of_csr_issued').html('-');
			}
			if( res?.issuedData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_issued').html(res?.issuedData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_issued').html('-');
			}
			if(res?.issuedData?.count_of_records ==0 && res?.issuedData?.count_of_rows ==0 && res?.issuedData?.sum_of_csr ==0 && res?.issuedData?.sum_of_csr_due ==0 ){
				$('.tr_status_issued').hide();
			}else{
				$('.tr_status_issued').show();
			}

			//deliveredData
			if( res?.deliveredData?.count_of_records !=0){
				$('.count_of_records_delivered').html(res?.deliveredData?.count_of_records );
			}else{
				$('.count_of_records_delivered').html('-');
			}
			if( res?.deliveredData?.count_of_rows !=0 ){
				$('.count_of_rows_delivered').html( res?.deliveredData?.count_of_rows );
			}else{
				$('.count_of_rows_delivered').html( '-' );
			}
			if( res?.deliveredData?.sum_of_csr !=0){
				$('.sum_of_csr_delivered').html(res?.deliveredData?.sum_of_csr);
			}else{
				$('.sum_of_csr_delivered').html('-');
			}
			if( res?.deliveredData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_delivered').html(res?.deliveredData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_delivered').html('-');
			}
			if(res?.deliveredData?.count_of_records ==0 && res?.deliveredData?.count_of_rows ==0 && res?.deliveredData?.sum_of_csr ==0 && res?.deliveredData?.sum_of_csr_due ==0 ){
				$('.tr_status_delivered').hide();
			}else{
				$('.tr_status_delivered').show();
			}

			//deletedData
			if( res?.deletedData?.count_of_records !=0){
				$('.count_of_records_deleted').html(res?.deletedData?.count_of_records);
			}else{
				$('.count_of_records_deleted').html('-');
			}
			if( res?.deletedData?.count_of_rows !=0 ){
				$('.count_of_rows_deleted').html( res?.deletedData?.count_of_rows);
			}else{
				$('.count_of_rows_deleted').html( '-' );
			}
			if( res?.deletedData?.sum_of_csr !=0){
				$('.sum_of_csr_deleted').html(res?.deletedData?.sum_of_csr);
			}else{
				$('.sum_of_csr_deleted').html('-');
			}
			if( res?.deletedData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_deleted').html(res?.deletedData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_deleted').html('-');
			}
			if(res?.deletedData?.count_of_records ==0 && res?.deletedData?.count_of_rows ==0 && res?.deletedData?.sum_of_csr ==0 && res?.deletedData?.sum_of_csr_due ==0 ){
				$('.tr_status_deleted').hide();
			}else{
				$('.tr_status_deleted').show();
			}

			//underReviewData
			if( res?.underReviewData?.count_of_records !=0){
				$('.count_of_records_under_review').html(res?.underReviewData?.count_of_records );
			}else{
				$('.count_of_records_under_review').html('-');
			}
			if( res?.underReviewData?.count_of_rows !=0 ){
				$('.count_of_rows_under_review').html( res?.underReviewData?.count_of_rows);
			}else{
				$('.count_of_rows_under_review').html( '-' );
			}
			if( res?.underReviewData?.sum_of_csr !=0){
				$('.sum_of_csr_under_review').html(res?.underReviewData?.sum_of_csr);
			}else{
				$('.sum_of_csr_under_review').html('-');
			}
			if( res?.underReviewData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_under_review').html(res?.underReviewData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_under_review').html('-');
			}
			if(res?.underReviewData?.count_of_records ==0 && res?.underReviewData?.count_of_rows ==0 && res?.underReviewData?.sum_of_csr ==0 && res?.underReviewData?.sum_of_csr_due ==0 ){
				$('.tr_status_under_review').hide();
			}else{
				$('.tr_status_under_review').show();
			}

			//rejectedData
			if( res?.rejectedData?.count_of_records !=0){
				$('.count_of_records_rejected').html(res?.rejectedData?.count_of_records );
			}else{
				$('.count_of_records_rejected').html('-');
			}
			if( res?.rejectedData?.count_of_rows !=0 ){
				$('.count_of_rows_rejected').html( res?.rejectedData?.count_of_rows);
			}else{
				$('.count_of_rows_rejected').html( '-' );
			}
			if( res?.rejectedData?.sum_of_csr !=0){
				$('.sum_of_csr_rejected').html(res?.rejectedData?.sum_of_csr);
			}else{
				$('.sum_of_csr_rejected').html('-');
			}
			if( res?.rejectedData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_rejected').html(res?.rejectedData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_rejected').html('-');
			}
			if(res?.rejectedData?.count_of_records ==0 && res?.rejectedData?.count_of_rows ==0 && res?.rejectedData?.sum_of_csr ==0 && res?.rejectedData?.sum_of_csr_due ==0 ){
				$('.tr_status_rejected').hide();
			}else{
				$('.tr_status_rejected').show();
			}

			//inProcessData
			if( res?.inProcessData?.count_of_records !=0){
				$('.count_of_records_in_process').html(res?.inProcessData?.count_of_records );
			}else{
				$('.count_of_records_in_process').html('-');
			}
			if( res?.inProcessData?.count_of_rows !=0 ){
				$('.count_of_rows_in_process').html( res?.inProcessData?.count_of_rows);
			}else{
				$('.count_of_rows_in_process').html( '-' );
			}
			if( res?.inProcessData?.sum_of_csr !=0){
				$('.sum_of_csr_in_process').html(res?.inProcessData?.sum_of_csr);
			}else{
				$('.sum_of_csr_in_process').html('-');
			}
			if( res?.inProcessData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_in_process').html(res?.inProcessData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_in_process').html('-');
			}
			if(res?.inProcessData?.count_of_records ==0 && res?.inProcessData?.count_of_rows ==0 && res?.inProcessData?.sum_of_csr ==0 && res?.inProcessData?.sum_of_csr_due ==0 ){
				$('.tr_status_in_process').hide();
			}else{
				$('.tr_status_in_process').show();
			}

			 //partiallyDeliveredData
			if( res?.partiallyDeliveredData?.count_of_records !=0){
				$('.count_of_records_partially_delivered').html(res?.partiallyDeliveredData?.count_of_records );
			}else{
				$('.count_of_records_partially_delivered').html('-');
			}
			if( res?.partiallyDeliveredData?.count_of_rows !=0){
				$('.count_of_rows_partially_delivered').html( res?.partiallyDeliveredData?.count_of_rows);
			}else{
				$('.count_of_rows_partially_delivered').html( '-' );
			}
			if( res?.partiallyDeliveredData?.sum_of_csr !=0){
				$('.sum_of_csr_partially_delivered').html(res?.partiallyDeliveredData?.sum_of_csr);
			}else{
				$('.sum_of_csr_partially_delivered').html('-');
			}
			if( res?.partiallyDeliveredData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_partially_delivered').html(res?.partiallyDeliveredData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_partially_delivered').html('-');
			}
			if(res?.partiallyDeliveredData?.count_of_records ==0 && res?.partiallyDeliveredData?.count_of_rows ==0 && res?.partiallyDeliveredData?.sum_of_csr ==0 && res?.partiallyDeliveredData?.sum_of_csr_due ==0 ){
				$('.tr_status_partially_delivered').hide();
			}else{
				$('.tr_status_partially_delivered').show();
			}

			 //csrnowMemberData
			if( res?.csrnowMemberData?.count_of_records !=0){
				$('.count_of_records_csrnow_member').html(res?.csrnowMemberData?.count_of_records );
			}else{
				$('.count_of_records_csrnow_member').html('-');
			}
			if( res?.csrnowMemberData?.count_of_rows !=0 ){
				$('.count_of_rows_csrnow_member').html( res?.csrnowMemberData?.count_of_rows);
			}else{
				$('.count_of_rows_csrnow_member').html( '-' );
			}
			if( res?.csrnowMemberData?.sum_of_csr !=0){
				$('.sum_of_csr_csrnow_member').html(res?.csrnowMemberData?.sum_of_csr);
			}else{
				$('.sum_of_csr_csrnow_member').html('-');
			}
			if( res?.csrnowMemberData?.sum_of_csr_due !=0){
				$('.sum_of_csr_due_partially_delivered').html(res?.csrnowMemberData?.sum_of_csr_due);
			}else{
				$('.sum_of_csr_due_partially_delivered').html('-');
			}
			if(res?.csrnowMemberData?.count_of_records ==0 && res?.csrnowMemberData?.count_of_rows ==0 && res?.csrnowMemberData?.sum_of_csr ==0 && res?.csrnowMemberData?.sum_of_csr_due ==0 ){
				$('.tr_status_csrnow_member').hide();
			}else{
				$('.tr_status_csrnow_member').show();
			}
			return res;
		}

		// ====Advance filter
		$(document).ready(function() {
			if( $('#awardReportadvanceFilterModal #pool_ref').length > 0 ){
				$('#awardReportadvanceFilterModal #pool_ref').select2({
					placeholder: 'Pool Reference',
					tags: true,
					ajax: {
						//url: <?php echo admin_url( 'admin-ajax.php' ); ?>, // AJAX URL provided by WordPress
						url: cipscript.ajax_url, // AJAX URL provided by WordPress
						dataType: 'json',
						delay: 250,
						data: function (params) {
							return {
								action: 'get_holder_options_data_award_report_select2_options',
								column: 'pool_ref',
								search: params.term
							};
						},
						processResults: function (data) {
							if (data.success) {
								return {
									results: data.data.map(function (item) {
										return { id: item, text: item }; // Map results for select2
									})
								};
							} else {
								return { results: [] };
							}
						},
						cache: true
					},
					minimumInputLength: 1
				});
			}
			if( $('#awardReportadvanceFilterModal #corp_approved').length > 0 ){
				$('#awardReportadvanceFilterModal #corp_approved').select2({
					placeholder: 'Status',
					tags: false,
					ajax: {
						url: cipscript.ajax_url, // AJAX URL provided by WordPress
						dataType: 'json',
						delay: 250,
						data: function (params) {
							return {
								action: 'get_holder_options_data_award_report_select2_options',
								column: 'corp_approved',
								search: params.term
							};
						},
						processResults: function (data) {
							if (data.success) {
								return {
									results: data.data.map(function (item) {
										return { id: item, text: item }; // Map results for select2
									})
								};
							} else {
								return { results: [] };
							}
						},
						cache: true
					},
					minimumInputLength: 1
				});
			}

			//selecting none value on select on load
			$('#awardReportadvanceFilterModal select[name="filter_condition_type"]').each(function() {
				if (!$(this).val()) {
					$(this).val('none');
				}
			});
			//hiding value textbox on load
			$('#awardReportadvanceFilterModal input[name="filter_condition_value"]').hide();

			// $(document).on("change", ".filter-condition-select", function() {
			// 	let condition = $(this).val();
			// 	$(this).next(".filter-value-input").toggle(condition !== 'none');
			// });

			$(document).on("change", ".select2-filter", function() {
				let filter_id = $(this).attr("id");
				let has_value = $(this).val() && $(this).val().length > 0;
				$('[advance-filter="accodian_' + filter_id + '"]').toggleClass("value", has_value);
			});

			//Clear filter button
			$(document).on("click", ".award_filter_clear", function() {
				$('#awardReportadvanceFilterModal select').each(function() {
					$(this).val('none').trigger('change');
				});
				$('#awardReportadvanceFilterModal input[type="text"]').each(function() {
					$(this).val('').trigger('change');
				});
				$('.filter-changed-indicator-award').hide();
				$('.award_report_advance_filter .fa-filter').html('');
				$('.award_report_filter_seleted').empty();

				$('#award_report_table').bootstrapTable('refresh');
			});
			//show filter form on click offilter
			$(document).on("click", "#awardReportadvanceFilterModal .ad_filter_label", function() {
				var target = $(this).attr("advance-filter");
				$("#awardReportadvanceFilterModal .ad_filter_label").removeClass("active");
				$(this).addClass("active");
				$(".ad_filter_body").removeClass("show");
				$("#" + target).addClass("show");
			});

			//show the selected filters
			$('body').on("click", "#awardReportadvanceFilterModal .award_report_filter_ok", function(e) {
				$('.award_report_filter_seleted').empty();
				if ($('.selected-filter').children().length == 0) {
					$('#award_report_table').bootstrapTable('refresh');
				}
				var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
				$('#awardReportadvanceFilterModal').modal('hide');
				$.blockUI(block_config);

				$('#awardReportadvanceFilterModal form').each(function() {
					var $form = $(this);
					var filterValue = $form.find('#filter_condition_value').val();
					var filterSelect = $form.attr('id');
					var textboxValue = $form.find('input[name="filter_condition_value"].active-textbox-award-report').val();

					//remove filter if already there
					$(`.award_report_filter_seleted .selected-filter[data-filter="${filterSelect}"]`).remove();

					if (filterValue && filterValue !== 'none') {

						var displayValue = ['is_not_empty', 'is_empty'].includes(filterValue) ? filterValue.replace(/_/g, ' ') : textboxValue;
						if(filterValue == 'CSR' || filterValue == 'CSR25'){
							var displayValue = filterValue;
						}
						if (displayValue && displayValue.trim() !== '') {
							var filterTitle = $form.closest('.form-group').find('label').text().replace('Filter by condition', '').trim();
							// button text
							var filterText = `${filterTitle}: ${filterValue.replace(/_/g, ' ')} ${textboxValue ? textboxValue.trim() : ''}`;

							var filterButtonHtml = `
								<button type="button" class="btn btn-info m-2 selected-filter single-award-report-filter" data-filter="${filterSelect}" data-value="${displayValue}">
									${filterText} <span class="remove-award-report-filter">×</span>
								</button>
							`;
							$('.award_report_filter_seleted').append(filterButtonHtml);
						}
					}
				});

				// Multi-select
				$('select[multiple]').each(function () {
					var $multiSelect = $(this);
					var closestForm = $multiSelect.closest('form');
					var label = closestForm.prev('label').text().trim();
					const selectId = $(this).attr('id');
					const selectedValues = $(this).val();

					if (selectedValues && selectedValues.length > 0) {
						// Loop through all selected values and display them individually
						selectedValues.forEach(function(value) {
							const displayValue = value; // Each selected value
							const buttonText = `${label}: ${displayValue} <span class="remove-filter-multi" data-value="${value}">×</span>`;

							// Append each value with an "X" to remove it from the filter
							const filterButtonHtml = `
								<button type="button" class="btn btn-info m-2 selected-filter multi-filter-award-report" data-filter="${selectId}" data-value="${displayValue}">
									${buttonText}
								</button>
							`;
							$('.award_report_filter_seleted').append(filterButtonHtml);
						});
					}
				});

			});

			//clcik on multiple selected filter btn and remove it
			$('body').on('click', '.multi-filter-award-report', function () {
				var filterButton = $(this);
				var filterSelect = filterButton.data('filter');
				var filterValue = filterButton.data('value');
				var $selectElement = $('#' + filterSelect);

				if ($selectElement.length > 0) {
					var currentValues = $selectElement.val() || [];
					var updatedValues = currentValues.filter(function (val) {
						return val !== filterValue;
					});

					// Update the Select2 element with new values
					$selectElement.val(updatedValues).trigger('change');

					// Check if the dropdown is empty
					if (updatedValues.length === 0) {
						var $form = $selectElement.closest('form');
						$form.find('select[name="filter_condition_type"]').val('none').trigger('change');
					}
				}
				// Remove the filter button
				filterButton.remove();
				$('.award_report_filter_ok').click();
			});


			// Remove filter button when '×' is clicked
			$('body').on('click', '.remove-award-report-filter, .single-award-report-filter', function() {
				var filterButton = $(this).closest('.selected-filter');
				var getSelectedFilterClass = $(this).closest('.selected-filter').data('filter').replace('filter_by_', '');
				var filterSelect = filterButton.data('filter');
				var filterValue = filterButton.data('value');
				var $form = $('#awardReportadvanceFilterModal form').filter(function() {
					return $(this).attr('id') === filterSelect;
				});
				$('.active_'+getSelectedFilterClass).hide();
				$('.active_'+getSelectedFilterClass).removeClass('award_report_filter_active');
				filterButton.remove();
				if (filterSelect == 'username' || filterSelect == 'email' || filterSelect == 'pool_ref' || filterSelect == 'corp_approved' || filterSelect == 'reference_isexactly' || filterSelect == 'eth_address_isexactly') {
					// emptying slecte2
					$('#'+filterSelect).empty().trigger("change");

					if( filterSelect == 'reference_isexactly' || filterSelect == 'eth_address_isexactly'){

						$('#awardReportadvanceFilterModal .'+filterSelect+'_wrapper').hide();
						if(filterSelect == 'reference_isexactly'){
							$("#filter_by_reference").find('#filter_condition_value').val('none');
						}else{
							$("#filter_by_eth_address").find('#filter_condition_value').val('none');
						}
					}
					//clicking apply filter button
					$('.award_report_filter_ok').click();
				} else {
					$form.find('#filter_condition_value').val('none');
					$form.find('#filter_condition_value').trigger("change");
					$form.find('input[name="filter_condition_value"]').val('');
					//clicking apply filter button
					$('.award_report_filter_ok').click();
				}
			});

			//show star when filter is selected
			function updateAwardReportFilterIndicator(filterElement) {
				var filterLabelId = filterElement.closest('.ad_filter_body').attr('id');
				var indicator = $('a[advance-filter="' + filterLabelId + '"] .filter-changed-indicator-award');

				if (filterElement.is('select[multiple]')) {
					if (filterElement.val() && filterElement.val().length > 0) {
						indicator.show();
						indicator.addClass('award_report_filter_active');
					} else {
						indicator.hide();
						indicator.removeClass('award_report_filter_active');
					}
				} else {
					if (filterElement.val() && filterElement.val() !== 'none') {
						indicator.show();
						indicator.addClass('award_report_filter_active');
					} else {
						indicator.hide();
						indicator.removeClass('award_report_filter_active');
					}
				}
			}

			// reset all select field
			$('#awardReportadvanceFilterModal').on('change', 'select', function() {
				updateAwardReportFilterIndicator($(this));
			});
			$('#awardReportadvanceFilterModal select').each(function() {
				updateAwardReportFilterIndicator($(this));
			});

			//Show value text box on seleted dropdown only CHECK+++++++++++
			$('#awardReportadvanceFilterModal select[name="filter_condition_type"]').on('change', function() {

				const $form = $(this).closest('form');
				const formID = $form.attr('id');
				const textbox = $form.find('input[name="filter_condition_value"]');

				// Show the textbox
				if ($(this).val() === 'contains_text' || $(this).val() === 'does_not_contains_text' ||
					$(this).val() === 'starts_with' || $(this).val() === 'ends_with' ||
					$(this).val() === 'is_exactly' || $(this).val() === 'greater_than' ||$(this).val() === 'less_than' || $(this).val() === 'equal_to' || $(this).val() === 'greater_than_equal' || $(this).val() === 'less_than_equal' ) {
					textbox.addClass('active-textbox-award-report').show();
					textbox.attr('required', true);
				} else {
					// Hide the textbox
					if ($(this).val() === 'none' || $(this).val() === 'is_not_empty' || $(this).val() === 'is_empty') {
						textbox.val('');
						textbox.attr('required', false);
						textbox.removeClass('active-textbox-award-report').hide();
					}
				}
			});

			function allowOnlyNumbersAwardFilter(selector) {
				$(document).on('input', selector, function () {
					const value = $(this).val();
					const numericValue = value.replace(/[^0-9.]/g, '');
					if (value !== numericValue) {
						$(this).val(numericValue);
					}
				});
			}

			// Apply the numeric-only rule to the specified fields CHECK+++
			allowOnlyNumbersAwardFilter('#awardReportadvanceFilterModal #filter_by_amount_due input[name="filter_condition_value"]');
		});
		// ====Advance filter END
    </script>
    <style>
        button.btn.btn-primary.award_report_export {
            padding: 11px !important;
			margin-right: 5px;
        }
		.custom_btn_wrapper_award_report {
			width: 95%;
			text-align: right;
			position: absolute;
			margin-top: 10px;
		}
		#award_summary_table{
			display: none;
		}
		#awardReportadvanceFilterModal{
			font-family: "Montserrat", Sans-serif;
		}
		.award_summary {
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 20px auto;
			font-family: "Montserrat", Sans-serif;
		}
		.award_summary table#award_summary_table {
			width: 60%;
			border-collapse: collapse;
			width: 80%;
			max-width: 600px;
			text-align: center;
		}

		#awardReportadvanceFilterModal select {
			width: 100% !important;
		}

		#awardReportadvanceFilterModal .ad_filter_body {
			display: none;
		}

		#awardReportadvanceFilterModal .ad_filter_body.show {
			display: block;
		}

		#awardReportadvanceFilterModal .ad_filter_body_container {
			border-left: 1px solid #dee2e6;
		}

		#awardReportadvanceFilterModal .ad_filter_body .heading-ad-filter {
			width: calc(100% + 30px);
			border-bottom: 1px solid #dee2e6;
			padding: 0 15px 15px 15px !important;
			margin-left: -15px;
			margin-right: 0 !important;
			margin-bottom: 20px;
			font-size: 18px !important;
			font-weight: 600;
		}

		#awardReportadvanceFilterModal .ad_filter_label.value div:after {
			content: "*";
			position: absolute;
			top: 50%;
			left: 100%;
			transform: translateY(-50%);
			padding-left: 5px;
		}

		#awardReportadvanceFilterModal .ad_filter_label.value div {
			position: relative;
		}

		#awardReportadvanceFilterModal #csr_advancefilter {
			width: 100%;
		}

		#awardReportadvanceFilterModal span.select2.select2-container.select2-container--default {
			width: 100% !important;
		}

		#awardReportadvanceFilterModal button.close {
			float: none;
			margin: 0;
			background: transparent;
			color: #000;
			opacity: 1;
			font-size: 30px;
			line-height: 25px;
		}

		#awardReportadvanceFilterModal .ad_filter_label {
			padding: 7px 12px;
			margin-bottom: 6px;
			color: #000 !important;
			border-radius: 10px;
		}

		#awardReportadvanceFilterModal .ad_filter_label.active {
			background: #7d38ab !important;
			color: #fff !important;
		}

		#awardReportadvanceFilterModal .modal-body {
			padding: 0 !important;
		}

		button.btn.btn-primary.award_report_advance_filter {
			padding: 11px !important;
		}

		#awardReportadvanceFilterModal .ad_filter_label .filter-changed-indicator-award {
			position: absolute;
			right: 20%;
			top: 19%;
			font-size: 20px;
		}

		#awardReportadvanceFilterModal .ad_filter_label {
			position: relative;
			padding-right: 20px;
		}

		#awardReportadvanceFilterModal #filter_by_reference span.select2.select2-container.select2-container--default,
		#awardReportadvanceFilterModal #filter_by_eth_address span.select2.select2-container.select2-container--default {
			margin-top: 20px;
		}

		.active-textbox {
			display: block !important;
		}

		.all_holder_buttons {
			position: absolute;
			margin-top: 10px;
			width: 96%;
		}

		@media (max-width: 1300px) and (min-width: 980px) {
			.all_holder_buttons {
				width: 95%;
			}
		}

		@media (max-width: 981px) and (min-width: 785px) {
			.all_holder_buttons {
				width: 94%;
			}
		}

		@media (max-width: 786px) {
			.all_holder_buttons {
				width: 93%;
			}
		}
    </style>
    <?php
}