<?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 Custom Posts
if (isset($_GET['export_custom'])) {
    ob_start();

    // Export Custom Posts
	$custom_posts_export = XC_Queries::export_custom_posts();

    $export_buffer = fopen('php://temp', 'r+');
	
    fputcsv($export_buffer, array('Id', 'Type', 'Title', 'Words', 'Modified', 'Published', 'Category', 'URL'), ';');

	if (!empty($custom_posts_export)) {
		foreach ($custom_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-custom-' . 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;
}
?>