<?php

/*require '../function.php';
require '../database_connection.php';*/


require_once('../../../wp-config.php');

global $wpdb;

$conn = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$query = "SELECT * FROM ".$wpdb->prefix."contact_listing ORDER BY id DESC";
$entries = mysqli_query($conn,$query);
$data = array();
 $data[] = array(

		'id' => 'S.No.',//if the first cell on a CSV starts with ID, Excel just assumes you are trying to open a SYLK File.
		'u_name' => 'Name',
		'u_email' => 'Email',
		'u_subject' => 'Subject',
		'u_message' => 'Message',
		'created_at' => 'Created',
 );

while ($row=mysqli_fetch_assoc($entries))
		{   
			$tempArray 		= array();

			 $data[] = array(

			 		'id' =>  $row['id'],
					'u_name' => $row['u_name'],
					'u_email' => $row['u_email'],
					'u_subject' => $row['u_subject'],
					'u_message' => $row['u_message'],
					'created_at' => $row['created_at'],
			 );

        }
// var_dump($data);die;

generateCsvFromArray($data,'contact-lsiting.csv');



function generateCsvFromArray($input_array, $output_file_name, $delimiter=',')
{
	/** open raw memory as file, no need for temp files */
	$temp_memory = fopen('php://memory', 'w');
	/** loop through array */
	foreach ($input_array as $line) {
		/** default php csv handler **/
		fputcsv($temp_memory, $line, $delimiter);
	}
		// var_dump($temp_memory);die;
	/** rewrind the "file" with the csv lines **/
	fseek($temp_memory, 0);
	/** modify header to be downloadable csv file **/
	// header('Content-Type: application/csv');
	// header('Content-Disposition: attachement; filename="' . $output_file_name . '";');

	header('HTTP/1.1 200 OK');
    header('Cache-Control: no-cache, must-revalidate');
    header("Pragma: no-cache");
    header("Expires: 0");
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=$output_file_name");


	
	/** Send file to browser for download */
	fpassthru($temp_memory);
}

?>