<?php

class Comercializacao_EstadoController extends Agro_Controller_Comercializacao {
	
	public function init() {
		$this->view->title = 'Produto » Comercializações » Estados';
		$this->tipo = 'E';		
	}
	
	public function getForm() {
		$Form = new Comercializacao_Form_Comercializacao();
		$Form->populate($this->getRequest()->getParams());
		return $Form;
	}
	
	public function getRow() {
		$params = explode(',', $this->getRequest()->getParam('id'));
		$Model = $this->getModel();

		$Row = $Model->find($params[0])->current()->toArray();

		$Produto = new Produto_Model_Produtos();
		
		$arr = $Produto->find($Row['id_produto'])->current()->toArray();
		$this->view->produto = $arr['ds_nome_produto'];
		
		$Safra = new Produto_Model_Safras();
		
		$arrSafras = $Safra->find($arr['id_safra'])->current()->toArray();

		$this->view->safra = $arrSafras['ds_nome_safra'];
		$this->view->idSafra = $arrSafras['id'];

		return $Row;
	}
	
	public function geraxlsAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$dados = $this->getRequest()->getParams();
		$Model = new Comercializacao_Model_Comercializacoes();
		
		$ret = $Model->getComercializacoesEstadoXls($dados);
		require_once(APPLICATION_PATH . "/../library/Agro/xls/PhpSimpleXlsGen.php");
		
		$myxls = new PhpSimpleXlsGen();
		$myxls->totalcol = 6;
		//produto | DATA INICIO VEN | DATA FIM VEND | DADTA INICIO COB | DATA FIM COB |  ESTADO
		$myxls->InsertText('Produto');
		$myxls->InsertText('Inicio Vendas');
		$myxls->InsertText('Fim Vendas');
		$myxls->InsertText('Inicio Cobertura');
		$myxls->InsertText('Fim Cobertura');
		$myxls->InsertText('Estado');
		foreach($ret as $linha) {

			$myxls->InsertText( utf8_decode($linha['ds_nome_produto']) . ' ');
			$myxls->InsertText( Agro_Util::formatDate($linha['dt_comercializacao_inicio'], Zend_Date::DATES) . ' ' );
			$myxls->InsertText( Agro_Util::formatDate($linha['dt_comercializacao_fim'], Zend_Date::DATES) . ' ' );
			$myxls->InsertText( Agro_Util::formatDate($linha['dt_cobertura_inicio'], Zend_Date::DATES) . ' ' );
			$myxls->InsertText( Agro_Util::formatDate($linha['dt_cobertura_fim'], Zend_Date::DATES) . ' ' );
			$myxls->InsertText( utf8_decode($linha['ds_sigla']) . ' ' );
		}
		
		$myxls->SendFile();
	}
	
	
	public function getFilter() {
		$where = array();
		$where[] = array(
			'field' => 'tp_comercializacao',
			'operator' => '=',
			'value' => $this->tipo
		);
		
		if ($this->getRequest()->getParam('ds_nome_comercializacao')) {
			$where[] = array(
				'field' => 'ds_nome_comercializacao',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_nome_comercializacao').'%'
			);
		}
		
		if ($this->getRequest()->getParam('id_safra')){
			$where[] = array(
				'field' => 'id_safra',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_safra')
			);
		}
		
		if ($this->getRequest()->getParam('id_produto')){
			$where[] = array(
				'field' => 'id_produto',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_produto')
			);
		}
		
		if ($this->getRequest()->getParam('fl_ativo')){
			$where[] = array(
				'field' => 'c.fl_ativo',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('fl_ativo')
			);
		}
		
		if ($this->getRequest()->getParam('id_estado')){
			$value = $this->getRequest()->getParam('id_estado');
			
			$where[] = "c.id in (select id_comercializacao from comercializacao.comercializacoes_estados where id_estado = $value group by id_comercializacao)";
		}
		
		if ($this->getRequest()->getParam('id_municipio')) {
			$value = $this->getRequest()->getParam('id_municipio');
			
			$where[] = "c.id in (select id_comercializacao from comercializacao.comercializacoes_municipios me where me.id_municipio = $value group by id_comercializacao)";
		}
		
		return $where;
	}

    public function excelAction() {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        ini_set('memory_limit','4096M');
        ini_set('max_execution_time',360);

        $where = $this->getFilter();
        $Model = new Comercializacao_Model_ComercializacoesEstados();

        if ($this->getRequest()->getParam("o")) {
            $Model->_order = trim($this->getRequest()->getParam("o") .' '. $this->getRequest()->getParam("s"));
        }

        $Rs = $Model->fetchAllPaginator($where);
        if ($Model->_columnExcel) {
            $Csv = new Agro_Plugin_Rs2Csv();
            $Csv->setTitles($Model->_columnExcel);
            $Csv->setRecordSet($Rs);
            $Csv->setType("application/octet-stream");
            $Csv->setFileName("pesquisa.csv");
            $Csv->setDisposition("attachment");
            $Csv->setSeparator(";");
            $Csv->getCsv();
        } else {
            $Csv = new Agro_Plugin_Rs2Csv();
            $Csv->setTitles($Model->_columnExcel);
            $Csv->setRecordSet(array('Excel não configurado'));
            $Csv->setType("application/octet-stream");
            $Csv->setFileName("notfound.csv");
            $Csv->setDisposition("attachment");
            $Csv->setSeparator(";");
            $Csv->getCsv();
        }
    }
}