<?php


//função para limpar os POSTs por segurança
function stringInputCleaner($data)
{
		//remove space bfore and after
		if(!empty($data)){
			$data = trim($data); 
			//remove slashes
			$data = stripslashes($data); 
			$data=(filter_var($data, FILTER_SANITIZE_STRING));
		} 	
		
		return $data;
}

//função para cortar um texto e adicionar 3 pontos no final
if(!function_exists("texto")) {
	function texto($string, $limite)
	{
		return substr_replace($string, (strlen($string) > $limite ? '...' : ''), $limite);
	}
}


//função para redirecionar usuário
if(!function_exists('redirect'))
{
	function redirect($string)
	{
		echo 
		'
			<script>
				setTimeout(function(){
					location.href="'.$string.'";
				}, 1500);
			</script> 
 		';
 	}
}


  //Compressão de imagem
	if(!function_exists('compressao'))
	{
	  function compressao($source, $destination, $quality){
	      $info = getimagesize($source);
	      if ($info['mime'] == 'image/jpeg') 
	          $image = imagecreatefromjpeg($source);
	      elseif ($info['mime'] == 'image/gif') 
	          $image = imagecreatefromgif($source);
	      elseif ($info['mime'] == 'image/png') 
	          $image = imagecreatefrompng($source);
	      imagejpeg($image, $destination, $quality);
	      return $destination;
	  }
	}
  //-----------------------------------------------------------------------------------


//função que converte array em json
if(!function_exists('messageJson'))
{
	function messageJson($tipo, $mensagem, $acao = "", $complemento = "", $complementnoSegundo = "", $complementnoTerceiro = "")
	{
		echo json_encode(array($tipo, $mensagem, $acao, $complemento, $complementnoSegundo, $complementnoTerceiro));
	}
}


//função que remove todos os elementos que não sejam numeros
if(!function_exists('numeros'))
{
	function numeros($string)
	{ 
		if (!empty($string))
		{
			return preg_replace('/[^\d\-]/', '',$string);
		}
		else
		{
			return '';
		}
 	}
}


//converte para formato de moeda
if(!function_exists("currency")) {
	function currency($string)
	{
		if(!empty($string))
		{
			return number_format($string, 2, ',', '.');
		}
		else
		{
			return 0;
		}
	}
}

 

if(!function_exists('mensagem'))
{
	function mensagem($tipo, $mensagem)
	{
		if($tipo == 'erro')
		{
			echo 
			'  
				<div class="alert alert-danger closeable">
					<p style="font-size: 16px;">Opsss </p>
					<p>'.$mensagem.'</p>
					<a class="close"></a>
				</div>
			';
		}
		elseif($tipo == 'sucesso')
		{
			echo 
			'  
				<div class="alert alert-success large margin-bottom-55 closeable">
					<p style="font-size: 16px;">Tudo Certo </p>
					<p>'.$mensagem.'</p>
					<a class="close"></a>
				</div>
			';
		}
		elseif($tipo == 'info')
		{
			echo 
			'  
				<div class="alert alert-info large margin-bottom-55">
					<p style="font-size: 16px;"></p>
					<p>'.$mensagem.'</p>
				</div>
			';
		}
	}
}
 


if(!function_exists('hideEmail'))
{
	function hideEmail($email)
	{
		$character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
		$key = str_shuffle($character_set); $cipher_text = ''; $id = 'e'.rand(1,999999999);
		for ($i=0;$i<strlen($email);$i+=1) $cipher_text.= $key[strpos($character_set,$email[$i])];
		$script = 'var a="'.$key.'";var b=a.split("").sort().join("");var c="'.$cipher_text.'";var d="";';
		$script.= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
		$script.= 'document.getElementById("'.$id.'").innerHTML="<a href=\\"mailto:"+d+"\\">"+d+"</a>"';
		$script = "eval(\"".str_replace(array("\\",'"'),array("\\\\",'\"'), $script)."\")"; 
		$script = '<script type="text/javascript">/*<![CDATA[*/'.$script.'/*]]>*/</script>';
		return '<span id="'.$id.'">[javascript protected email address]</span>'.$script;
	}
}





