<?php

class CsvAdapter {


# ~ Export data to CSV file format - - - - - - - - - - - - - - - - - - - - - - #
	public function export($records, $columns, $filename = null) {

		$columns = array_values($columns);

		# Prepare records for export
		foreach($records as $index => $record) {
			$records[$index] = array_values($record);
		}

		# Append columns to records
		array_unshift($records, $columns);

		# Get filename
		$filename = date('Y.m.d H:i') . '-' . $filename . '.csv';

		# Set headers
		header('Content-Type: text/csv');
		header('Content-Disposition: attachment; filename="' . $filename .'"');

		# Build CSV
		$fp = fopen('php://output', 'w');
		foreach ($records as $line) {
			fputcsv($fp, $line);
		}
		fclose($fp);
		exit;
	}

}
