<?php

class Comercializacao_TaxacarController extends Agro_Controller_TaxaAgrupamento {
	public $_columnList = false;
	public $_tipo = 'C';
	
	public function init() {
		$this->view->title = 'Produto » Taxas » Propriedade';
	
		$Session = new Zend_Session_Namespace('agrupamento');
		$Session->unsetAll();
	}
	
	public function getModel() {
		return new Comercializacao_Model_TaxasAgrupamentos();
	}
	
	public function getFilter() {
		$where = array();
		
		$where[] = array(
			'field' => 'tp_taxa_agrupamento',
			'operator' => '=',
			'value' => $this->_tipo
		);

        if ($this->getRequest()->getParam('id_taxa')) {
            $where[] = array(
              'field' => 'c.id',
              'operator' => '=',
              'value' => $this->getRequest()->getParam('id_taxa')
            );
        }
		
		if ($this->getRequest()->getParam('id_safra')) {
			$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('ds_nome_agrupamento_taxas')) {
			$where[] = array(
				'field' => 'ds_nome_agrupamento_taxas',
				'operator' => 'ilike',
				'value' => '%' . $this->getRequest()->getParam('ds_nome_agrupamento_taxas') . '%'
			);
		}

		if ($this->getRequest()->getParam('ds_numero_car')) {
			$where[] = array(
				'field' => 'ds_car',
				'operator' => 'ilike',
				'value' => '%' . Agro_Util::carUnmask($this->getRequest()->getParam('ds_numero_car')) . '%'
			);
		}
		
		if($this->getRequest()->getParam('fl_ativo')) {
			$where[] = array(
				'field' => 'c.fl_ativo',
				'operator' => ' = ',
				'value' =>  $this->getRequest()->getParam('fl_ativo')
			);
		}

		return $where;
	}
	
	public function relacionacarAction()
	{
		$this->getHelper('layout')->disableLayout();
		
		$this->view->id_taxa_agrupamento = $this->getRequest()->getParam('id');
		$this->view->tipo = $this->getRequest()->getParam('tipo');
		// $this->view->id_produto = $this->getRequest()->getParam('id_produto');
		$this->view->carRelacionados = (new Comercializacao_Model_TaxasAgrupamentoCar())->getCarRelacionados($this->view->id_taxa_agrupamento);
	}

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

		$params = $this->getRequest()->getParams();
		
		$modelCar = new Comercializacao_Model_TaxasAgrupamentoCar();
		$response = [];
		
		try {
			if (empty($params['ds_car'])) {
				throw new Exception('Número da propriedade (CAR) não foi informado.');
			}

			$aux[] = [
				'ds_car' => Agro_Util::carUnmask($params['ds_car'])
			];

			$car = (new Comercializacao_Model_TaxasAgrupamentoCar())
				->getCarsRelacionadosPorTaxaAgrupamento($params['id_taxa_agrupamento'], $aux);
			
			if (!empty($car)) {
				throw new Exception("O número de CAR {$params['ds_car']} já encontra-se vinculado a uma taxa de agrupamento.");
			}
			
			$id = $modelCar->save($params);

			if (!$id) {
				throw new Exception ('Erro ao salvar propriedade.');
			}

			$response['id_car'] = $id;
			$response['status'] = true;
		} catch (Exception $e) {
			$response['message'] = $e->getMessage();
			$response['status'] = false;
		}

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

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

		$response = [];

		try {
			$id = $this->getRequest()->getParam('id');
			
			if (empty($id)) {
				throw new Exception('ID não informado.');
			}

			$deletado = (new Comercializacao_Model_TaxasAgrupamentoCar())->deletar((int) $id);

			if (!$deletado) {
				throw new Exception('Erro ao tentar deletar propriedade.');
			}

			$response['status'] = true;

		} catch (Exception $e) {
			$response['message'] = $e->getMessage();
			$response['status'] = false;
		}

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

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

