<?php

class Agro_Mail extends Zend_Mail {
	private $tipoUsuario = "Usuário";
	private $inicioTextoPadrao = true;
    /**
     * Controla o envio de e-mail para o usuário setado como destinatário em ambiente de teste, desde que seja
     * funcionário Agro
     * @var bool
     */
	private bool $enviarParaDestinatarioAmbienteTeste = false;

	public function __construct() {
		parent::__construct('UTF-8');
		parent::setFrom(MAIL_USERNAME, 'AgroBrasil - Agronet 2.0');


		$config = array(
			'ssl' => MAIL_SSL,
			'port' => MAIL_PORT,
			'auth' => MAIL_AUTH,
			'username' => MAIL_USERNAME,
			'password' => MAIL_PASSWORD
		);

		$transport = new Zend_Mail_Transport_Smtp(MAIL_SMTP, $config);
		
        parent::setDefaultTransport($transport);
	}

	public function setBody($body, $type='text') {
		if ($type == 'html') {
			$this->setBodyHtml($this->getHtmlLayout($body));
		} else {
			$this->setBodyText($this->getTextLayout($body));
		}
	}

	public function setTipoUsuario($tipoUsuario){
		$this->tipoUsuario = $tipoUsuario;
	}

	public function getTipoUsuario(){
		return $this->tipoUsuario;
	}

	public function setTo($to){
		$this->to = $to;
	}

    /**
     * @return array
     */
	public function getTo() {
		return $this->_to;
	}

    public function getTextLayout($content) {

        $return = '';

        if ($this->inicioTextoPadrao) {
            $return .= "Prezado ".$this->getTipoUsuario().", ";
        }

        $return .= "\n\n$content\n\n";

        $return .= "Acesse o sistema Agronet 2.0 através do endereço: http://agronet.agrobrasilseguros.com.br/";
        $return .= "\nATENÇÃO: esta é uma mensagem automática. Por favor, não responda. Se deseja entrar em contato conosco, escreva para atendimento@agrobrasilseguros.com.br \n\n";

        return $return;
    }

	public function getHtmlLayout($content) {
		$return = "$content";
		return $return;
	}

	public function send()
    {
        if (APPLICATION_ENV != 'production') {
            if ($this->enviarParaDestinatarioAmbienteTeste) {
                $destinatarios = $this->getTo();

                if (isset($destinatarios[0])) {
                    $row = (new Sistema_Model_Usuarios())->getFuncionarioAgroByEmail($destinatarios[0]);

                    if (empty($row)) {
                        $this->dadosEnvioAmbienteTeste();
                    }
                }
            } else {
                $this->dadosEnvioAmbienteTeste();
            }

            $this->clearFrom();
            $this->setFrom(MAIL_USERNAME, 'AgroBrasil - Agronet 2.0');
        }

        return parent::send();
    }

    /**
     * Envia um email para o corretor com os dados passados por parametro
     *
     * @param Agro_Db_Table_Abstract $Proposta
     * @param string $subject
     * @param string $body
     * @param array $opt
     * @return bool
     */
	public function notificarCorretor($Proposta, $subject, $body, array $opt = null, bool $copiarAtendimento = true) {
		try {
			$this->addTo($Proposta->ds_email_corretor, $Proposta->ds_nome_corretor);
			if (is_array($Proposta->ds_email_preposto)) {
				$this->addCc($Proposta->ds_email_preposto, $Proposta->ds_nome_preposto);
			}

			//solicitacao 4041
			if (strpos(strtoupper($subject), strtoupper('Alerta de Pendência por Vistoria:')) === false) {
                if ($copiarAtendimento) {
                    $this->addCc('atendimento@agrobrasilseguros.com.br', 'Atendimento');
                }

				$this->addBcc('luana.beck@agrobrasilseguros.com.br', 'Luana Beck');
			} else {
				$this->clearFrom();
				$this->setFrom('vp@agrobrasilseguros.com.br', 'Agro VP');
				$this->addBcc('karina.figueiro@agrobrasilseguros.com.br', 'Karina Figueiro da Silva');

				if (!empty($opt['emailsAdicionais'])) {
				    foreach ($opt['emailsAdicionais'] as $email) {
                        $this->addBcc($email['e-mail'], $email['nome']);
                    }
                }
			}

            $this->addBcc('karina.silva@agrobrasilseguros.com.br', 'Karina Fernanda da Silva');
			$this->setTipoUsuario("Corretor");
			if (isset($opt['html']) && $opt['html'] == true) {
                $this->setBodyHtml($body);
            } else {
                                //DEBUG - INICIO
		        if (APPLICATION_ENV != 'production') {
			        $body .= "<br><br><hr><b>DEBUG</b>";
			        $body .= "<br>Destinatários";
			        foreach ($Mail->getRecipients() as $recipient) {
				        $body .= "<br> - {$recipient}";
			        }
		        }
		        //DEBUG - FIM
                $this->setBody($body);
            }
			$this->setSubject($subject);

			$this->send();
		} catch (Exception $e) {
			return false;
		}

		return true;
	}

