<?php
/**
* Export class
*/
class Export {
	private $handle;
	/**
	 * Constructor
	 *
	 * @param	string	$filename
 	*/
	public function __construct($filename) {
		$this->handle = fopen(DIR_UPLOAD . $filename, 'a');
	}
	
	public function exportToCSV($data, $filename = null) {
		// File path and name
        if(!isset($filename))
        {
            $datetime = date('Ymd_His');
            $filename = 'data_' . $datetime . '.csv';
        }
        // Open the file in write mode
        $file = fopen($filename, 'w');

        // Write data to the file
        foreach ($data as $row) {
            fputcsv($file, $row);
        }

        // Close the file
        fclose($file);

        // Set headers to download the file
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename="'. $filename .'"');
        header('Pragma: no-cache');

        // Output the file to the browser
        readfile($filename);
	}

	public function __destruct() {
		fclose($this->handle);
	}
}