<?php

declare(strict_types=1);

class Sinistro2_ParametrotipodespesaController extends Agro_Controller_Action
{
    public function indexAction(): void
    {
        parent::indexAction();
		$this->view->title = 'Sinistro » Cobrança » Configurações » Parâmetros Tipos Despesa';	
    }

    public function getModel(): Sinistro2_Model_ParametroTipoDespesa
    {
		return new Sinistro2_Model_ParametroTipoDespesa();
	}

    public function getForm(): Sinistro2_Form_ParametroTipoDespesa
    {
		return new Sinistro2_Form_ParametroTipoDespesa();
	}

	public function formAction(): void
	{
		$id = $this->getRequest()->getParam('id');
		
		if (!empty($id)) {
			$parametroTipoDespesa = $this->getModel()->find($id)->current();

			$this->view->id = $parametroTipoDespesa['id'];
			$this->view->ds_parametro_tipo_despesa = $parametroTipoDespesa['ds_parametro_tipo_despesa'];
			$this->view->vl_minimo = $parametroTipoDespesa['vl_minimo'];
			$this->view->vl_maximo = $parametroTipoDespesa['vl_maximo'];
			$this->view->fl_anexo_obrigatorio = $parametroTipoDespesa['fl_anexo_obrigatorio'];
		}

		parent::formAction();
	}

	public function getparametrostiposdespesabyestadoAction(): void
	{
		$this->isAjax();
		
		try {
			$rs = $this->getModel()->getParametrosTiposDespesaByIdEstado((int) $this->getRequest()->getParam('idEstado'));
			
			$this->getResponse()->setBody(Zend_Json::encode([
				'parametrosTiposDespesa' => $rs,
				'status' => true
			]));
		} catch (Exception $e) {
			$this->getResponse()->setBody(Zend_Json::encode([
				'message' => $e->getMessage(),
				'status' => false
			]));
		}
	}
	
	public function getestadosvinculadosAction(): void
	{
		$this->isAjax();

		try {
			$rs = $this->getModel()->getEstadosVinculados((int) $this->getRequest()->getParam('id'));
			
			$this->getResponse()->setBody(Zend_Json::encode([
				'estados' => $rs,
				'status' => true
			]));
		} catch (Exception $e) {
			$this->getResponse()->setBody(Zend_Json::encode([
				'message' => $e->getMessage(),
				'status' => false
			]));
		}
	}

	public function listAction(): void
	{
		$this->_paginator = (bool) $this->getRequest()->getParam('show_paginacao');
	    parent::listAction();
	}

	public function getFilter()
	{
		$params = $this->getRequest()->getParams();
		if (!empty($params['id_estado'])) {
			$where[] = [
				'field' => 'sptd.id',
				'operator' => 'in',
				'value' => '
					(
						SELECT
							sptde2.id_parametro_tipo_despesa
						FROM
							sinistro.parametro_tipo_despesa_estado sptde2
						WHERE sptde2.id_estado IN ('. implode(', ', $params['id_estado']). ')
					)'
			];
		}
		
		return $where;
	}

