<?php
    @session_start();
    header( "Content-type: text/html; charset=utf-8" );
    set_time_limit(2000000);
    if (!isset($_SESSION["admin"]["id"])) {
        echo "<script>location.href='index.php';</script>";
    }
    include "config/conf.php";
?>


<!DOCTYPE html>
<html>
<head>
	<title><?php echo $title; ?></title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta charset="utf-8">
	<base href="<?php echo "http://".$_SERVER["HTTP_HOST"].$_SERVER["SCRIPT_NAME"]; ?>" />

	<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
	<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>

	<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="css/sb-admin.css">
	<link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
	<link rel="stylesheet" type="text/css" href="css/jasny-bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css">
	<link rel="stylesheet" type="text/css" href="css/wysiwyg-color.css">

	<link rel="stylesheet" type="text/css" href="css/style.css">
	
    <link rel="shortcut icon" type="image/x-icon" href="<?=$base;?>/icone.png">

    <link href="summernote.css" rel="stylesheet">
   

	<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
	<script type="text/javascript" src="js/bootstrap.min.js"></script>
	<script type="text/javascript" src="js/jqBootstrapValidation.js"></script>
	<script type="text/javascript" src="js/bootstrap-inputmask.min.js"></script>
	<script type="text/javascript" src="js/jquery.maskMoney.min.js"></script>
	<script type="text/javascript" src="js/prettify.js"></script>
	<script type="text/javascript" src="js/jquery.colorbox-min.js"></script>

    <script src="js/jquery.complexify.js"></script> 
    <script src="summernote.min.js"></script>

	<link rel="stylesheet" type="text/css" href="colorbox.css">
	<script>
	  $(function () { $("input,select,textarea").not("[type=submit]").jqBootstrapValidation(); } );
	</script>
</head>
<body style="padding-top: 15px !important;">
<div class="container" style="margin-top:-50px">
<div id="msg"></div>

<?php
	if ( $_POST ) {

		$id = trim ( $_POST["id"] );
		$boleto = trim ( $_POST["boleto"] );
		$teste = trim ( $_POST["teste"] );
		$mes = trim ( $_POST["mes"] );

		$max = 150;
		$qtde = $_POST["qtde"];
		$q = $max * $qtde;

		$limit = " limit $q, $max ";
		if ( $teste == "S" ) {
			$limit = " limit 3 ";
			echo "<p><strong>Enviando e-mail de teste!</strong></p>";
		}

		$sql = "select c.email, c.nome, c.id cid, c.cnpj, p.nome parceiro, p.servidor, p.login, p.senha, p.porta, p.assinatura, m.assunto, m.mensagem,  m.ativo, p.nomeemail, f.nome fnome, f.email femail
			from cliente c 
			inner join parceiro p on ( p.id = c.parceiro_id )
			inner join email_mensagem em on ( em.cliente_id = c.id )
			inner join mensagem m on ( m.id = em.email_id) 
			inner join funcionario f on ( f.id = c.funcionario_id )
			where m.id = ? and m.ativo = 'Sim'
			order by c.nome $limit";

		$consulta = $db->prepare($sql);
		$consulta->bindParam(1, $id);
		$consulta->execute();

		echo "<p class='alert alet-danger'>Serão enviados: ".$consulta->rowCount()."</p>";

		$i = 0;

		require 'PHPMailerAutoload.php';

		while ( $dados = $consulta->fetch( PDO::FETCH_OBJ ) ) {

			$i++;

			$server = $dados->servidor;
			$port = $dados->porta;
			$pass = $dados->senha;
			$login = $dados->login;
			$parceiro = utf8_decode( $dados->parceiro );
			$cliente = $dados->nome;
			$cemail = $dados->email;
			$assinatura = "../downloads/".$dados->assinatura;
			$mensagem = $dados->mensagem;
			$assunto = $dados->assunto;
			$nome = $dados->nomeemail;
			$cid = $dados->cid;

			$fnome = $dados->fnome;
			$femail = $dados->femail;

			$mail = new PHPMailer;
			$mail->isSMTP();
			$mail->SMTPDebug = 0;
			$mail->Debugoutput = 'html';
			$mail->Host = $server;
			$mail->Port = $port;
			//$mail->SMTPSecure = 'ssl';
			$mail->SMTPAuth = true;
			$mail->Username = $login;
			$mail->Password = $pass;

			
			if ( $teste == "S" ) {

				$cemail = "thiago@redendl.com.br;marciar@redendl.com.br;burnes@professorburnes.com;";
				$femail = "teste@maxcredit.com.br";

				if ( $i > 3 ) {

					echo "<div class='alert alert-success'>Foram enviados 3 e-mails de teste!</div>";
					exit;

				}

			} 

			//$cemail = "burnes@professorburnes.com;teste@maxcredit.com.br";
			//$femail = "atendimento@uniti.com.br";
			
			$mail->setFrom($login, $nome);
			$mail->addAddress($femail, $fnome);

			$emails = str_replace("\\\\", ";", $cemail);
   			$emails = str_replace("\\", ";", $emails);
   			$emails = str_replace(" ", ";", $emails);
   			$emails = str_replace("<", "", $emails);

   			$emails = explode(";", $emails);
   			$eemail = "";
   			foreach ($emails as $e) {
   				$mail->addAddress($e, $cliente);
   				$eemail .= $e." ";
   			}

   			if ( $boleto == "S" ) {

   				$data = date("Y") . "-". $mes;

   				$sql2 = "select * from arquivo where cliente_id = $cid and data like '$data%' limit 1";
   				$consulta2 = $db->prepare($sql2);
   				$consulta2->execute();

   				$row = $consulta2->fetch(PDO::FETCH_OBJ);

   				$arquivo = "../../downloads/".$row->arquivo;
   				$mail->addAttachment($arquivo);
   			}

   			$mail->ConfirmReadingTo = $femail;

   			$mensagem = ("$mensagem<br><img src='http://www.gruporbk.com.br/downloads/$assinatura'>");
   			
   			$mail->Subject = $assunto;
   			$mail->msgHTML("Prezado $cliente <br><br> $mensagem");

   			if (!$mail->send()) {
                echo "<div class='alert alert-danger'>Erro ao enviar mensagem para $cliente ( $dados->cnpj ) $eemail </div>";

            } else {
                echo "<div class='alert alert-success'>Mensagem enviada com sucesso para $cliente ( $dados->cnpj ), para os e-mails: $eemail </div>";	                	
            }

            

		}
		$qtde++;
		echo "<script>top.$('#enviando').hide();top.$('#qtde').val($qtde);</script>";


	}

?>

</div>
</body>
</html>