if(!function_exists('dataAgora'))
{
	function dataAgora($datetime, $full = false) {
		$now = new DateTime;
		$ago = new DateTime($datetime);
		$diff = $now->diff($ago);

		$diff->w = floor($diff->d / 7);
		$diff->d -= $diff->w * 7;

		$string = array(
			'y' => 'anos',
			'm' => 'mês',
			'w' => 'semana',
			'd' => 'dia',
			'h' => 'hora',
			'i' => 'minuto',
			's' => 'segundo',
		);
		foreach ($string as $k => &$v) {
			if ($diff->$k) {
				$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
			} else {
				unset($string[$k]);
			}
		}
			//2021-05-19 18:48:03 
			
				$dataP1 = explode(' ', $datetime);
				
				$HoraP1 = explode(':', $dataP1[1]);
				$hora 	= $HoraP1[0].':'.$HoraP1[1];
				
				//ontem
				$data  = $dataP1[0];
				$ontem =  date('Y-m-d', strtotime('-1 days'));


				if($ontem == $data)
				{
					return 'ontem às '.$hora;
				}
				else
				{
					///checa dia anterior a ontem
					$data_inicial 	= $dataP1[0];
					$data_final 	= date("Y-m-d");
					$diferenca 		= strtotime($data_final) - strtotime($data_inicial);
					$dias 			= floor($diferenca / (60 * 60 * 24));
					
					if($dias > 1)
					{
						return date("d/m/Y", strtotime($dataP1[0])) .' às '.$hora;
					}
					else
					{
						if (!$full) $string = array_slice($string, 0, 1);
						return $string ? implode(', ', $string) . ' atrás' : 'agora';
					}
				}
	}
}


 

 

