<?php
class CsvController 
{
    public function csvExport() {
        $res = $this->db->Query($this->conf['export_query']);
        if ($this->db->Error($this->conf['export_query'])) return false;
        $firstRow = $res->fetch(PDO::FETCH_ASSOC);
        if (!$firstRow) return false;
        $columns = array_keys($firstRow);
        $this->columnDetails = array();
        for ($i = 0; $i < count($firstRow); $i++) {
            $$this->column_details[$columns[$i]] = $this->getColumnTypeFromQuery($res, $i);
        }
        $header = $this->db->getHeaderNames($columns);
    
        $fwh = fopen($this->conf['filename'], "w");
        fwrite($fwh, implode(';', $header)."\n");
        fwrite($fwh, implode(';', convertRow($firstRow))."\n");
    
        while($row = $res->fetch(PDO::FETCH_ASSOC)) {
            fwrite($fwh, implode(';', convertRow($row))."\n");
        }
        fclose($fwh);
        return true;
    }
    
    public function csvConvert($tableArray)
    {
        $result = "";
        foreach ($tableArray as $row)
        {
            $result .= implode(';', $this->convertRow($row)) . "\r\n";
        }
        return $result;
    }    
    
    
    private function convertRow ($row) {
        $result = array();
    
        foreach ($row as $key => $value) 
        {
            $result[] = $this->convertCell($value);
        }
        return $result;
    }
    
    private function convertCell ($cell, $format = "VAR_STRING") {
        switch ($format) {
            case 'VAR_STRING':
                return trim($cell);
            case 'FLOAT':
            case 'NEWDECIMAL':
                return number_format($cell, 2, ",", "");
            case 'DATE':
                return ($format == '0000-00-00') ? "" : $cell;
            default:
                return $cell;
        }
        return $cell;
    }    
}