<?php

class Agro_Plugin_Rs2Csv {
	private $_filename, $_type, $_disposition, $_separator, $_recordSet, $_string, $_titles, $_ignoreHeader;

	public function __construct() {
		$this->_string = "";
		$this->setFileName("file.csv");
		$this->setType("text/tab-separated-values");
		$this->setDisposition("attachment");
		$this->setSeparator(",");
		$this->setIgnoreHeader(false);
	}

	public function setDisposition($disposition) { $this->_disposition = $disposition; }
	public function setSeparator($separator) { $this->_separator = $separator; }
	public function setIgnoreHeader(bool $ignore) { $this->_ignoreHeader = $ignore; }
	public function setRecordSet($RecordSet) { $this->_recordSet = $RecordSet; }
	public function setTitles($titles) { $this->_titles = $titles; }
	public function setFileName($name) { $this->_filename = Zend_Controller_Front::getInstance()->getRequest()->getControllerName() . '_' . Zend_Controller_Front::getInstance()->getRequest()->getActionName() . '.csv'; }
	public function setType($type) { $this->_type = $type; }

    public function buildTitles() {
    	$line = array();

    	foreach ($this->_titles as $title) {
    		$line[] = utf8_decode($title);
    	}

    	$this->_string = implode($this->_separator, $line)."\n";
    }

    public function buildString() {
		if (!$this->_ignoreHeader) {
    		$this->buildTitles();
		}

    	$lines = array();
    	$l = 0;
    	$c = 0;

    	if ($this->_recordSet) {
    		foreach ($this->_recordSet as $Row) {
				foreach ($this->_titles as $column => $title) {
					$lines[$l][$c] = mb_convert_encoding($Row[$column], 'ISO-8859-1' ,'UTF-8');
					$c++;
				}

    			$l++;
    		}
    	}

		foreach ($lines as $line) {
			$this->_string .= implode($this->_separator, $line)."\n";
		}
    }

	public function getCsv($download = true, string $filePath= '') {

		$this->buildString();
        $this->saveLastReport();

        if ($download) {
			if (!empty($filePath)) {
				$originalPath = APPLICATION_PATH . '/upload_files/relatorio/' . $this->_filename;
				copy($originalPath, $filePath);
				$this->_filename = basename($filePath);
			}

            header("Content-Disposition: ".$this->_disposition."; filename=".$this->_filename);
            header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
            header("Cache-Control: no-store, no-cache, must-revalidate");
            header("Cache-Control: post-check=0, pre-check=0", false);
            header("Content-Length: ".strlen($this->_string));
            header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
            header("Content-type: ".$this->_type);
            header("Pragma: no-cache");

            die($this->_string);
        }
	}

    private function saveLastReport() {
        $file = fopen(APPLICATION_PATH . '/upload_files/relatorio/' . $this->_filename, 'w');
        fputs($file, $this->_string);
        fclose($file);
        $this->insereLog();
    }

	public function saveDailyReport($nomeSafra) {
		$nomeSafra = str_replace("/", "", $nomeSafra);
		$this->_filename = "relatorio_aviso_sinistro_safra_{$nomeSafra}.csv";
		$this->buildString();
        $file = fopen(APPLICATION_PATH . '/upload_files/relatorio/' . $this->_filename, 'w');
        fputs($file, $this->_string);
        fclose($file);
        $this->insereLog();
    }

    /*
    * Salva um registro na tabela de log dos arquivos
    */
    private function insereLog() {

        $User = Zend_Auth::getInstance()->getIdentity();
        $data = array(
            'id_usuario_criacao' => $User->id,
            'ds_controller'      => Zend_Controller_Front::getInstance()->getRequest()->getControllerName(),
            'ds_module'          => Zend_Controller_Front::getInstance()->getRequest()->getModuleName(),
            'ds_action'          => Zend_Controller_Front::getInstance()->getRequest()->getActionName(),
            'filename'           => Zend_Controller_Front::getInstance()->getRequest()->getControllerName() . '_' . Zend_Controller_Front::getInstance()->getRequest()->getActionName() . '.csv'
        );

        Agro_Db_Table_Abstract::getDefaultAdapter()->insert('log.log_relatorios_gerados', $data);
    }

	public function changeFileName($name) {
		//Como foi forçado (e não pensado) no método filename que todo nome de arquivo .csv 
		//deverá ser controller_action.csv, este método (changeFileName) foi criado para quando se é necessário
		//alterar o nome do csv sem afetar os demais relatório que já utilizam do método
		//setFileName. Vale lembrar que o método setFileName obriga a ser passado um parâmetro que não é usado nele. 
		//Parabéns aos envolvidos \o.
		$this->_filename = $name;
	}

	public function getFileName()
    {
        return $this->_filename;
    }

	public function getCsvContent()
	{
		$this->buildString();
        $this->saveLastReport();

        return $this->_string;
	}
}
