<?php
require_once APPLICATION_PATH. "/../library/dompdf/autoload.inc.php";

use Dompdf\Dompdf;
use Mpdf\Http\Exception\ForbiddenRequestException;

class Agronet_FileController extends Agro_Controller_Action
{
	public function viewAction()
    {
        try {
            $this->getHelper('ViewRenderer')->setNoRender();
            $this->getHelper('layout')->disableLayout();

            $path = Agro_File::clearFileName($this->getRequest()->getParam('path'));
            $file = Agro_File::clearFileName($this->getRequest()->getParam('name'));

            if (!Agro_Util::validaDir($path)) {
                throw new ForbiddenRequestException('Diretório não existente');
            }

            $mime = Agro_Util::getMimeType($file);
            header('Content-Type: ' . $mime . '; charset=ISO-8859-1');

            echo file_get_contents(APPLICATION_PATH . "/upload_files/{$path}/{$file}");
        } catch (ForbiddenRequestException $e) {
            $this->_redirect('/agronet');
        }
    }

    public function viewcarrosselAction()
    {
        try {
            $this->getHelper('ViewRenderer')->setNoRender();
            $this->getHelper('layout')->disableLayout();

            $path = Agro_File::clearFileName($this->getRequest()->getParam('path'));
            $file = Agro_File::clearFileName($this->getRequest()->getParam('name'));
            $fileExtension = pathinfo($file)['extension'];
            
            if (!Agro_Util::validaDir($path)) {
                throw new ForbiddenRequestException('Diretório não existente');
            }

            if ($fileExtension == 'pdf') {
                header('Content-Type: application/pdf');
                header('Content-Disposition: inline; filename="' . basename($file) . '"');
                header('Content-Transfer-Encoding: binary');
                header('Accept-Ranges: bytes');
                @readfile(APPLICATION_PATH . "/upload_files/{$path}/{$file}");
            } else {
                $mime = Agro_Util::getMimeType($file);
                header('Content-Type: ' . $mime . '; charset=ISO-8859-1');
                echo file_get_contents(APPLICATION_PATH . "/upload_files/{$path}/{$file}");
            }
        } catch (ForbiddenRequestException $e) {
            $this->_redirect('/agronet');
        }
    }
	
	public function viewfiletransmissaoAction()
    {
        try {
            $this->getHelper('ViewRenderer')->setNoRender();
            $this->getHelper('layout')->disableLayout();

            $path = Agro_File::clearFileName($this->getRequest()->getParam('path'));
            $file = Agro_File::clearFileName($this->getRequest()->getParam('name'));

            if (!Agro_Util::validaDir($path)) {
                throw new ForbiddenRequestException('Diretório não existente');
            }

            echo file_get_contents(APPLICATION_PATH . "/upload_files/{$path}/{$file}");
        } catch (ForbiddenRequestException $e) {
            $this->_redirect('/agronet');
        }
    }
	
	public function viewidAction()
    {
        try {
            $this->getHelper('ViewRenderer')->setNoRender();
            $this->getHelper('layout')->disableLayout();

            $path = Agro_File::clearFileName($this->getRequest()->getParam('path'));
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');

            if (!Agro_Util::validaDir($path)) {
                throw new ForbiddenRequestException('Diretório não existente');
            }

            $rs = (new Seguro_Model_PropostasArquivos())->fetchRow(' id = ' . $id);
            $file = $rs['ds_nome_arquivo'];

            header('Content-Type: image; charset=ISO-8859-1');

            echo file_get_contents(APPLICATION_PATH . "/upload_files/{$path}/{$file}");
        } catch (ForbiddenRequestException $e) {
            $this->_redirect('/agronet');
        }
    }
	
	public function tempAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        $file = Agro_File::clearFileName($this->getRequest()->getParam('name'));
        $mime = Agro_Util::getMimeType($file);

        header('Content-Type: ' . $mime . '; charset=ISO-8859-1');

