<?php
class Seguro_VistoriaprevianovaController extends Agro_Controller_Action {
	protected $_paginator = false;

	public function init() {
		//$this->view->title = 'Solicitação de Vistorias Prévias » Listagem';
	}

	public function indexAction() {
		$this->view->form = $this->getForm();
	}

	public function getForm() {
		return new Seguro_Form_VistoriaPrevia();
	}

	public function getModel() {
		return new Seguro_Model_VistoriaPreviaNova();
	}

	public function listAction() {
		$this->getHelper('layout')->disableLayout();

		$where = $this->getFilter();
		$Model = $this->getModel();

		if ($this->getRequest()->getParam('o')) {
			$Model->_order = trim($this->getRequest()->getParam('o'). ' ' . $this->getRequest()->getParam('s'));
		}

		$Rs = $Model->getData($where);

		$this->view->paginator = $Rs;
	}

	public function getFilter() {
		$where = array();

		if ($this->getRequest()->getParam('dt_inicio')) {
			$where[] = array(
				'field' => 'sub.data_semeadura',
				'operator' => '<=',
				'value' => Agro_Util::formatDate($this->getRequest()->getParam('dt_inicio'), 'Y-MM-dd')
			);
		}

		if ($this->getRequest()->getParam('fl_filtro_data_plantio')) {
			$where[] = array(
				'field' => 'fl_filtro_data_plantio',
				'operator' => '=',
				'value' => true
			);
		}

		if ($this->getRequest()->getParam('id_municipio') && $this->getRequest()->getParam('id_municipio') != 0) {
			$where[] = array(
				'field' => 'm.id',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_municipio')
			);
		}

		if ($this->getRequest()->getParam('id_estado') && $this->getRequest()->getParam('id_estado') != 0) {
			$where[] = array(
				'field' => 'm.id_estado',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_estado')
			);
		}

		$where[] = array(
			'field' => 'vp.id_status',
			'operator' => ' is ',
			'value' => 'null'
		);

		if (($this->getRequest()->getParam('id_safra')) && ($this->getRequest()->getParam('id_safra') != 'TODAS')) {
			$where[] = array(
				'field' => 'saf.id',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_safra')
			);
		}

		if ($this->getRequest()->getParam('id_produto')) {
			$where[] = array(
				'field' => 'prod.id',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_produto')
			);
		}

		if ($this->getRequest()->getParam('id_corretor')) {
			$where[] = 'usu.id in (' . implode(',', $this->getRequest()->getParam('id_corretor')). ')';
		}

		if ($this->getRequest()->getParam('vl_pesquisar_por')) {
			switch ($this->getRequest()->getParam('pesquisar_por')) {
				case 'ds_nome_proponente':
				case 'ds_cfp_proponente':
					$where[] = array(
						'field' => $this->getRequest()->getParam('pesquisar_por'),
						'operator' => 'ilike',
						'value' => '%'.$this->getRequest()->getParam('vl_pesquisar_por')
					);
					break;
				default:
					$where[] = array(
						'field' => $this->getRequest()->getParam('pesquisar_por'),
						'operator' => '=',
						'value' => $this->getRequest()->getParam('vl_pesquisar_por')
					);
					break;
			}
		}

		if ($this->getRequest()->getParam('dt_criacao')) {
			$where[] = array(
				'field' => 'to_char(vp.dt_criacao, \'DD/MM/YYYY\')',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('dt_criacao')
			);
		}

		if ($this->getRequest()->getParam('situacao_boleto')) {
			$where[] = array(
				'field' => 'pb.fl_pago',
				'operator' => 'is',
				'value' => $this->getRequest()->getParam('situacao_boleto') == 1 ? true : false
			);
		}

		return $where;
	}

	public function encaminharvistoriaAction(){
		$this->isAjax();
		$dados = $this->getRequest()->getParams();

		$Model = $this->getModel();

		if($Model->save($dados)) {
			$this->getResponse()->setBody(Zend_Json::encode(count($dados['id_propostas'])." proposta(s) encaminhada(s) com sucesso!"));
		}else{
			$this->getResponse()->setBody(Zend_Json::encode("Erro ao encaminhar proposta!"));
		}
	}	

	public function dispensarvistoriaAction(){
		$this->isAjax();

		$Model = $this->getModel();

		if($Model->dispensarVistoria($this->getRequest()->getParams('id_propostas')) == true) {
			$this->getResponse()->setBody(Zend_Json::encode(count($dados['id_propostas'])." proposta(s) dispensada(s) com sucesso!"));
		}else{
			$this->getResponse()->setBody(Zend_Json::encode("Erro ao encaminhar proposta!\n ".$Model->getMessage()));
		}
	}

	public function importarsolicitacaoAction() {
		$this->view->title = "Seguro » Vistoria Prévia » Importar Solicitação";

		$this->view->form = $this->getForm();

		if ($this->getRequest()->isPost()) {
			$this->isAjax();

			$resposta = array();
			if ($this->getRequest()->getParam('id_empresa')) {
				$Adapter = new Zend_File_Transfer_Adapter_Http();
				$Adapter->setDestination(APPLICATION_PATH.'/upload_files/temp/');
				$file = $Adapter->getFileInfo();

				if (!$Adapter->receive($file['solicitacoes']['name'])) {
					$resposta['status'] = 'Erro ao importar Solicitações!';
				} else {
					$extensao = explode('.',$file['solicitacoes']['name']);
					if ($extensao[1] == 'csv') {
						$arquivo = fopen(APPLICATION_PATH.'/upload_files/temp/' . $file['solicitacoes']['name'],"r");
						$vistoriaNovaDados = array(
							'id_propostas' => array(),
							'id_empresa' => $this->getRequest()->getParam('id_empresa')
						);
						while(($dados = fgetcsv($arquivo, 0, ";")) != false){
							if (is_numeric($dados[0])) {
								$vistoriaNovaDados['id_propostas'][] = $dados[0];
							}
						}

						$Model = $this->getModel();
						$saved = $Model->save($vistoriaNovaDados);

						$resposta['status'] = 'Importação concluída com sucesso!';
						if ($saved !== true) {
							$resposta['status'] = $saved;
						}
					} else {
						$resposta['status'] = 'Formato de arquivo inválido!';
					}
				}
			} else {
				$resposta['status'] = 'Empresa inválida!';
			}

			$this->getResponse()->setBody(Zend_Json::encode($resposta));
		}
	}
}
