<?php
function setData($data, $val)
{
	if(!empty($data)){
		$data.= ",";
	}
	$data.= '"'.str_ireplace('"', "'", str_ireplace('&nbsp;', " ", $val)).'"';
	return $data;
}

$data = "";
foreach($this->data->set->display as $r){
	$data = setData($data, $r['nama']);
}
$data.= "\n";

$date = new Date;
foreach($this->data->data as $n => $i){
	$res = "";
	foreach($this->data->set->display as $r){
		$id = $r['id'];
		$val = $i->$id;
		
		$id_csv  = $id.'_csv';
		$val_csv = $i->$id_csv;
		
		if($r['type'] == 'date'){
			$val = $date->serialDate($val);
		}
		if($r['type'] == 'numeric'){
			$int = (int)$r['dec'];
			$val = number_format($val, $int, '.', '');
		}
		
		if(!empty($val_csv)){
			$val = $val_csv;
		}
		
		$res = setData($res, $val);
	}
	$res.= "\n";
	$data.= $res;
}

$nama = str_ireplace(" ", "_", $this->data->set->modul);
$namafile = "ext/csv/".$nama.".csv";
$handle = fopen ($namafile, "w");
if (!$handle) {
	echo "Gagal";
} else {
	 fwrite ($handle, $data);
	 echo "<a href='".$this->baseUrl.$namafile."'>Klik di sini untuk download CSV ".$nama."</a>";
}
fclose($handle); 		

// echo nl2br($data);

		
// $nama = str_ireplace(" ", "_", $this->data->set->modul);
// $filename = $nama;
// header('Content-Type: application/csv');
// header('Content-Disposition: attachment; filename="'.$filename.'.csv"');
// echo $data; 
// exit();