<?php
//support manager import token holders
add_shortcode('CIP-INTERNAL-TRANSFER-VIEW','cip_sm_internaltransfer_view_cb');
function cip_sm_internaltransfer_view_cb(){
	$html = "";
	ob_start();
	global $wpdb;
	$internaltransferTable = $wpdb->prefix.'internaltransfer';
	$getLogs = $wpdb->get_var( "SELECT COUNT(id) FROM $internaltransferTable WHERE 1 ORDER BY id desc" );
	if( current_user_can('supportagent') ){
			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('dr-moment');
            wp_enqueue_script('daterangepicker-script');
			?>
			<table id="internaltransfer_table" data-filter-control="true" data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="false" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" data-click-to-select="false" class="table table-bordered" data-side-pagination="server" data-pagination="true" data-page-list="[10, 20, 50, 100]">
			<thead>
				<tr>
					<th data-field="id" data-sortable="false" class="id"><?php _e('ID',CIP_TXTDOMAIN); ?></th>
					<th data-field="ref_no" data-sortable="true" data-filter-control="input" class="ref_no"><?php _e('Ref No',CIP_TXTDOMAIN); ?></th>
					<th data-field="_date" data-sortable="true" data-filter-control="input" class="_date"><?php _e('Date',CIP_TXTDOMAIN); ?></th>
					<th data-field="from_user" data-sortable="true" data-filter-control="input" class="from_user"><?php _e('From User',CIP_TXTDOMAIN); ?></th>
					<th data-field="to_user" data-sortable="true" data-filter-control="input" class="to_user"><?php _e('To User',CIP_TXTDOMAIN); ?></th>
					<th data-field="token" data-sortable="true" data-filter-control="select" class="token" data-filter-data="var:withdrawalProcessToken"><?php _e('Token',CIP_TXTDOMAIN); ?></th>
					<th data-field="amount" data-sortable="true" data-filter-control="input" class="amount"><?php _e('Amount',CIP_TXTDOMAIN); ?></th>
                    <th data-field="short_description" data-sortable="true" data-filter-control="input" class="short_description"><?php _e('Short Description',CIP_TXTDOMAIN); ?></th>
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
	<?php }
	$html .= ob_get_clean();
	return $html;
}
add_action('wp_footer','cip_init_bs_table_5913_script');
function cip_init_bs_table_5913_script(){
	$internaltransferLogsData = array();
	$internaltransferLogsData['action'] = 'internaltransfer_loader';
	$internaltransferLogsData['pageid'] = get_the_ID();
	$internaltransferLogsUrl = add_query_arg( $internaltransferLogsData, admin_url( 'admin-ajax.php' ) );
?><script>
jQuery(document).ready(function($){
    if( $('#internaltransfer_table').length > 0 ){
        var internaltransfer_table = $('#internaltransfer_table');
        var internaltransferLogsUrl = "<?php echo $internaltransferLogsUrl; ?>";
        internaltransfer_table.bootstrapTable({
            method: 'post',
            contentType: 'application/x-www-form-urlencoded',

            url: internaltransferLogsUrl,
            queryParams: function (p) {
                return {

                    amount_selection: $("#amount-fillter").val(),
                    columnfilter: p.filter,
                    limit: p.limit,
                    offset: p.offset,
                    sort: p.sort,
                    order: p.order,
                };
            },
            stickyHeader: true,
            // stickyHeaderOffsetY: parseInt($('header').height()),
            onPostBody: function (){

            }
        });

		let dateFormat = 'DD/MM/YYYY';
		$('#internaltransfer_table input.bootstrap-table-filter-control-_date[type="search"]')
		.daterangepicker(
			{
				autoUpdateInput: false,
				locale: {
					format: dateFormat,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default cancelButton_requested_date'
			},
			function(start, end) {
				startDate = start.format(dateFormat);
				endDate = end.format(dateFormat);
				let dates = [ startDate, endDate ];
				// filterByDate(dates, 'requested_date');
				$('#internaltransfer_table input.bootstrap-table-filter-control-_date[type="search"]').val(
					start.format(dateFormat) + ' - ' + end.format(dateFormat)
				);
				let eve2 = jQuery.Event("keyup");
				eve2.which = 13
				eve2.keyCode = 13
				$('#internaltransfer_table input.bootstrap-table-filter-control-_date[type="search"]').trigger(eve2);
			}
		);

		jQuery('#internaltransfer_table input.bootstrap-table-filter-control-_date[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatWD) + ' - ' + picker.endDate.format(dateFormatWD));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('#internaltransfer_table input.bootstrap-table-filter-control-_date[type="search"]').trigger(eve);
		});
		$('#internaltransfer_table input.bootstrap-table-filter-control-_date[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('#internaltransfer_table .bootstrap-table-filter-control-_date').trigger(eve);
		});

    }
});
</script>
<?php
}
add_action('wp_ajax_internaltransfer_loader','cip_internaltransfer_loader_cb');
function cip_internaltransfer_loader_cb(){
	global $wpdb;

	$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';

	$internaltransferTable = $wpdb->prefix.'internaltransfer';
	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
// 	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'STR_TO_DATE(`_date`,"%Y-%m-%d %H:%i:%s")';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $internaltransferTable WHERE 1");

	$filter_qry = "";
	$test = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	$isNumericColumn = array( 'amount' );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == '_date' ){
				if( str_contains($filterData, ' - ') ){
					$filterDataMinMax = explode(' - ', $filterData);
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d/%m/%Y') BETWEEN '$filterDataMinMax[0]' AND '$filterDataMinMax[1]'";
				}else{
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d/%m/%Y') = '$filterData'";
				}
			}else if( in_array( $filterKey, $isNumericColumn ) ){//numeric filter
				if( str_contains($filterData, '-') ){ //between
					$filterDataMinMax = explode('-', $filterData);
					$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
				}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
					$filter_qry .= " AND `$filterKey` $filterData";
				}else{
					$filter_qry .= " AND `$filterKey` = " . $filterData . "";
				}
			}else if( $filterKey == 'token' ){
				$filter_qry .= " AND `$filterKey` = '".$filterData."'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}

		}

	}

	if($filter_qry != ""){
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $internaltransferTable WHERE 1 $filter_qry");
	}

	$getLogs = $wpdb->get_results( "SELECT * FROM $internaltransferTable WHERE 1 $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset" );

	$rows = array();
	if( $getLogs ){
        $sno= $_REQUEST['offset'] + 1;
		$rowCounter = 1;
		foreach( $getLogs as $getLog ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				// 'id'			=>	__('id', CIP_TXTDOMAIN),
				'ref_no'			=>	__('ref_no', CIP_TXTDOMAIN),
				'_date'		=>	__('date', CIP_TXTDOMAIN),
				'from_user'		=>	__('from_user', CIP_TXTDOMAIN),
				'to_user'	=>	__('to_user', CIP_TXTDOMAIN),
				'token'	=>	__('token', CIP_TXTDOMAIN),
				'amount'	=>	__('amount', CIP_TXTDOMAIN),
				'short_description'	=>	__('short_description', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getLog->$columnKey;

					if( $columnKey == '_date' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('d/m/Y H:i');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'amount' ){
						$columnsDataVal = number_format( $columnsDataVal );
					}

					$row[$columnKey] = $columnsDataVal;
				}

			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows,
		'test'	=> "SELECT * FROM $internaltransferTable WHERE 1 $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset"
	);
	echo wp_json_encode( $out );
	exit;
}