<?php
function sa_member_po_invoice(){
	$html = "";
    global $wpdb;
    $wpdb_prefix = $wpdb->prefix;
    $invoice= $wpdb_prefix.'cip_member_invoice';
    $e_mail=$_SESSION['refAccount'];
	
// 	$uploads = wp_upload_dir(); 
// 	echo $uploads['baseurl'] . '/USER_PHOTOS/ronny/';
// 	echo $uploads['baseurl'];
	
	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_script('dr-moment');
	wp_enqueue_script('daterangepicker-script');
	wp_enqueue_script('jszip');
	ob_start();
	?>

	<div class="scroll">
	<script type="text/javascript">
		var selectToken = {
			"CSR": "CSR",
			"CSR25": "CSR25",
		};
	</script>
	<button type="button" class="btn btn-primary paid_po_invoice_export" title="Download"><i class="fa fa-download"></i></button>
	<table id="tokenholder_OP_Invoices_table"  data-filter-control="true" data-show-search-clear-button="false" data-pagination="true" data-sortable="true" data-toggle="table" data-archive-toggle="true" data-show-columns="true" data-show-columns-toggle-all="true" data-show-toggle="false" data-show-export="false" data-export-types="['csv', 'pdf']" class="table table-bordered" data-side-pagination="server" data-page-size="20" data-page-list="[20, 30, 50, 100]">
		<thead>
			<tr>
				<th data-field="id" data-filter-control="input" data-sortable="true" class="id" data-switchable="false" data-width="50" data-width-unit="px"><?php _e('#', CIP_TXTDOMAIN); ?></th>
				<th data-field="ProformaInvoiceNumber" data-filter-control="input" data-sortable="true" class="pnumber"><?php _e('PO Number', CIP_TXTDOMAIN); ?></th>
				<th data-field="Date" data-filter-control="input" data-sortable="true" class="date"><?php _e('Date', CIP_TXTDOMAIN); ?></th>
				<th data-field="InvoiceNumber" data-filter-control="input" data-sortable="true" class="inumber"><?php _e('Invoice Number', CIP_TXTDOMAIN); ?></th>
				<th data-field="PaidDate" data-filter-control="input" data-sortable="true" class="pdate"><?php _e('Paid Date', CIP_TXTDOMAIN); ?></th>
				<th data-field="Status" data-filter-control="select" data-filter-custom-search="BsTableFilterStatus" data-sortable="true" class="status"><?php _e('Status', CIP_TXTDOMAIN); ?></th>	
				<th data-field="Username" data-filter-control="input" data-sortable="true" class="uname"><?php _e('Amplivo username', CIP_TXTDOMAIN); ?></th>							
				<th data-field="FirstName" data-filter-control="input" data-sortable="true" class="fname"><?php _e('First Name', CIP_TXTDOMAIN); ?></th>							
				<th data-field="LastName" data-filter-control="input" data-sortable="true" class="lname"><?php _e('Last Name', CIP_TXTDOMAIN); ?></th>	
				<th data-field="Email" data-filter-control="input" data-sortable="true" class="email"><?php _e('Email', CIP_TXTDOMAIN); ?></th>			
				<th data-field="IntroducedBy" data-filter-control="input" data-sortable="true" class="by"><?php _e('Sponsor ID', CIP_TXTDOMAIN); ?></th>																																																							
				<th data-field="NetAmount" data-filter-control="input" data-sortable="true" class="netAmt"><?php _e('Net Amount', CIP_TXTDOMAIN); ?></th>		
                <th data-field="VATAmount" data-filter-control="input" data-sortable="true" class="vatAmt"><?php _e('VAT Amount', CIP_TXTDOMAIN); ?></th>
				<th data-field="GrossAmount" data-filter-control="input" data-sortable="true" class="grossAmt"><?php _e('Gross Amount', CIP_TXTDOMAIN); ?></th>
				<th data-field="VatNumber" data-filter-control="input" data-sortable="true" class="VatNumber"><?php _e('Vat Number', CIP_TXTDOMAIN); ?></th>							
				<!-- <th data-field="POVATAmount" data-filter-control="input" data-sortable="true" class="poAmt"><?php _e('(€) Paid VAT', CIP_TXTDOMAIN); ?></th> -->
				<th data-field="BusinessName" data-filter-control="input" data-sortable="true" class="bname"><?php _e('Business Name', CIP_TXTDOMAIN); ?></th>							
				<th data-field="Country" data-filter-control="input" data-sortable="true" class="country"><?php _e('Country', CIP_TXTDOMAIN); ?></th>							
				<th data-field="Address1" data-filter-control="input" data-sortable="true" class="address1"><?php _e('Address1', CIP_TXTDOMAIN); ?></th>														
				<th data-field="Address2" data-filter-control="input" data-sortable="true" class="address2"><?php _e('Address2', CIP_TXTDOMAIN); ?></th>							
				<th data-field="City" data-filter-control="input" data-sortable="true" class="city"><?php _e('City', CIP_TXTDOMAIN); ?></th>							
				<th data-field="State" data-filter-control="input" data-sortable="true" class="state"><?php _e('State', CIP_TXTDOMAIN); ?></th>
				<th data-field="Zipcode" data-filter-control="input" data-sortable="true" class="zip"><?php _e('Zipcode', CIP_TXTDOMAIN); ?></th>
                <th data-field="token" data-filter-control="select" data-filter-data="var:selectToken" data-sortable="true" class="token"><?php _e('Token', CIP_TXTDOMAIN); ?></th>
				<!-- <th data-field="action" data-switchable="false"><?php _e('Action', CIP_TXTDOMAIN); ?></th> -->
			</tr>
		</thead>
	</table>
	<style>
		body .btn.btn-primary.paid_po_invoice_export {
			position: absolute;
			right: 100px;
			top: 10px;
			padding-top: 0px !important;
			padding-bottom: 0px !important;
		}
	</style>
	<?php   
}
$op_Invoices_table_url = add_query_arg( [
	'action'	=>	'PaidOrders_Invoices_table_loader',
	'pageid'	=>	get_the_ID(),
], admin_url( 'admin-ajax.php' ) );
?>
<script>
    jQuery(document).ready(function(){
		const swalOIToast = Swal.mixin({
			toast: true,
			animation: true,
			position: 'bottom',
			showConfirmButton: false,
			timer: 4000,
			timerProgressBar: true,
			didOpen: (toast) => {
			toast.addEventListener('mouseenter', Swal.stopTimer)
			toast.addEventListener('mouseleave', Swal.resumeTimer)
			}
		});
		if( $('table#tokenholder_OP_Invoices_table').length > 0 ){
			$('[data-toggle-title="tooltip"]').tooltip();
			var op_Invoices_table_url = "<?php echo $op_Invoices_table_url ?>";
			var $OrdersInvoicesTable = $('#tokenholder_OP_Invoices_table');
			$OrdersInvoicesTable.bootstrapTable({
				method: 'post',
				contentType: 'application/x-www-form-urlencoded',
				url: op_Invoices_table_url,
				queryParams: function (p) {
					return {
						search: p.search,
						columnfilter: p.filter,
						limit: p.limit,
						offset: p.offset,
						sort: p.sort,
						order: p.order
					};
				},
				stickyHeader: true,
				onPostBody: function (){
					if( $('body').find('.modelpop_notes').length > 0 ){
						$('[data-toggle-tt="tooltip"]').tooltip();
					}else if( $('[data-toggle-tt="tooltip"]').length > 0 ){
						$('[data-toggle-tt="tooltip"]').tooltip();
					}
				}
			});
			let dateFormat = 'DD/MM/YYYY';
			$('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');
					$('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
					$('input.bootstrap-table-filter-control-Date[type="search"]').trigger(eve2);
				}
			);
			$('input.bootstrap-table-filter-control-PaidDate[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');
					$('input.bootstrap-table-filter-control-PaidDate[type="search"]').val(
						start.format(dateFormat) + ' - ' + end.format(dateFormat)
					);
					let eve2 = jQuery.Event("keyup");
					eve2.which = 13
					eve2.keyCode = 13
					$('input.bootstrap-table-filter-control-PaidDate[type="search"]').trigger(eve2);
				}
			);
			$(document).on('click', '.paid_po_invoice_export', function() {

				const table = $('#tokenholder_OP_Invoices_table');
				const options = table.bootstrapTable('getOptions');
				const filterValues = options.valuesFilterControl;
				var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
				$.blockUI(block_config);
				var appliedFilters = {}
				if (filterValues) {
					appliedFilters = Object.fromEntries(
						Object.entries(filterValues)
						.filter(([key, value]) => value.value !== undefined && value.value !== '')
						.map(([key, value]) => {
							return [value.field, value.value];
						})
					);
				}
				$.ajax({
					method: "POST",
					url: cipscript.ajax_url,
					data: { action: "export_paid_po_invoice_report" ,
						'columnfilter': JSON.stringify(appliedFilters)
					},
					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 = "PO/Invoice Report-" + date + " " + time + ".csv";

						// Create a blob with the CSV data
						var blob = new Blob([response], { type: 'text/csv;charset=utf-8;' });

						// Create a link and trigger the download
						var downloadLink = document.createElement("a");
						var url = URL.createObjectURL(blob);

						downloadLink.href = url;
						downloadLink.download = fileName;

						document.body.appendChild(downloadLink);
						downloadLink.click();
						document.body.removeChild(downloadLink);
						$.unblockUI();
					},
					error: function () {
						$.unblockUI();
					}
				});
			});
		}
        let lsname = '-hideColumn-tokenholder_OP_Invoices_table'
        let hideColumn = JSON.parse(localStorage.getItem(lsname)) || [];
        let th = $('table#tokenholder_OP_Invoices_table').find('thead tr th');
        th.each(function (index) {
            let attrTitle = $(this).attr('data-field')
            if (hideColumn.includes(attrTitle)) {
                $('table#tokenholder_OP_Invoices_table').bootstrapTable('hideColumn', attrTitle);
            }
        })
        $('table#tokenholder_OP_Invoices_table').on("column-switch.bs.table", function (e, field, checked) {
            if (checked && hideColumn.includes(field)) {
                // remove form local storage
                const index = hideColumn.indexOf(field);
                if (index > -1) {
                    hideColumn.splice(index, 1);
                    localStorage.setItem(lsname, JSON.stringify(hideColumn))
                }
            } else if (!checked) {
                if (hideColumn.includes(field)) {} else {
                    hideColumn.push(field);
                    localStorage.setItem(lsname, JSON.stringify(hideColumn))
                }
            }
        });
        $("body").on("change", ".toggle-all", function () {
            let $this = $(this);
            let div = $this.parent().parent()[0];
            $(div).find("input[type=checkbox]").each(function (index) {
                let checked = $(this).is(":checked");
                let field = $(this).attr("data-field");
                if (checked && hideColumn.includes(field)) {
                    // remove form local storage
                    const index = hideColumn.indexOf(field);
                    if (index > -1) {
                        hideColumn.splice(index, 1);
                        localStorage.setItem(
                            lsname,
                            JSON.stringify(hideColumn)
                        );
                    }
                } else if (!checked) {
                    if (hideColumn.includes(field)) {
                        // hands up nothing needed
                    } else {
                        // add in LS for nexttime
                        hideColumn.push(field);
                        localStorage.setItem(
                            lsname,
                            JSON.stringify(hideColumn)
                        );
                    }
                }
            });
        });
    });
</script>