        echo file_get_contents(APPLICATION_PATH . "/upload_files/temp/{$file}");
    }
	
	public function croquiAction()
    {
        header('Content-Type: application/attachment; charset=ISO-8859-1');
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();
        ini_set('memory_limit', '256M');

        echo file_get_contents(PATH_CROQUI . '/' . Agro_File::clearFileName($this->getRequest()->getParam('name')));
    }
	
	public function viewchamadoAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        $file = Agro_File::clearFileName($this->getRequest()->getParam('name'));

        header('Content-Type: application/attachment; charset=ISO-8859-1');

        echo file_get_contents(APPLICATION_PATH . "/upload_files/temp/{$file}");
    }
	
	public function viewarquivolaudoAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        $file = Agro_File::clearFileName($this->getRequest()->getParam('name'));

        header('Content-Type: application/image; charset=ISO-8859-1');

        echo file_get_contents(APPLICATION_PATH . "/upload_files/laudoprevia/{$file}");
    }
	
	public function propostaxmlAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        $file = Agro_File::clearFileName($this->getRequest()->getParam('name'));

        header('Content-Type: application/attachment; charset=ISO-8859-1');

        echo file_get_contents(APPLICATION_PATH . "/upload_files/temp/{$file}");
    }
	
	public function deleteAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		if (unlink(APPLICATION_PATH."/upload_files/".$this->getRequest()->getParam('path')."/".$this->getRequest()->getParam('nome'))) {
			echo $this->getRequest()->getParam('id');
		}
	}
	
	public function processoarquivoAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            $row = (new Sinistro2_Model_ProcessosArquivos())->find($id)->current();

            $arquivo = APPLICATION_PATH . '/upload_files/sinistro_processo/' . $row['ds_nome_arquivo'];

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_nome_arquivo'],
                    true
                );
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }

	public function processarnotaAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            $row = (new Sinistro2_Model_NotasFiscaisArquivos())->find($id)->current();

            $arquivo = APPLICATION_PATH . '/upload_files/sinistro_processo/' . $row['ds_nome_arquivo'];

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_nome_arquivo'],
                    true
                );
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }
	
	public function liquidacaoarquivoAction()
    {
		$this->isAjax();
		
		if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            
			$row = (new Sinistro2_Model_Liquidacoes())->find($id)->current();
			
			$arquivo = APPLICATION_PATH.'/upload_files/sinistro_liquidacao/'.$row['ds_arquivo_liquidacao_manual'];

			if (file_exists($arquivo)) {
				$data = file_get_contents($arquivo);
				$size = filesize($arquivo);
			    
			    $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
			    $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_arquivo_liquidacao_manual'],
                    true
                );
			    $this->getResponse()->setHeader('Content-Length', $size, true);
			    $this->getResponse()->setHeader('Pragma', 'no-cache', true);
			    $this->getResponse()->setBody($data);
			    $this->getResponse()->sendResponse();
			}
		}
	}
	
	public function propostasobservacoesarquivosAction()
    {
        $this->isAjax();

        if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            
            $row = (new Seguro_Model_PropostasObservacoesArquivos())->find($id)->current();
            $arquivo = APPLICATION_PATH . '/upload_files/proposta_observacoes/' . $row['ds_nome_arquivo'];

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);
                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_nome_arquivo'],
                    true
                );
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }

        if ($this->getRequest()->getParam('nome')) {
            $nome = Agro_File::clearFileName($this->getRequest()->getParam('nome'));
            $arquivo = APPLICATION_PATH . '/upload_files/proposta_observacoes/' . $nome;

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);
                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_nome_arquivo'],
                    true
                );
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }
	
	public function laudofinalAction() {
		$this->isAjax();
					
		if ($this->getRequest()->getParam('id')) {

            $model = new Sinistro2_Model_LaudosFinaisArquivos();
			if ($this->getRequest()->getParam('isArquivoItem')) {
				$model = new Sinistro2_Model_LaudosFinaisItensSeguradosArquivos();
			}
			
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            
            $row = $model->find($id)->current();

            $arquivo = APPLICATION_PATH . '/upload_files/laudofinal/' . $row['ds_nome_arquivo'];

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_nome_arquivo'],
                    true
                );
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }

	public function laudopreliminarAction()
    {
        $this->isAjax();

        if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            
            $row = (new Sinistro2_Model_LaudosPreliminaresArquivos())->find($id)->current();

            $arquivo = APPLICATION_PATH . '/upload_files/laudopreliminar/' . $row['ds_nome_arquivo'];

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_nome_arquivo'],
                    true
                );
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }
	
	public function cobrancanobreAction()
    {
        $this->isAjax();

        if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            
            $row = (new Sinistro2_Model_CobrancaRelatorioArquivos())->find($id)->current();

            $arquivo = APPLICATION_PATH . '/upload_files/cobranca/' . $row['ds_nome_arquivo'];

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_nome_arquivo'],
                    true
                );
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }

	public function cobrancaessorAction()
    {
        $this->isAjax();

        if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            
            $row = (new Sinistro2_Model_CobrancaRelatorioArquivos())->find($id)->current();

            $arquivo = APPLICATION_PATH . '/upload_files/cobranca/' . $row['ds_nome_arquivo'];

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_nome_arquivo'],
                    true
                );
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }
	
	public function digitalizacaoAction()
    {
        $this->isAjax();

        if ($this->getRequest()->getParam('file')) {
            $file = Agro_File::clearFileName($this->getRequest()->getParam('file'));
            $file = APPLICATION_PATH . "/upload_files/proposta/digitalizacao/" . $file;

            if (file_exists($file)) {
                $data = file_get_contents($file);
                $size = filesize($file);

                $this->getResponse()->setHeader('Content-Type', Agro_Util::getMimeType($file), true);
                $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $file, true);
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }
	
	public function corretorarquivoAction()
    {
        $this->isAjax();

        if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            
            $row = (new Sistema_Model_CorretoresArquivos())->find($id)->current();

            $arquivo = APPLICATION_PATH . '/upload_files/corretores/' . $row['ds_nome_arquivo'];

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_arquivo_liquidacao_manual'],
                    true
                );
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }
	
	public function beneficiarioarquivoAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            
            $row = (new Seguro_Model_BeneficiariosArquivos())->find($id)->current();

            $arquivo = APPLICATION_PATH . '/upload_files/beneficiarios/' . $row['ds_nome_arquivo'];

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_nome_arquivo'],
                    true
                );
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }

	public function laudopreviaarquivoAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            
            $row = (new Seguro_Model_Vistoriapreviaempresaarquivos())->find($id)->current();

            $arquivo = APPLICATION_PATH . '/upload_files/laudoprevia/' . $row['ds_nome_arquivo'];

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_nome_arquivo'],
                    true
                );
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }
	
    public function declaracaocorretorAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        $parametros = $this->getRequest()->getParams();
        $idCorretor = !Agro_Util::filterVariable($parametros['id_corretor'])
            ? 0
            : (int)$parametros['id_corretor'];

        $modelCorretores = new Sistema_Model_Corretores();
        $this->view->dados = $modelCorretores->find($idCorretor)->current()->toArray();

        $this->view->setScriptPath(APPLICATION_PATH . '/modules/sistema/views/scripts/');
        $html = $this->view->render('corretor/pdfdeclaracao.phtml');

        $dompdf = new Dompdf(array('isRemoteEnabled' => true));
        $html = preg_replace('/>\s+</', '><', $html);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        $output = $dompdf->output();
        $nomeArquivo = "declaracao_corretor_{$idCorretor}.pdf";
        $arquivo = APPLICATION_PATH . "/upload_files/corretores/declaracao_corretor_{$idCorretor}.pdf";

        file_put_contents($arquivo, $output);

        if (file_exists($arquivo)) {
            $data = file_get_contents($arquivo);
            $size = filesize($arquivo);

            $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
            $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $nomeArquivo, true);
            $this->getResponse()->setHeader('Content-Length', $size, true);
            $this->getResponse()->setHeader('Pragma', 'no-cache', true);
            $this->getResponse()->setBody($data);
            $this->getResponse()->sendResponse();
        }
    }

	public function zipfotosvistoriasAction()
	{
        $this->isAjax();

        $filename = Agro_File::clearFileName($this->getRequest()->getParam('filename'));
        $tipoLaudo = Agro_File::clearFileName($this->getRequest()->getParam('tipo_laudo'));
        $file = APPLICATION_PATH . "/upload_files/{$tipoLaudo}/{$filename}";

        if (file_exists($file)) {
            $data = file_get_contents($file);
            $size = filesize($file);

            $this->getResponse()->setHeader('Content-Type', 'application/zip', true);
            $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $filename, true);
            $this->getResponse()->setHeader('Content-Length', $size, true);
            $this->getResponse()->setHeader('Pragma', 'no-cache', true);
            $this->getResponse()->setBody($data);
            $this->getResponse()->sendResponse();
        }
    }

	public function propostadocumentoAction()
	{
		$this->isAjax();

		$fileName = "propostas.zip";
		$file = APPLICATION_PATH . "/upload_files/proposta_tipo_assinatura/" . $fileName;
		if ($this->getRequest()->getParam('path') && $this->getRequest()->getParam('file')) {
			$fileName = Agro_File::clearFileName($this->getRequest()->getParam('file'));
			$file = APPLICATION_PATH . base64_decode($this->getRequest()->getParam('path')) . $fileName;
		}

		if (file_exists($file)) {
			$data = file_get_contents($file);
			$size = filesize($file);

			$this->getResponse()->setHeader('Content-Type', 'application/zip', true);
			$this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $fileName, true);
			$this->getResponse()->setHeader('Content-Length', $size, true);
			$this->getResponse()->setHeader('Pragma', 'no-cache', true);
			$this->getResponse()->setBody($data);
			$this->getResponse()->sendResponse();
		}
	}

    public function autorizacaoAction()
    {
        $this->isAjax();
        $nomeArquivo = "MODELO_AUTORIZACAO.docx";
        $arquivo = APPLICATION_PATH . "/upload_files/sinistro_processo/{$nomeArquivo}";

        if (file_exists($arquivo)) {
            $data = file_get_contents($arquivo);
            $size = filesize($arquivo);

            $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
            $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $nomeArquivo, true);
            $this->getResponse()->setHeader('Content-Length', $size, true);
            $this->getResponse()->setHeader('Pragma', 'no-cache', true);
            $this->getResponse()->setBody($data);
            $this->getResponse()->sendResponse();
        }
    }

	public function processosarquivospendenciasAction()
	{
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        if ($this->getRequest()->getParam('id')) {
            $modelProcessosArquivosPendencias = new Sinistro2_Model_ProcessosArquivosPendencias();
            $Row = $modelProcessosArquivosPendencias->find($this->getRequest()->getParam('id'))->current();

            $arquivo = Sinistro2_Model_ProcessosArquivosPendencias::getDiretorioByStatus($Row['id_status']) . "/" . $Row['ds_nome_arquivo'];

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $Row['ds_nome_arquivo'], true);
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }

	public function treinamentosaqruivosAction()
	{
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');
            
			$modelTreinamentosArquivos = new Sistema_Model_TreinamentosArquivos();
			$row = $modelTreinamentosArquivos->find($id)->current();

			$arquivo = Sistema_Model_TreinamentosArquivos::FILE_PATH . "/" . $row['ds_nome_arquivo'];
			
			if (file_exists($arquivo)){
				$data = file_get_contents($arquivo);
				$size = filesize($arquivo);
			    
			    $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
			    $this->getResponse()->setHeader(
                    'Content-Disposition',
                    'attachment; filename="' . $row['ds_nome_arquivo'],
                    true
                );
			    $this->getResponse()->setHeader('Content-Length', $size, true);
			    $this->getResponse()->setHeader('Pragma', 'no-cache', true);
			    $this->getResponse()->setBody($data);
			    $this->getResponse()->sendResponse();
			}
		}
	}

	public function processosarquivosexcluidosAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        if ($this->getRequest()->getParam('ds_nome_arquivo')) {
            $nomeArquivo = Agro_File::clearFileName($this->getRequest()->getParam('ds_nome_arquivo'));
            $arquivo = Sinistro2_Model_ProcessosObservacoesArquivos::FILE_PATH_DEL . "/" . $nomeArquivo;

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $nomeArquivo, true);
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }

	public function agritaskAction()
	{
        $this->isAjax();
        $nomeArquivo = '';

        if ($this->getRequest()->getParam('id_proposta')) {
            $idProposta = !Agro_Util::filterVariable($this->getRequest()->getParam('id_proposta'))
                ? 0
                : (int)$this->getRequest()->getParam('id_proposta');
            $modelPropostasCotacaoAgritask = new Seguro_Model_PropostasCotacaoAgritask();
            $idCotacao = $modelPropostasCotacaoAgritask->getCotacaoByProposta($idProposta);

            $arquivos = glob(Seguro_Model_PropostasCotacaoAgritask::FILE_PATH . "/{$idCotacao}*.pdf");

            if (!empty($arquivos)) {
                $nomeArquivo = "{$idProposta}_arquivos.zip";
                $diretorioZip = Seguro_Model_PropostasCotacaoAgritask::FILE_PATH . "/{$nomeArquivo}";

                $zip = new ZipArchive;

                if ($zip->open($diretorioZip, (ZipArchive::CREATE | ZipArchive::OVERWRITE)) !== TRUE) {
                    throw new Exception("Ocorreu um erro ao criar o arquivo ZIP.");
                }

                $contadorTipo02 = 0;
                $contadorTipo03 = 0;

                foreach ($arquivos as $indice => $arquivo) {
                    $basename = basename($arquivo);
                    $labelArquivo = $modelPropostasCotacaoAgritask->getLabelArquivo($basename, $indice);

                    if ($labelArquivo == 'Indenização Simulada - Cenário Histórico') {

                        if ($contadorTipo02 > 0) {
                            $labelArquivo .= "({$contadorTipo02})";
                        }
                        $contadorTipo02++;
                    } elseif ($labelArquivo == 'Laudo Final - Apuração dos Prejuízos') {
                        if ($contadorTipo03 > 0) {
                            $labelArquivo .= "({$contadorTipo03})";
                        }

                        $contadorTipo03++;
                    }

                    $zip->addFile($arquivo, $labelArquivo . ".pdf");
                }

                $zip->close();

                $data = file_get_contents($diretorioZip);
                $size = filesize($diretorioZip);
            }
        } elseif ($this->getRequest()->getParam('nome_arquivo')) {
            $nomeArquivo = Agro_File::clearFileName($this->getRequest()->getParam('nome_arquivo'));
            $arquivo = Seguro_Model_PropostasCotacaoAgritask::FILE_PATH . "/{$nomeArquivo}";

            if (file_exists($arquivo)) {
                $data = file_get_contents($arquivo);
                $size = filesize($arquivo);
            }
        }

        if (!empty($nomeArquivo)) {
            $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
            $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $nomeArquivo, true);
            $this->getResponse()->setHeader('Content-Length', $size, true);
            $this->getResponse()->setHeader('Pragma', 'no-cache', true);
            $this->getResponse()->setBody($data);
            $this->getResponse()->sendResponse();
        }
    }

	public function devolucaoarquivosAction()
	{
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        if ($this->getRequest()->getParam('id')) {
            $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
                ? 0
                : (int)$this->getRequest()->getParam('id');

            $modelPropostasDevolucoesArquivos = new Seguro_Model_PropostasDevolucoesArquivos();
            $row = $modelPropostasDevolucoesArquivos->find($id)->current();
            $nomeArquivo = $row['ds_nome_arquivo'];
        } elseif ($this->getRequest()->getParam('ds_nome_arquivo')) {
            $nomeArquivo = Agro_File::clearFileName($this->getRequest()->getParam('ds_nome_arquivo'));
        }

        if (!empty($nomeArquivo)) {
            $caminho = Seguro_Model_PropostasDevolucoesArquivos::FILE_PATH . "/" . $nomeArquivo;

            if (file_exists($caminho)) {
                $data = file_get_contents($caminho);
                $size = filesize($caminho);

                $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
                $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $nomeArquivo, true);
                $this->getResponse()->setHeader('Content-Length', $size, true);
                $this->getResponse()->setHeader('Pragma', 'no-cache', true);
                $this->getResponse()->setBody($data);
                $this->getResponse()->sendResponse();
            }
        }
    }

	public function importarchamadosAction()
    {
        $this->isAjax();

		$nomeArquivo = "MODELO_ARQUIVO_TECNICA.xlsx";
		
		if ($this->getRequest()->getParam('tipo') == 'sinistro') {
			$nomeArquivo = "MODELO_ARQUIVO_SINISTRO.xlsx";
		}
       
        $arquivo = APPLICATION_PATH . "/upload_files/chamados/{$nomeArquivo}";

        if (file_exists($arquivo)) {
            $data = file_get_contents($arquivo);
            $size = filesize($arquivo);

            $this->getResponse()->setHeader('Content-Type', 'application/octetstream', true);
            $this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $nomeArquivo, true);
            $this->getResponse()->setHeader('Content-Length', $size, true);
            $this->getResponse()->setHeader('Pragma', 'no-cache', true);
            $this->getResponse()->setBody($data);
            $this->getResponse()->sendResponse();
        }
    }

	public function termoautorizacaoacompanhanteAction()
	{
		$this->isAjax();

		$file = APPLICATION_PATH . base64_decode($this->getRequest()->getParam('path')) . $this->getRequest()->getParam('filename');

		if (file_exists($file)) {
			$data = file_get_contents($file);
			$size = filesize($file);

			$this->getResponse()->setHeader('Content-Type', 'application/zip', true);
			$this->getResponse()->setHeader('Content-Disposition', 'attachment; filename="' . $this->getRequest()->getParam('filename'), true);
			$this->getResponse()->setHeader('Content-Length', $size, true);
			$this->getResponse()->setHeader('Pragma', 'no-cache', true);
			$this->getResponse()->setBody($data);
			$this->getResponse()->sendResponse();
		}
	}
}