		try {
			$allowedExtensions = ['csv'];
			$carArray = [];
			
			foreach ($_FILES as $file) {
				$aux = explode('.', $file['name']);
				$extension = $aux[count($aux) - 1];

				if (!in_array($extension, $allowedExtensions)) {
					throw new Exception('Só permitido realizar upload de arquivos .csv.');
				}
				
				$linha = 0;
				
				if (($open = fopen($file['tmp_name'], "r")) !== false) {
					while (($data = fgetcsv($open, 0, ',')) !== FALSE) {
						$row = explode(';', $data[0]);
						
						if ($linha == 0) {
							$row[0] = preg_replace("/\xEF\xBB\xBF/", "", $row[0]);
							$row[1] = preg_replace("/\xEF\xBB\xBF/", "", $row[1]);

							if ($row[0] != 'numero_car' || $row[1] != 'vl_produtividade_esperada') {
								throw new Exception("Importação inválida. O arquivo deve conter duas colunas com o cabeçalho na seguinte ordem:\n1ª - numero_car\n2ª - vl_produtividade_esperada");
							}

							++$linha;
							continue;
						}
						
						if (!array_filter($row)) {
							continue;
						}
						
						$numeroCar = Agro_Util::carUnmask($row[0]);
						$produtividadeEsperada = $row[1];

						$carArray[] = [
							'ds_car' => $numeroCar,
							'vl_produtividade_esperada' => $produtividadeEsperada
								? str_replace(',', '.', $produtividadeEsperada)
								: 'null'
						];
					}

					fclose($open);
				}

			}
			
			if (empty($carArray)) {
				throw new Exception('Nenhuma propriedade informada no arquivo para importar.');
			}

			$taxasAgrupamentoCar = new Comercializacao_Model_TaxasAgrupamentoCar();
			$taxasAgrupamentoCar->vincularCar(
				(int) $this->getRequest()->getParam('id'),
				$carArray
			);

			$carVinculados = $taxasAgrupamentoCar->getCarRelacionados((int) $this->getRequest()->getParam('id'));
			
			$return = [
				'statusCode' => 200,
				'carVinculados' => $carVinculados->toArray(),
				'message' => 'Propriedades importadas com sucesso',
				'status' => true
			];
		} catch(Exception $e) {
			$return = [
				'statusCode' => 406,
				'message' => $e->getMessage(),
				'status' => false
			];
		}

		
		$this->getResponse()->setBody(Zend_Json::encode($return));
	}
	
	public function listAction() {
		$this->getHelper('layout')->disableLayout();
		$where = $this->getFilter();
		$Model = new Comercializacao_Model_TaxasAgrupamentoCar();

        if (array_key_exists('show_paginacao', $this->getRequest()->getParams())) {
            $this->_paginator = $this->getRequest()->getParam('show_paginacao');
        }

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

        $Session = new Zend_Session_Namespace('filtro');
        $Session->{$Module}->{$Controller} = $this->getRequest()->getParams();

        if ($this->getRequest()->getParam("o")) {
            $Model->_order = trim($this->getRequest()->getParam("o") .' '. $this->getRequest()->getParam("s"));
        }
		
        $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 geraxlsAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$dados = $this->getRequest()->getParams();
		$Model = new Comercializacao_Model_TaxasAgrupamentos();
		
		$ret = $Model->getTaxaCarXls($dados);
		require_once(APPLICATION_PATH . "/../library/Agro/xls/PhpSimpleXlsGen.php");
		
		$myxls = new PhpSimpleXlsGen();
		$myxls->totalcol = 7;
		
		// $myxls->InsertText('CPF/CNPJ');
		$myxls->InsertText('Nome');
		$myxls->InsertText('Produto');
		$myxls->InsertText('Cobertura');
		$myxls->InsertText('Valor Franquia');
		$myxls->InsertText('Valor Taxa');
		$myxls->InsertText('Estado');
		
		foreach($ret as $linha) {
			// $myxls->InsertText(utf8_decode($linha['cpf_cnpj']) . ' ');
			$myxls->InsertText(utf8_decode($linha['ds_nome_agrupamento_taxas']) . ' ');
			$myxls->InsertText(utf8_decode($linha['ds_nome_produto']) . ' ');
			$myxls->InsertText(utf8_decode($linha['ds_nome_cobertura']) . ' ');
			$myxls->InsertText(utf8_decode($linha['vl_franquia']) . ' ');
			$myxls->InsertText(utf8_decode($linha['vl_taxa']) . ' ');
			$myxls->InsertText(utf8_decode($linha['ds_sigla']) . ' ');
		}
		
		$myxls->SendFile();
	}	

	public function excelAction() {

		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		ini_set('memory_limit','4096M');
		ini_set('max_execution_time',360);
		
		$where = $this->getFilter();
		$Model = new Comercializacao_Model_TaxasAgrupamentoCar();
		
		if ($this->getRequest()->getParam("o")) {
			$Model->_order = trim($this->getRequest()->getParam("o") .' '. $this->getRequest()->getParam("s"));
		}

		$Rs = $Model->fetchAll($Model->getDataExcel($where));
		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();
		}
	}

    public function propostascomtaxaAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();

        $rows = (new Seguro_Model_Propostas())->getPropostasComTaxaCar(
            ['sp.id_proposta_mae'],
            ['ps.fl_vigente is true']
        )->toArray();

        file_put_contents(APPLICATION_PATH . '/upload_files/temp/propostascomtaxacar.csv', "Proposta\n");

        foreach ($rows as $proposta) {
            file_put_contents(
                APPLICATION_PATH . '/upload_files/temp/propostascomtaxacar.csv',
                "{$proposta['id_proposta_mae']}\n",
                FILE_APPEND
            );
        }
    }

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

        $adapter = Agro_Db_Table_Abstract::getDefaultAdapter();
        $this->_return['mensagem'] = 'Propriedades excluídas com sucesso.';

        try {
            $adapter->beginTransaction();

            if (empty($this->getRequest()->getParam('idsPropriedadesSelecionadas'))) {
                throw new InvalidArgumentException('Nenhuma propriedade informada.', 1);
            }

            (new Comercializacao_Service_TaxasAgrupamentoCar())->excluirpropriedadesrelacionadas(
                explode(',', $this->getRequest()->getParam('idsPropriedadesSelecionadas'))
            );

            $adapter->commit();
        } catch (Exception $exception) {
            $adapter->rollBack();

            $this->_return['erro'] = true;
            $this->_return['mensagem'] = 'Erro ao excluir as propriedades relacionadas.';

            if ($exception->getCode() > 0) {
                $this->_return['mensagem'] = $exception->getMessage();
            }
        }

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