	public function inicioTextoPadrao(bool $inicioTextoPadrao)
    {
        $this->inicioTextoPadrao = $inicioTextoPadrao;
    }

    public static function getAssinatura(Agro_Mail $email, int $tipoAssinatura)
    {
        switch ($tipoAssinatura) {
            case 1:
                $filename = APPLICATION . "/resources/imagens/assinatura_email_tecnica.png";
                break;

            case 2:
                $filename = APPLICATION . "/resources/imagens/assinatura_departamento_sinistro.png";
                break;

            default:
                throw new Exception('Tipo de assinatura não encontrado.');
        }

        $anexo = $email->createAttachment(file_get_contents($filename));
        $anexo->type = Agro_Util::getMimeType($filename);
        $anexo->disposition = Zend_Mime::DISPOSITION_INLINE;
        $anexo->encoding = Zend_Mime::ENCODING_BASE64;
        $anexo->id = 'cid' . md5_file($filename);

        return $anexo;
    }

    public static function textoPadraoEmailHtml()
    {
        $body = "<br /> ";
        $body .= "<span style=\"color: grey; margin: 0!important;  font-family: Verdana; font-size: .5em; text-align: left; display: block;\"> ";
        $body .= "<font face='webdings' style=\"color: darkgreen\">i</font> ";
        $body .= "<span style=\"color: darkblue\"> Este e-mail, inclusive anexos, podem conter informações confidenciais de propriedade exclusiva da AgroBrasil Seguros, ";
        $body .= "<br />não devendo ser utilizado, copiado ou revelado sem prévia autorização.</span> This e-mail, including attachments, is intended<br /> for ";
        $body .= "the person(s) or company named and may contain confidential and/or legally privileged information. Unauthorized<br /> disclosure, ";
        $body .= "copying or use of this information may be unlawful and is prohibited. If you are not the intended recipient,<br /> please delete this ";
        $body .= "message and notify the sender. ";
        $body .= "</span> ";
        $body .= "<br /> ";
        $body .= "<span style=\"color: grey; margin: 0!important; font-family: Verdana; font-size: .5em; text-align: left; display: block\"> ";
        $body .= "<font face='webdings'  style=\"color: darkgreen\">P</font> <span style=\"font-weight: bold\">Antes de imprimir, pense em seu compromisso com o Meio Ambiente.</span> Before printing, think about your<br /> commitment ";
        $body .= "to the environment. ";
        $body .= "</div>";

        return $body;
    }

    /**
     * Libera envio de e-mail para o usuário setado como destinatário em ambiente de teste, desde que seja funcionário
     * Agro
     * @param bool $enviarParaDestinatarioAmbienteTeste
     * @return void
     */
    public function enviarParaDestinatarioAmbienteTeste(bool $enviarParaDestinatarioAmbienteTeste)
    {
        $this->enviarParaDestinatarioAmbienteTeste = $enviarParaDestinatarioAmbienteTeste;
    }

    private function dadosEnvioAmbienteTeste()
    {
        $this->addDestinatariosCorpoEmail();
        $this->clearRecipients();

        if (!Sistema_Model_Usuarios::usuarioLogadoFuncionarioAgro()) {
            $this->addTo('tonismar.bernardo@agrobrasilseguros.com.br', 'Tonismar R. Bernardo');
            $this->addTo('fabio.bertoldi@agrobrasilseguros.com.br', 'Fábio Bertoldi');
            $this->addTo('silvia.silva@agrobrasilseguros.com.br', 'Silvia Martins da Silva');
            return;
        }

        $user = Zend_Auth::getInstance()->getIdentity();
        $this->addTo($user->ds_email);
    }
    
    /**
     * Adiciona os destinatários no corpo do e-mail para validações no ambiente de testes
     */
    private function addDestinatariosCorpoEmail(): void
    {
        $isHtml = true;
        $corpo = $this->getBodyHtml();
        
        if (empty($corpo)) {
            $isHtml = false;
            $corpo = $this->getBodyText();
        }

        $quebraLinha = $isHtml ? "<br>" : "\n";

        $conteudo  = $corpo->getRawContent();
        $conteudo .= "{$quebraLinha}{$quebraLinha}" . str_repeat("-", 150);
        $conteudo .= "{$quebraLinha}Em ambiente de produção, este e-mail será enviado para os seguintes destinatários: ";
        foreach ($this->getRecipients() as $destinatario) {
            $conteudo .= "{$quebraLinha} - $destinatario";
        }
        $conteudo .= "{$quebraLinha}{$quebraLinha}";
        
		if ($isHtml) {
			$this->setBodyHtml($conteudo);
            return;
		}

        $this->setBodyText($conteudo);
    }
}
