<?php
require_once 'atendimento/controllers/PropostaController.php';

class ScriptsController extends Zend_Controller_Action{

	public function init() {
		$this->getHelper('layout')->disableLayout();
		ini_set('memory_limit','10240M');
	}
	
	public function kmlAction() {
		if ($this->getRequest()->getParam('proposta')) {
			$Propostas = new Seguro_Model_Propostas();
			$Proposta = $Propostas->find($this->getRequest()->getParam('proposta'))->current();

			$this->view->propriedade = $Proposta->propriedade();
			$this->view->proposta = $Proposta;

			unset($this->view->propriedade['ds_referencia_localizacao']);

			if (empty($this->getRequest()->getParam('id_solicitacao'))) {
			    $this->view->quadras = $Proposta->itens_segurados();
            }

			$proposta = empty($this->getRequest()->getParam('id_solicitacao')) ? $this->getRequest()->getParam('proposta') : null;
			$idSolicitacao = !empty($this->getRequest()->getParam('id_solicitacao')) ? $this->getRequest()->getParam('id_solicitacao') : null;

			$this->view->geocroquis = $this->geoCroquiToKml($proposta, $idSolicitacao);

			$filename = $this->getRequest()->getParam('proposta');

			if (!empty($this->getRequest()->getParam('id_solicitacao'))) {
                $filename = $this->getRequest()->getParam('proposta') . "_" . $this->getRequest()->getParam('id_solicitacao');
            }

            $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
            $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $filename .'.kml', true);
            $this->getResponse()->setHeader('Pragma', 'no-cache', true);
            $this->getResponse()->sendResponse();
		}
	}

	public function kmlauditoriasinistroAction() {

		if ($this->getRequest()->getParam('propostas')) {

		    $Propostas = new Seguro_Model_Propostas();

		    foreach($this->getRequest()->getParam('propostas') as $proposta){
		        $Proposta = $Propostas->find($proposta)->current();
		        $arrProposta[] = $Proposta;
		    }

			$this->view->proposta = $arrProposta;

			$this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
			$this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . 'auditoria_sinistro.kml', true);
			$this->getResponse()->setHeader('Pragma', 'no-cache', true);
			$this->getResponse()->sendResponse();
		}
	}


	public function kmlpreviaAction() {
		if ($this->getRequest()->getParam('proposta')) {

		    $ModelSafras = new Produto_Model_Safras();
			$Propostas   = new Seguro_Model_Propostas();

			$Proposta = $Propostas->find($this->getRequest()->getParam('proposta'))->current();

			$model = $ModelSafras->getSafraModel($Proposta->id, "Lvp001ItensSegurados");
			$ModelLvp001IS = new $model();

			$this->view->propriedade = $Proposta->propriedade();
			$this->view->quadras = $ModelLvp001IS->get(array('id_laudo' => $this->getRequest()->getParam('id_laudo')));
			$this->view->proposta = $Proposta;

			$this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
			$this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $Proposta->id.'.kml', true);
			$this->getResponse()->setHeader('Pragma', 'no-cache', true);
			$this->getResponse()->sendResponse();
		}
	}

	public function kmlquadraAction() {
		if ($this->getRequest()->getParam('coordenada')) {
			$Propostas = new Seguro_Model_Propostas();
			$Proposta = $Propostas->find($this->getRequest()->getParam('proposta'))->current();

			$this->view->propriedade = $Proposta->propriedade();
			$this->view->quadra = $this->getRequest()->getParam('coordenada');
			$this->view->proposta = $Proposta;

			$this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
		    $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $Proposta->id.'.kml', true);
		    $this->getResponse()->setHeader('Pragma', 'no-cache', true);
		    $this->getResponse()->sendResponse();
		}
	}

	public function mapsAction() {
		$options = $this->getFrontController()->getParam('bootstrap')->getApplication()->getOptions();
		$this->view->key = $options['gdata']['mapskey'];

		if ($this->getRequest()->getParam('proposta')) {
			if ($this->getRequest()->getParam('quadra')) {
				$Itens = new Seguro_Model_ItensSegurados();
				$this->view->quadra = $Itens->find($this->getRequest()->getParam('quadra'))->current();
			} else {
				$Propostas = new Seguro_Model_Propostas();
				$Proposta = $Propostas->find($this->getRequest()->getParam('proposta'))->current();
				$this->view->propriedade = $Proposta->propriedade();
				$this->view->rows = $Proposta->itens_segurados();
			}
		} elseif ($this->getRequest()->getParam('coordenada')) {
			$this->view->coordenada = $this->getRequest()->getParam('coordenada');
		}
	}

	public function endossoAction() {
		$this->getHelper('ViewRenderer')->setNoRender();

		$Propostas = new Default_Model_Proposta();
		$Propostas->criaEndossos();
	}

	public function queryAction() {
		//delete from seguro.propostas_arquivos where id_proposta=110644
		$Db = Zend_Db_Table_Abstract::getDefaultAdapter();

		if ($this->getRequest()->getParam('query')) {
			$Db->query($this->getRequest()->getParam('query'));
		}
	}

	public function versionamentoAction() {
		$Rs = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll("select id from seguro.propostas where id_versao is null");
		$this->getHelper('ViewRenderer')->setNoRender();

		foreach ($Rs as $Row) {
			if (Agro_Db_Table_Abstract::getDefaultAdapter()->insert("seguro.propostas_versoes", array('id_usuario_criacao' => Zend_Auth::getInstance()->getIdentity()->id, 'id_proposta' => $Row['id']))) {
				$versao = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select id from seguro.propostas_versoes where id_proposta = {$Row['id']}");

				Agro_Db_Table_Abstract::getDefaultAdapter()->query("update seguro.propostas set id_versao = $versao where id = {$Row['id']}");
				echo "PROPOSTA $proposta VERSIONADA.";
				flush();
			}
		}
	}

	public function zerapropostaAction() {
		$this->getHelper('ViewRenderer')->setNoRender();

		if ($this->getRequest()->getParam('id')) {
			$id = $this->getRequest()->getParam('id');
			$processo = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select id from sinistro.processos where id_proposta = $id");

			if ($processo) {
				Agro_Db_Table_Abstract::getDefaultAdapter()->query("delete from sinistro.laudos_finais_itens_segurados where id_laudo_final in (select id from sinistro.laudos_finais where id_processo = $processo)");
				Agro_Db_Table_Abstract::getDefaultAdapter()->query("delete from sinistro.laudos_finais where id_processo = $processo");
				Agro_Db_Table_Abstract::getDefaultAdapter()->query("delete from sinistro.laudos_preliminares_itens_segurados where id_laudo_preliminar in (select id from sinistro.laudos_preliminares where id_processo = $processo)");
				Agro_Db_Table_Abstract::getDefaultAdapter()->query("delete from sinistro.laudos_preliminares where id_processo = $processo");
				Agro_Db_Table_Abstract::getDefaultAdapter()->query("delete from sinistro.processos_empresas where id_processo = $processo");
			} else {
				throw new Exception('Nenhum processo encontrado.');
			}
		}
	}

	public function kmlavisosinistroAction() {

		if ($this->getRequest()->getParam('id_aviso')) {

			$this->view->tipo_mapa = $this->getRequest()->getParam('tipo_mapa');

	    	$Model     = new Sinistro2_Model_AvisosSinistro();
			$Propostas = new Seguro_Model_Propostas();

			$arrPropostas = array();

			foreach ($this->getRequest()->getParam('id_aviso') as $key => $id_aviso){
				$RowProposta = $Model->getIdPropostaMaeByIdAviso($id_aviso);
				//$arrPropostas[$key] = $Model->getIdPropostaByIdAviso($id_aviso);

				$Proposta           = $Propostas->find($RowProposta[0]['id_proposta'])->current();
				$arrPropostas[$key] = $Proposta;

				$nomeArquivo .= $RowProposta[0]['id_proposta_mae']."-";
			}

			$this->view->proposta = $arrPropostas;

			$this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
			$this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $nomeArquivo.'.kml', true);
			$this->getResponse()->setHeader('Pragma', 'no-cache', true);
			$this->getResponse()->sendResponse();
		}
	}

	public function kmlsolicitacaopreviaAction() {
		if ($this->getRequest()->getParam('id_proposta')) {

		    $Propostas = new Seguro_Model_Propostas();

		    foreach($this->getRequest()->getParam('id_proposta') as $proposta){
		        $Proposta = $Propostas->find($proposta)->current();
		        $arrProposta[] = $Proposta;
				$nomeArquivo .= $Proposta->id."-";
		    }

			$this->view->proposta = $arrProposta;

			$this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
			$this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="'.$nomeArquivo.'.kml', true);
			$this->getResponse()->setHeader('Pragma', 'no-cache', true);
			$this->getResponse()->sendResponse();
		}
	}

	private function geoCroquiToKml($id_proposta = null, $idSolicitacao = null) {
		$arCroqui = array();
		$i = 0;

		$metodo = !empty($id_proposta) ? "getCroquis" : "getCroquisSolicitacao";
		$parametro = !empty($id_proposta) ? $id_proposta : $idSolicitacao;

		$ModelPropostasCroqui = new Seguro_Model_PropostasCroquis();
		$propostaCroquis = $ModelPropostasCroqui->{$metodo}($parametro);

		foreach ($propostaCroquis as $g) {
			$coords = '';
			$coordenadas = json_decode($g['ds_coordenadas'], true);
			foreach ($coordenadas as $coord) {
				$coords .= ' '.$coord['longitude'].','.$coord['latitude'].',0';
			}

			$coords .= ' '.$coordenadas[0]['longitude'].','.$coordenadas[0]['latitude'].',0';

			$arCroqui[$i]['coords'] = $coords;
			$arCroqui[$i]['ds_nome'] = $g['ds_nome'];
			$i++;
		}

		return $arCroqui;
	}

	public function watermarkAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
        
        $result['status'] = false;
        $result['message'] = "Marca d'água não gerada.";

		$arTmp = explode('/', $this->getRequest()->getParam('imagepath'));
		$image = $arTmp[count($arTmp)-1];

        $wt = new Agro_Utils_Watermark(
            APPLICATION_PATH . '/upload_files/laudoprevia/' . $image
        );
        $wt->setFont('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf');
        
        if ($wt->generateWatermark()) {
            $result['status'] = true;
            $result['message'] = "Marca d'água gerada com sucesso!";
        }

        $this->getResponse()->setBody(Zend_Json::encode($result));
    }

	public function kmlpropostasAction()
	{
		$result = ['status' => true, 'name' => '', 'message' => "Agendada geração do KML. \nVocê receberá um e-mail com o arquivo em anexo quando concluído."];

		try {
			$user = Zend_Auth::getInstance()->getIdentity();
			$modelPropostas = new Seguro_Model_Propostas();
			$modelItensSegurados = new Seguro_Model_ItensSegurados();
			$propostaController = new Atendimento_PropostaController($this->getRequest(), $this->getResponse());
			$this->getHelper('layout')->disableLayout();
			$this->getHelper('ViewRenderer')->setNoRender();
			
			$dir = APPLICATION_PATH . "/upload_files/temp/";
			$arquivoLock = realpath($dir . 'gerar_kml_'. $user->id .'.lock');
        
			if (file_exists($arquivoLock)) {
				throw new Exception("Já existe um KML sendo gerado para o usuário. Aguarde o e-mail com o arquivo KML gerado ou tente novamente mais tarde.");
			}

			// Cria arquivo lock para não permitir o mesmo usuário gerar mais de um KML por vez
			file_put_contents($arquivoLock, date("d/m/Y H:i:s") . ' - Início do processamento');

			$maxItens = 20000;

			$where = $propostaController->getFilter();
			$where[] = array(
				'field' => 'spe.fl_proposta_vigente',
				'operator' => '=',
				'value' => true
			);

			$sql = $modelPropostas->getData($where);
			$propostas = $modelPropostas->fetchAll($sql);
			
			if (count($propostas) == 0) {
				unlink($arquivoLock);
				throw new Exception("Nenhuma proposta encontrada para os filtros selecionados.");
			}

			if (count($propostas) > $maxItens) {
				unlink($arquivoLock);
				throw new Exception("Erro ao gerar o KML. Capacidade da geração excedida.");
			}

			$idsPropostas = [];
			foreach ($propostas as $proposta) {
				$idsPropostas[] = $proposta->id;
			}

			$totalItens = $modelItensSegurados->fetchAll("id_proposta IN (". implode(', ', $idsPropostas) .")")->count();
			if ($totalItens > $maxItens) {
				unlink($arquivoLock);
				throw new Exception("Erro ao gerar o KML. \nTotal de itens ({$totalItens}) excede o limite máximo de {$maxItens}.");
			}

			$parametros = [
				$user->id,
				implode(",", $idsPropostas)
			];
			Agro_Util::generateAtscript("gerarkmlpropostas.php", $parametros, 'now');


		} catch (\Throwable $th) {
			$result['status'] = false;
			$result['message'] = $th->getMessage();
		}

		$result['name'] = $this->view->name;
		$this->getResponse()->setBody(Zend_Json::encode($result));
	}

	private function getDadosKMLbyProposta($idProposta) 
	{
		$modelPropostas = new Seguro_Model_Propostas();
		$Proposta = $modelPropostas->find($idProposta)->current();
		$dados = new stdClass();
		$dados->proposta = $Proposta;
		$doc = $dados->proposta->doc();
		$dados->propostaCompleta = (!empty($doc)) ? $doc : $idProposta;
		$dados->propriedade = $Proposta->propriedade();
		$dados->cultura = $Proposta->cultura();
		$dados->quadras = $Proposta->itens_segurados();
		$dados->geocroquis = $this->geoCroquiToKml($idProposta);		
		unset($dados->propriedade['ds_referencia_localizacao']);
		return $dados;
	}

	public function gerarkmlpropostasAction()
	{
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$result = ['status' => true, 'message' => 'Arquivo gerado com sucesso.'];

		try {
            $idUsuario = !Agro_Util::filterVariable($this->getRequest()->getParam('id_usuario'))
                ? 0
                : (int)$this->getRequest()->getParam('id_usuario');
			$idsPropostas = $this->getRequest()->getParam('ids_propostas');
			$idsPropostas = explode(",", $idsPropostas);
	
			$modelFuncionarios = new Sistema_Model_Funcionarios();
			$funcionario = $modelFuncionarios->fetchRow("id_usuario = $idUsuario");
	
			$dir = APPLICATION_PATH . "/upload_files/temp/";
			$arquivoLock = $dir . 'gerar_kml_'. $idUsuario .'.lock';
			$arquivoKML = $dir . "kml_propostas_" . time() . "_" . $idUsuario .".kml";
			
			// Remove todos os arquivos kml do usuário
			array_map('unlink', array_filter((array) glob($dir . "kml_propostas_*_". $idUsuario .".kml")));
			
			$this->view->dadosKML = [];
			foreach ($idsPropostas as $idProposta) {
				$this->view->dadosKML[] = $this->getDadosKMLbyProposta($idProposta);
			}
			
			$texto = $this->view->render('scripts/kmlpropostas.phtml');
			file_put_contents($arquivoKML, $texto);
	
			if (!empty($funcionario->ds_email)) {
				$anexoKML = new Zend_Mime_Part($texto);
				$anexoKML->type = mime_content_type($arquivoKML);
				$anexoKML->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
				$anexoKML->encoding = Zend_Mime::ENCODING_BASE64;
				$anexoKML->filename = basename($arquivoKML);
	
				$agroMail = new Agro_Mail();
				$agroMail->addTo([$funcionario->ds_email]);

				$body = "Segue em anexo o arquivo KML gerado.";

				if (APPLICATION_ENV != 'production') {
					$body .= "\n\n DEBUG(somente ambiente teste) - Esse e-mail seria enviado para: {$funcionario->ds_email} \n\n";
				}

				$agroMail->setBody($body);
				$agroMail->setSubject("Arquivo KML gerado com sucesso.");
				$agroMail->addAttachment($anexoKML);
				$agroMail->send();
			}
	
			unlink($arquivoLock);
		} catch (\Throwable $th) {
			$result['status'] = false;
			$result['message'] = $th->getMessage();
		}

		$this->getResponse()->setBody(Zend_Json::encode($result));
	}
}