if(!function_exists('EnviaEmail'))
{
	function enviaEmail($destinatario_email, $destinatario_nome, $assunto, $mensagem, $link, $log)
	{ 
			global $configSistema;

 			$mensagem_envia = 
			'
<!doctype html>
<html>
  <head>
    <meta name="viewport" content="width=device-width" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title></title>
    <style>
		img{border:none;-ms-interpolation-mode:bicubic;max-width:100%}body{background-color:#f6f6f6;font-family:sans-serif;-webkit-font-smoothing:antialiased;font-size:14px;line-height:1.4;margin:0;padding:0;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}table{border-collapse:separate;mso-table-lspace:0;mso-table-rspace:0;width:100%}table td{font-family:sans-serif;font-size:14px;vertical-align:top}.body{background-color:#f6f6f6;width:100%}.container{display:block;margin:0 auto!important;max-width:580px;padding:10px;width:580px}.content{box-sizing:border-box;display:block;margin:0 auto;max-width:580px;padding:10px}.main{background:#fff;border-radius:3px;width:100%}.wrapper{box-sizing:border-box;padding:20px}.content-block{padding-bottom:10px;padding-top:10px}.footer{clear:both;margin-top:10px;text-align:center;width:100%}.footer td,.footer p,.footer span,.footer a{color:#999;font-size:12px;text-align:center}h1,h2,h3,h4{color:#000;font-family:sans-serif;font-weight:400;line-height:1.4;margin:0 0 30px}h1{font-size:35px;font-weight:300;text-align:center;text-transform:capitalize}p,ul,ol{font-family:sans-serif;font-size:14px;font-weight:400;margin:0 0 15px}p li,ul li,ol li{list-style-position:inside;margin-left:5px}a{color:#3498db;text-decoration:underline}.btn{box-sizing:border-box;width:100%}.btn > tbody > tr > td{padding-bottom:15px}.btn table{width:auto}.btn table td{background-color:#fff;border-radius:5px;text-align:center}.btn a{background-color:#fff;border:solid 1px #3498db;border-radius:5px;box-sizing:border-box;color:#3498db;cursor:pointer;display:inline-block;font-size:14px;font-weight:700;margin:0;padding:12px 25px;text-decoration:none;text-transform:capitalize}.btn-primary table td{background-color:#3498db}.btn-primary a{background-color:#3498db;border-color:#3498db;color:#fff}.last{margin-bottom:0}.first{margin-top:0}.align-center{text-align:center}.align-right{text-align:right}.align-left{text-align:left}.clear{clear:both}.mt0{margin-top:0}.mb0{margin-bottom:0}.preheader{color:transparent;display:none;height:0;max-height:0;max-width:0;opacity:0;overflow:hidden;mso-hide:all;visibility:hidden;width:0}.powered-by a{text-decoration:none}hr{border:0;border-bottom:1px solid #f6f6f6;margin:20px 0}@media only screen and (max-width: 620px){table[class=body] h1{font-size:28px!important;margin-bottom:10px!important}table[class=body] p,table[class=body] ul,table[class=body] ol,table[class=body] td,table[class=body] span,table[class=body] a{font-size:16px!important}table[class=body] .wrapper,table[class=body] .article{padding:10px!important}table[class=body] .content{padding:0!important}table[class=body] .container{padding:0!important;width:100%!important}table[class=body] .main{border-left-width:0!important;border-radius:0!important;border-right-width:0!important}table[class=body] .btn table{width:100%!important}table[class=body] .btn a{width:100%!important}table[class=body] .img-responsive{height:auto!important;max-width:100%!important;width:auto!important}}@media all{.ExternalClass{width:100%}.ExternalClass,.ExternalClass p,.ExternalClass span,.ExternalClass font,.ExternalClass td,.ExternalClass div{line-height:100%}.apple-link a{color:inherit!important;font-family:inherit!important;font-size:inherit!important;font-weight:inherit!important;line-height:inherit!important;text-decoration:none!important}.btn-primary table td:hover{background-color:#34495e!important}.btn-primary a:hover{background-color:#34495e!important;border-color:#34495e!important}}
    </style>
  </head>
  <body class="">
    <table border="0" cellpadding="0" cellspacing="0" class="body">
      <tr>
        <td>&nbsp;</td>
        <td class="container">
          <div class="content">
            <span class="preheader">Você recebeu uma nova mensagem no '.$configSistema['sistema'].'</span>
            <table class="main">
				  		<tr>
								<td class="wrapper">
									<img src="'.$configSistema['logo'].'" width="220px">
								</td>
              </tr>
              <tr>
                <td class="wrapper">
                  <table border="0" cellpadding="0" cellspacing="0">
                    <tr>
                      <td>
                        	<p>
														'.$mensagem.'
														<br><br><br>
														Esta é uma mensagem automática, por favor, não responda
													</p> 
                      </td>
                    </tr>
                  </table>
                </td>
              </tr>
            </table>

            <div class="footer">
              <table border="0" cellpadding="0" cellspacing="0">
                <tr>
                  <td class="content-block">
                     <br> Você está recebendo este email por estar em algum canal '.$configSistema['sistema'].'.
                  </td>
                </tr>
                <tr>
                  <td class="content-block powered-by">
                    Copyright '.$configSistema['sistema'].'
                  </td>
                </tr>
              </table>
            </div>
          </div>
        </td>
        <td>&nbsp;</td>
      </tr>
    </table>
  </body>
</html>

';
 
			require_once 'libs/phpmailer/PHPMailerAutoload.php';
 
			$mail = new PHPMailer();
			$mail->isSMTP();
			// 0 = off (for production use)
			// 1 = client messages
			// 2 = client and server messages
			$mail->SMTPDebug = 0;
			$mail->Debugoutput = 'html';
			$mail->Host = $configSistema['servidor'];
			$mail->Port = $configSistema['porta'];
			$mail->SMTPAuth = true;
			$mail->SMTPSecure = $configSistema['ssl'];
			$mail->Username = $configSistema['usuario'];
			$mail->Password = $configSistema['pwd'];
			$mail->setFrom($configSistema['usuario'], utf8_decode($configSistema['remetente']));
				//$mail->addReplyTo('replyto@example.com', 'First Last');
			$mail->addAddress($destinatario_email, $destinatario_nome);
			$mail->Subject = utf8_decode($assunto);
			$mail->msgHTML(utf8_decode($mensagem_envia));
			if($log == 1)
			{
				if (!$mail->send()) {
					echo "Mailer Error: " . $mail->ErrorInfo;
					echo '<br>2';
				} else {
					echo "Email enviado";
					echo '<br>1';
				}
			}
			else
			{
 				if($mail->send())
				{
					return 1;
				}
				else
				{
					return 2;
				}
			}
	}
}