<?php

class Comercializacao_TaxavalorController extends Agro_Controller_Action {

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

	public function getForm() {
		$Model = $this->getModel();
		$this->view->taxas = $Model->getCoberturas();
		$this->view->show_taxas = $Model->getShowCoberturas();

		if ($this->getRequest()->getParam('id')) {
			$this->view->taxas_relacionadas = $Model->getCoberturasRelacionadas($this->getRequest()->getParam('id'));
		}

		return new Comercializacao_Form_TaxaValor();
	}

	public function init() {
		$Session = new Zend_Session_Namespace('agrupamento');

		if (!$Session->taxa['id']) {
			$Taxas = new Comercializacao_Model_Taxas();

			if ($this->getRequest()->getParam('id')) {
				$Taxa = $Taxas->find($this->getRequest()->getParam('id'))->current();
				$Session->taxa['id'] = $Taxa->id;
				$Session->taxa['id_produto'] = $Taxa->id_produto;
				$Session->taxa['ds_nome_agrupamento_taxas'] = $Taxa->ds_nome_agrupamento_taxas;
				$Session->taxa['tp_taxa_agrupamento'] = $Taxa->tp_taxa_agrupamento;
			}
		}

		if ($Session->taxa['tp_taxa_agrupamento'] == 'E') {
			$this->view->back = '/comercializacao/taxaestado';
		} else if ($Session->taxa['tp_taxa_agrupamento'] == 'M') {
			$this->view->back = '/comercializacao/taxamunicipio';
		} else if ($Session->taxa['tp_taxa_agrupamento'] == 'U') {
			$this->view->back = '/comercializacao/taxausuario';
		} else if ($Session->taxa['tp_taxa_agrupamento'] == 'P') {
			$this->view->back = '/comercializacao/taxaproponente';
		} else if ($Session->taxa['tp_taxa_agrupamento'] == 'O') {
            $this->view->back = '/comercializacao/taxaorcamento';
        } else if ($Session->taxa['tp_taxa_agrupamento'] == 'C') {
            $this->view->back = '/comercializacao/taxacar';
        }

		if ($Session->taxa['id']) {
			$this->view->title = "Gerência de Taxas » Valores";
			$this->view->ds_nome_agrupamento_taxas = $Session->taxa['ds_nome_agrupamento_taxas'];
		}
	}

	public function getFilter() {
		$Session = new Zend_Session_Namespace('agrupamento');
		$where = array();

		$where[] = array(
			'field' => 'id_taxa_agrupamento',
			'operator' => '=',
			'value' => $Session->taxa['id']
		);

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

		return $where;
	}

	public function settaxaAction() {
		$Session = new Zend_Session_Namespace('agrupamento');
		
		$Model = new Comercializacao_Model_TaxasAgrupamentos();
		$Session->taxa = $Model->find($this->getRequest()->getParam('id'))->current()->toArray();

		$this->_redirect('/comercializacao/taxavalor');
	}

	public function formAction() {
		$this->view->back = '/comercializacao/taxavalor';
		$this->view->form = $this->getForm();
		$this->view->title .= ' » Formulário';
		$Model = $this->getModel();

		if (!$this->view->back) {
			$this->view->back = "/{$this->_forwardSettings['module']}/{$this->_forwardSettings['controller']}";
		}

		if ($this->getRequest()->isPost()) {
			if ($this->view->form->isValid($this->getRequest()->getParams())) {
				$Row = $this->save($this->getRequest()->getParams());
			} else {
				$Errors = $this->view->form->getMessages();
				$this->view->showMessage($this->getHtmlFormError($Errors), 'error');
				$this->view->form->populate($this->getRequest()->getParams());
			}
		} else if ($this->getRequest()->getParam('id')) {
			$this->view->taxas_relacionadas = $Model->getCoberturasRelacionadas($this->getRequest()->getParam('id'));
			$row = $this->getRow();
			$this->view->form->populate($row);
		}
	}

	public function save(array $post) {
		$Session = new Zend_Session_Namespace('agrupamento');

		try {
			$Model = $this->getModel();
			$data = array(
				'id' => $post['id'],
				'id_taxa_agrupamento' => $Session->taxa['id'],
				'id_cobertura' => $post['id_cobertura'],
				'vl_franquia' => $post['vl_franquia'],
				'vl_taxa' => $post['vl_taxa'],
				'vl_produtividade_estimada' => ($post['vl_produtividade_estimada'] ? $post['vl_produtividade_estimada'] : null),
				'vl_taxa_renovacao' => $post['vl_taxa_renovacao'],
			    'vl_taxa_inadimplente' => $post['vl_taxa_inadimplente'],
				'vl_taxa_reduzida' => $post['vl_taxa_reduzida'],
				'vl_percentual_subvencao_federal' => $post['vl_percentual_subvencao_federal'],
				'fl_franquia_disponivel' => $post['fl_franquia_disponivel'],
				'fl_ativo' => $post['fl_ativo']
			);

			$id = $Model->save($data);
			if ($id) {
				if (is_array($post['relacionar']) && count($post['relacionar'])) {
					$Model->relacionarTaxas($post, $id);
				} else {
					$Model->relacionarTaxas($post, $id, true);
				}

				if (!$post['stay']) {
					$this->_redirect('/comercializacao/taxavalor');
				} else {
					$this->view->showMessage(MSG_SUCCESS, 'success');
				}
			} else {
				$this->view->showMessage(MSG_ERROR, 'error');
			}
		} catch (Exception $e) {
			$this->view->showMessage(MSG_ERROR, 'error', $e);
		}
	}

	public function gettaxasrelacionadasAction()
    {
        $this->isAjax();

        $taxasRelacionadas = $this->getModel()->getCoberturasRelacionadas($this->getRequest()->getParam('id'));

        $this->getResponse()->setBody(Zend_Json::encode(['taxasRelacionadas' => $taxasRelacionadas]));
    }

    public function gettaxavaloresbypropostacoberturaAction()
    {
        $this->isAjax();
        $parametros = $this->getRequest()->getParams();

        $modelPropostas = new Seguro_Model_Propostas();
        $rowProposta = $modelPropostas->getRow($parametros['id_proposta']);
        $taxaAgrupamento = $rowProposta->agrupamento(false);
        $taxaValores = $this->getModel()->getTaxasValoresByTaxaAgrupamento($taxaAgrupamento['id'], $parametros['id_cobertura'])->toArray();

        $this->getResponse()->setBody(Zend_Json::encode(
          ['taxaValores' => $taxaValores[0] ?? null, 'taxaAgrupamento' => $taxaAgrupamento]
        ));
    }
}