	public function salvarAction(): void
	{
		$this->isAjax();

		$params = $this->getRequest()->getParams();
		$retorno = ['message' => 'Tipo de despesa salvo com sucesso!', 'status' => true];

		$adapter = Agro_Db_Table_Abstract::getDefaultAdapter();

		try {
			$adapter->beginTransaction();
			
			if (!empty($params['id']) && !filter_var($params['id'], FILTER_VALIDATE_INT))  {
				throw new Exception('ID deve ser um inteiro.');
			}

			if (!empty($params['id_tipo_despesa']) && !filter_var($params['id_tipo_despesa'], FILTER_VALIDATE_INT))  {
				throw new Exception('ID tipo despesa deve ser um inteiro.');
			}
	
			if (!empty($params['vl_minimo']) && !filter_var($params['vl_minimo'], FILTER_VALIDATE_FLOAT))  {
				throw new Exception('Valor mínimo deve ser um número.');
			}
	
			if (!empty($params['vl_maximo']) && !filter_var($params['vl_maximo'], FILTER_VALIDATE_FLOAT))  {
				throw new Exception('Valor máximo deve ser um número.');
			}
			
			foreach ($params['ids_estado'] as $id) {
				if (!filter_var($id, FILTER_VALIDATE_INT)) {
					throw new Exception('IDs estado devem ser inteiros.');
				}
			}
			
			$mensagemErro = '';

			if (empty($params['id_tipo_despesa'])) {
				$mensagemErro = "Campo Tipo Despesa é obrigatório.\n";
			}
			
			if (empty($params['ds_parametro_tipo_despesa'])) {
				$mensagemErro = "Campo Descirção Parâmetro Tipo Despesa é obrigatório.\n";
			}
	
			if (empty($params['ids_estado'])) {
				$mensagemErro .= "Necessário vincular pelo menos um estado.\n";
			}
	
			if (strlen($params['ds_parametro_tipo_despesa']) > 60) {
				$mensagemErro .= "Descrição deve ter no máximo 60 caracteres.\n";
			}
			
			if (!empty($mensagemErro)) {
				throw new Exception($mensagemErro);
			}
			
			(new Sinistro2_Model_ParametroTipoDespesa)->save($params);
			
			$adapter->commit();
			
		} catch (Exception $e) {
			$adapter->rollback();

			$retorno = ['message' => $e->getMessage(), 'status' => false];
			$this->getResponse()->setHttpResponseCode(406);
		}

		$this->getResponse()->setBody(Zend_Json::encode($retorno));
	}

	public function getunidadeAction(): void
	{
		$this->isAjax();

		try {
			$idParametroTipoDespesa = (int) $this->getRequest()->getParam('idParametroTipoDespesa');

			if (empty($idParametroTipoDespesa)) {
				throw new Exception('ID tipo despesa é obrigatório.', 400);
			}

			if (!filter_var($idParametroTipoDespesa, FILTER_VALIDATE_INT)) {
				throw new Exception('ID tipo despesa deve ser um inteiro.', 400);
			}

			$parametroTipoDespesa = $this->getModel()->find($idParametroTipoDespesa)->current();
			$tipoDespesa = (new Sinistro2_Model_TipoDespesa())->find($parametroTipoDespesa['id_tipo_despesa'])->current();

			if (empty($parametroTipoDespesa)) {
				throw new Exception('Tipo de despesa não encontrado.', 404);
			}

			$retorno = ['message' => 'Sucesso', 'ds_unidade' => $tipoDespesa['ds_unidade'], 'status' => true];
		} catch (Exception $e) {
			$retorno = ['message' => $e->getMessage(), 'status' => false];
			$this->getResponse()->setHttpResponseCode($e->getCode());
		}

		$this->getResponse()->setBody(Zend_Json::encode($retorno));
	}

	public function getidstiposdespesaAction(): void
	{
		$this->isAjax();
		
		$retorno = ['status' => true];
		$model = new Sinistro2_Model_TipoDespesa();

		try {
			$retorno['tiposDespesa'] = $model->fetchAll(
				$model->select()->from($model, ['id', 'ds_tipo_despesa'])
			)->toArray();
		} catch (Exception $e) {
			$retorno = ['message' => $e->getMessage(), 'status' => false];
			$this->getResponse()->setHttpResponseCode($e->getCode());
		}

		$this->getResponse()->setBody(Zend_Json::encode($retorno));
	}

	public function excelAction() 
	{
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		ini_set('memory_limit','4096M');
		ini_set('max_execution_time', '360');
		
		$model = $this->getModel();
		
		$params = $this->getRequest()->getParams();

		$descricaoParametrotipoDespesa = $params['ds_tipo_despesa'] ?? '';
		$idsEstado = $params['id_estado'] ?? [];

		$Rs = $model->getParametrosTiposDespesa($descricaoParametrotipoDespesa, $idsEstado);
		
		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();
		}
	}
}