<?php

class Seguro_RenovacaoController extends Agro_Controller_Proposta {

	public function init() {
		$this->view->title = 'Seguro » Proposta » Renovação';
		$this->view->renovacao = true;
	}

	public function getModel() {
		return new Seguro_Model_Renovacao();
	}

	public function indexAction() {
		$this->view->title .= " » Listagem";
		$this->view->form = new Seguro_Form_PropostaSearch(true);
	}

	public function getFilter() {
		$User = Zend_Auth::getInstance()->getIdentity();
		$where = array();

		if ($User->tp_usuario == 'C') {
		    $where[] = "(scr.id_usuario = ".$User->id." or prc.id_usuario = ".$User->id.")";
		}

		if ($User->tp_usuario == 'P') {
			$where[] = "(spr.id_usuario_criacao = ".$User->id." or prc.id_usuario = ".$User->id.")";
		}

		if ($User->tp_usuario == 'C' || $User->tp_usuario == 'P') {
		    $where[] = "spr.id not in (select id_proposta from seguro.propostas_corretores_renovacao where id_usuario <> ".$User->id.")";
		}

		if ($this->getRequest()->getParam('id')) {
			$where[] = "spe.id_endosso = (select id_endosso from seguro.propostas where id = ".$this->getRequest()->getParam('id').")";
		}

		if ($this->getRequest()->getParam('nr_apolice')) {
			$where[] = array(
				'field' => 'spr.nr_apolice',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('nr_apolice')
			);
		}

		if ($this->getRequest()->getParam('id_corretor')) {
			$where[] = array(
				'field' => 'scr.id_usuario',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_corretor')
			);
		}

		if ($this->getRequest()->getParam('id_preposto')) {
			$where[] = array(
				'field' => 'spr.id_usuario_criacao',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_preposto')
			);
		}

		if ($this->getRequest()->getParam('ds_sigla_propriedade')) {
			$where[] = array(
				'field' => 'suf.ds_sigla',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('ds_sigla_propriedade')
			);
		}

		if ($this->getRequest()->getParam('id_municipio_propriedade')) {
			$where[] = array(
				'field' => 'spd.id_municipio',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_municipio_propriedade')
			);
		}

		if ($this->getRequest()->getParam('dt_inicio') && $this->getRequest()->getParam('dt_fim')) {
			$inicio = Agro_Util::formatDate($this->getRequest()->getParam('dt_inicio'), Zend_Date::W3C);
			$final = Agro_Util::formatDate($this->getRequest()->getParam('dt_fim'), Zend_Date::W3C);

			$where[] = "spr.dt_vigencia_inicio between '$inicio' and '$final'";
		}

		if ($this->getRequest()->getParam('dt_inicio') && !$this->getRequest()->getParam('dt_fim')) {
			$inicio = Agro_Util::formatDate($this->getRequest()->getParam('dt_inicio'), Zend_Date::W3C);
			$where[] = "spr.dt_vigencia_inicio >= '$inicio'";
		}

		if ($this->getRequest()->getParam('id_status') > 0) {
			$where[] = array(
				'field' => 'spr.id_status',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_status')
			);
		}

  		if ($this->getRequest()->getParam('id_safra')) {
   			$where[] = array(
   				'field' => 'ppr.id_safra',
   				'operator' => '=',
   				'value' => $this->getRequest()->getParam('id_safra')
   			);
   		} else {
   			$where[] = array(
   					'field' => 'ppr.id_safra',
   					'operator' => '>=',
   					'value' => $this->getRequest()->getParam('id_safra_min')
   			);
   		}

   		if ($this->getRequest()->getParam('id_produto')) {
   			$where[] = array(
   				'field' => 'spr.id_produto',
   				'operator' => '=',
   				'value' => $this->getRequest()->getParam('id_produto')
   			);
   		}

		if ($this->getRequest()->getParam('ds_nome_proponente')) {
			$where[] = array(
				'field' => 'spt.ds_nome_proponente',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_nome_proponente').'%'
			);
		}

		if ($this->getRequest()->getParam('ds_cpf_proponente')) {
			$where[] = array(
				'field' => 'spt.cpf_cnpj',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('ds_cpf_proponente')
			);
		}

		if ($this->getRequest()->getParam('id_pendencia')) {
			$where[] = array(
				'field' => 'id_pendencia',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_pendencia')
			);
		}

        $where[] = [
          'field' => 'sst.ds_chave',
          'operator' => '=',
          'value' => 'APOLICE_EMITIDA'
        ];

        $where[] = [
          'field' => 'spe.fl_proposta_vigente',
          'operator' => '=',
          'value' => true
        ];

		return $where;
	}

	public function excelAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		$where = $this->getFilter();

		$Model = new Seguro_Model_Propostas();

		if ($this->getRequest()->getParam("o")) {
			$Model->_order = trim($this->getRequest()->getParam("o") .' '. $this->getRequest()->getParam("s"));
		}

		$Rs = $Model->fetchAllPaginator($where, $this->getRequest()->getParam('page'), null, $this->_paginator);

		$this->view->paginator = $Rs;
		$colunas = [
			'id' => 'Cod.',
			'ds_nome_proponente' => 'Nome',
			'ds_nome_abreviado' => 'Produto',
			'dt_vigencia_inicio' => 'Início Vigência',
			'ds_status' => 'Status',
			'ds_nome_municipio' => 'Município/U'
		];

