<?php
if(isset($_POST['exporttocsv']))
{
	
	$path = preg_replace('/wp-content(?!.*wp-content).*/','',__DIR__);
	require($path.'wp-load.php');
	$wpdb->show_errors(); 
	
	
global $wpdb;
							
// Grab any post values you sent with your submit function
$DownloadReportFrom = $_POST['ReportDateFrom'];
$DownloadReportTo = $_POST['ReportDateTo'];

// Build your query						
$MyQuery = $wpdb->get_results($wpdb->prepare('SELECT id,email,value,recorded,action FROM '.$wpdb->prefix.'wpfresh5_gdpr_requests where type=%s',array('uns')));
						

// Process report request
if (! $MyQuery) {
$Error = $wpdb->print_error();
die("The following error was found: $Error");
} else {
// Prepare our csv download

// Set header row values
$csv_fields=array();
$csv_fields[] = '#';
$csv_fields[] = 'Email';
$csv_fields[] = 'Name';
$csv_fields[] = 'Date and Time';
$csv_fields[] = 'Status';

$output_filename = 'MyReport_' . $DownloadReportFrom .'-'. $DownloadReportTo  . '.csv';
$output_handle = @fopen( 'php://output', 'w' );
 
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Content-Description: File Transfer' );
header( 'Content-type: text/csv' );
header( 'Content-Disposition: attachment; filename=' . $output_filename );
header( 'Expires: 0' );
header( 'Pragma: public' );	

// Insert header row
fputcsv( $output_handle, $csv_fields );

// Parse results to csv format
foreach ($MyQuery as $Result) {
	$leadArray = (array) $Result; // Cast the Object to an array
	// Add row to file
	fputcsv( $output_handle, $leadArray );
	}
 
// Close output file stream
fclose( $output_handle ); 

die();
}
}
?>