<?php

class Sinistro_LaudosperitoController extends Agro_Controller_Action {
	public function init() {
		$this->view->title = "Sinistro » Laudos para peritos";
	}

	public function getModel() {
		return new Sinistro_Model_LaudosPerito();
	}

	public function getForm(){
		return new Sinistro_Form_LaudosPerito();
	}

	public function getFilter() {

		$Model = $this->getModel();
		$where = array();

		if (($this->getRequest()->getParam('id_safra')) && ($this->getRequest()->getParam('id_safra') != 'TODAS')){
			$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('id_cobertura')) {
			$where[] = array(
				'field' => 'id_cobertura',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_cobertura')
			);
		}

		if ($this->getRequest()->getParam('fl_ativo') != null) {
			$where[] = array(
				'field' => 'fl_ativo',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('fl_ativo')
			);
		}

		return $where;
	}

	public function excelAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		ini_set('memory_limit','2048M');
		$where = $this->getFilter();

		$Module = $this->getRequest()->getModuleName();
		$Controller = $this->getRequest()->getControllerName();
		$Model = $this->getModel();

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

		$Rs = $Model->fetchAllPaginator($where);
		$arr = array();
		$count = 0;

		foreach($Rs as $Row){;
			$arr[$count]['chave']       = $Row['chave'];
			$arr[$count]['id_safra']	= $Row['id_safra'];
			$arr[$count]['tipo']       = $Row['tipo'];
			$arr[$count]['produto_cobertura']  	= $Row['produto_cobertura'];
			$arr[$count]['digitavel']  			=  $Row['digitavel'];
			$count++;
		}

		if ($Model->_columnExcel) {
			$Csv = new Agro_Plugin_Rs2Csv();
			$Csv->setTitles($Model->_columnExcel);
			$Csv->setRecordSet($arr);
			$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();
		}
	}

}
