<?php
// Exit if Accessed Directly
if ( ! defined( 'ABSPATH' ) ) exit;

// Classes Require
require_once dirname( plugin_dir_path( __FILE__ ) ) . '/includes/xc-class-queries.php';

// Query to Export Posts
if (isset($_GET['export_posts'])) {
	ob_start();
	
	// Export Posts
	$posts_export = XC_Queries::export_posts();

	$export_buffer = fopen('php://temp', 'r+');

	fputcsv($export_buffer, array('Id', 'Title', 'Words', 'Modified', 'Published', 'Category', 'URL'), ';');

	if (!empty($posts_export)) {
		foreach ($posts_export as $row) {
			$row = array_map('html_entity_decode', $row);
			fputcsv($export_buffer, array_values($row), ';');
		}
	}

	rewind($export_buffer);
	$csv_output = chr(0xEF) . chr(0xBB) . chr(0xBF) . stream_get_contents($export_buffer);
	fclose($export_buffer);

	ob_get_clean();

	$file = "xpose-content-export-posts-" . wp_date('Y-m-d') . ".csv";

	header("Content-Type: text/csv; charset=utf-8");
	header("Content-Disposition: attachment; filename=\"$file\"");
	header("Content-Transfer-Encoding: binary");
	header("Cache-Control: public, must-revalidate, max-age=0");

	$out = fopen('php://output', 'w');
	fwrite($out, $csv_output);
	fclose($out);
	exit;
}
?>