		$Csv = new Agro_Plugin_Rs2Csv();
		$Csv->setTitles($colunas);
		$Csv->setRecordSet($Rs);
		$Csv->setType("application/octet-stream");
		$Csv->setFileName("renovacao.csv");
		$Csv->setDisposition("attachment");
		$Csv->setSeparator(";");
		$Csv->getCsv();
	}

	public function listAction() {
		$this->getHelper('layout')->disableLayout();
		$where = $this->getFilter();

		$Model = new Seguro_Model_Propostas();

		if ($this->getRequest()->getParam("o")) {
			$Model->_order = trim($this->getRequest()->getParam("o") .' '. $this->getRequest()->getParam("s"));
		}

        if (array_key_exists('show_paginacao', $this->getRequest()->getParams())) {
            $this->_paginator = $this->getRequest()->getParam('show_paginacao');
        }

		$recordsPerPage = ($this->recordsPerPage ? $this->recordsPerPage :  RECORDS_PER_PAGE);
		$Rs = $Model->fetchAllPaginator($where, $this->getRequest()->getParam('page'), $recordsPerPage, $this->_paginator);

		if ($this->_columnList) {
			$this->getHelper('ViewRenderer')->setNoRender();

			$List = new Agro_List_Table($this->_columnList, $Rs, $this->_paginator, $this->getRequest());
			$this->getResponse()->setBody($List->toString());
		} else {
			$this->view->paginator = $Rs;
		}
	}

	public function renovarAction() {
		$this->getHelper('layout')->disableLayout();

		$Model = new Seguro_Model_Propostas();
		$Proposta = $Model->get($this->getRequest()->getParam('id'));

		$corretor = $Proposta->corretor();
		$params['id_corretor'] = $corretor['id_usuario'];
		if($Proposta->corretores_renovacao()){
		    $corretor = $Proposta->corretores_renovacao();
		    $params['id_corretor'] = $corretor[0]['id_usuario'];
		}
		$preposto = $Proposta->preposto();
		$produto  = $Proposta->produto();


		$params['id_preposto']      = $preposto['id_usuario'];
		$params['id_produto_geral'] = $produto['id_produto_geral'];
		$params['id_produto']       = $produto['id'];

		$this->view->id_proposta = $this->getRequest()->getParam('id');
		$this->view->produtos = $Model->getProdutosRenovacao($params,$Proposta->inadimplente());
	}

	public function copiarloteAction() {
		$this->isAjax();
		$result['message'] = null;
		$result['status'] = false;

		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$Model = new Seguro_Model_Renovacao();
		$result = array();

		$novoOrcamentoNovosDados = $this->getRequest()->getParam('novos_dados') ? true : false;

		if ($novoOrcamentoNovosDados) {
			$id = $Model->copyNovoOrcamento($this->getRequest()->getParams());
			//$message = $id;
		} else {
			$id = $Model->copy($this->getRequest()->getParams(), true);
			//$message = 'Renovação efetuada: '.$id;
		}

		if ($id) {
			$result['message'] = $id;
			$result['status'] = true;
		}
		$this->getResponse()->setBody(Zend_Json::encode($result));
	}

	public function copiarAction() {
		//tarefa 2335
		$Atributo = new Produto_Model_Atributos();
		$nro_safras_retroativas = $Atributo->getAtributoByChaveProduto('PROD_SAFRAS_RENOVACAO', $this->getRequest()->getParam('id_produto'));
		$ModelProposta = new Seguro_Model_Propostas();
		$Proposta = $ModelProposta->find($this->getRequest()->getParam('id_proposta'))->current();
		$ProdutoOld = $Proposta->produto();
		$safra_old = $ProdutoOld['id_safra'];

		$ModelSafra = new Produto_Model_Safras();
		$safra = $ModelSafra->getSafraByProduto($this->getRequest()->getParam('id_produto'));

		$diff_safras = $safra - $safra_old;

		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		if ($diff_safras <= $nro_safras_retroativas) {

			$Model = new Seguro_Model_Renovacao();
			$result = array();

			try {
				$id = $Model->copy($this->getRequest()->getParams(), true);
				if ($id) {
					$this->getResponse()->setBody("location.href='/seguro/proposta/edit/id/$id'");
				} else {
					$this->getResponse()->setBody("alert('".$Model->getMessages()."')");
				}
			} catch (Exception $e) {
				$this->getResponse()->setBody("alert('{$e->getMessage()}')");
			}
		} else {
			$this->getResponse()->setBody("alert('O produto selecionado não permite renovar propostas da safra escolhida.');");
		}
	}

	public function copiarorcamentoAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$Model = new Seguro_Model_Renovacao();
		$result = array();

		try {
			$id = $Model->copy($this->getRequest()->getParams(), false);
			if ($id) {
				$this->getResponse()->setBody(Zend_Json::encode($id));
			} else {
				$this->getResponse()->setBody("alert('".$Model->getMessages()."')");
			}
		} catch (Exception $e) {
			$this->getResponse()->setBody("alert('{$e->getMessage()}')");
		}
	}
}
