<?php
require 'PHPMailer-master/PHPMailerAutoload.php';

global $w_fecha; 
global $w_fecha_dmy;
global $w_hora;
$w_fecha = date("Y-m-d");
$w_fecha_dmy = date("d/m/Y");
/*// Si se quiere correr para otra fecha 
$w_fecha = '2017-07-26';
$w_fecha_dmy = '26/07/2017';
*/

$w_hora = date("Y-m-d H:i:s"); 
echo "\n", $w_hora; 
echo " - Inicio del Proceso\n";   

const KEY   = "KeyFiDeLitAS2016";

function safe_b64encode($string) {

    $data = base64_encode($string);
    $data = str_replace(array('+','/','='),array('-','_',''),$data);
    return $data;
}

function safe_b64decode($string) {
    $data = str_replace(array('-','_'),array('+','/'),$string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

  //Método público que se encarga de encriptar una cadena
  function encrypt($value){ 
    if(!$value){return false;}
    $text = $value;
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, KEY, $text, MCRYPT_MODE_ECB, $iv);
    return trim(safe_b64encode($crypttext)); 
  }

  //Método público que se encarga de desencriptar únicamente lo que este encriptado con el método encrypt
  function decrypt($value){
    if(!$value){return false;}
    $crypttext = safe_b64decode($value); 
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, KEY, $crypttext, MCRYPT_MODE_ECB, $iv);
    return trim($decrypttext);
  }

  function parsearHTMLPorSeccion($connection,$info,$tabla,$nro_cheque,$id,$w_fecha){
    switch ($tabla) {
      case 'cendeu':
        $html ="<td>".$info->nombre."</td>";
        $html .="<td>".$info->periodo."</td>";
        $html .="<td>".$info->situacion."</td>";
        //$html .="<td>".$info->total."</td>";
        $html .="<td align=right>".number_format($info->total, 2, ',', ' ')."</td>";

        break;
      case 'cendeu_cancela':
        $html  ="<td>".$info->fecha."</td>";
        $html .="<td>".$info->evento."</td>";
        $html .="<td>".$info->banco."</td>";
        $html .="<td>".$info->desde."</td>";
        $html .="<td>".$info->hasta."</td>";
        break;
      case 'juicios':
        $html  ="<td>".$info->fecha_causa."</td>";
        $html .="<td>".$info->nombre_causa."</td>";
        $html .="<td>".$info->cuit_actor."</td>";
        $html .="<td>".$info->nombre_actor."</td>";
        break;
      case 'sircreb':
        $html  ="<td>".$info->fecha."</td>";
        $html .="<td>".$info->desde."</td>";
        $html .="<td>".$info->hasta."</td>";
        break;
      case 'arba':
         $html  = "<td>".$info->impuesto."</td>";
         $html .= "<td>".$info->objeto."</td>";
         $html .= "<td>".$info->numero_interno_de_juicio."</td>";
         $html .= "<td>".$info->fecha_de_inicio_de_juicio ."</td>";
         //$html .= "<td>".$info->importe_deuda_del_juicio."</td>";
         $html .="<td align=right>".number_format($info->importe_deuda_del_juicio, 2, ',', ' ')."</td>";
         $html .= "<td>".$info->fecha_de_cancelacion."</td>";
         $html .= "<td>".$info->fecha_de_plan_de_pagos."</td>";
         $html .= "<td>".$info->cancelacion_del_juicio."</td>";
         $html .= "<td>".$info->estado_de_medida_cautelar."</td>";
         $html .= "<td>".$info->estado_de_plan_de_pagos."</td>";
         break;
      case 'balances_contables':
         $html  = "<td>".$info->titulo."</td>";
         $html .= "<td>".$info->fecha."</td>";
         break;
      case 'chequesbcra':
        $html ="<td>".$info->causa."</td>";
        $html .="<td>".$info->cuit_firmante."</td>";
        $html .="<td>".$info->cuit_relacionado."</td>";
        $html .="<td>".$info->nro_cheque."</td>";
        $html .="<td align=right>".number_format($info->importe, 2, ',', ' ')."</td>";
        $html .="<td>".$info->fecha_rechazo."</td>";
        $html .="<td>".$info->fecha_pago."</td>";
        $html .="<td>".$info->fecha_levantamiento."</td>";
        break;
      case 'cheques99':
        $html ="<td>".$info->causa."</td>";
        $html .="<td>".$info->cuit_firmante."</td>";
        $html .="<td>".$info->Cuit_relacionado."</td>";
        $html .="<td>".$info->fecha_rechazo."</td>";
        $html .="<td>".$info->nro_cheque."</td>";
        //$html .="<td>".$info->importe."</td>";
        $html .="<td align=right>".number_format($info->importe, 2, ',', ' ')."</td>";
        $html .="<td>".$info->fecha_levantamiento."</td>";
        $html .="<td>".$info->fecha_pago."</td>";
        $html .="<td>".$nro_cheque."</td>";
        break;
      }
      //echo $tabla, " - ", $html; 
      //$stmt  = $connection->prepare("EXEC dbo.cargar_novedades_html $id,'$seccion',$nro_cheque,'$html'");
      $stmt  = $connection->prepare("EXEC dbo.cargar_novedades_html $id,'$tabla',$nro_cheque,'$html','$w_fecha'");
      $stmt->setFetchMode(PDO::FETCH_OBJ);
      if ($stmt) {
        $stmt->execute();
      }
  }

  function obtenerInfoNovedades($connection,$cuit,$id,$tabla,$nro_cheque,$w_fecha){
    //echo " ", $cuit, " ", $id, " ", $tabla, " " ,$nro_cheque, "\n"; 
    $nro_cheque = (int)$nro_cheque;
    
    $stmt  = $connection->prepare("EXEC dbo.obtener_info_novedades '$cuit',$id,'$tabla',$nro_cheque");
    $stmt->setFetchMode(PDO::FETCH_OBJ);
    if ($stmt) {
      $stmt->execute();
    }
    $info = $stmt->fetch();
    
//    InsertarHtmlPorSeccion($info,$seccion);
    parsearHTMLPorSeccion($connection,$info,$tabla,$nro_cheque,$id,$w_fecha);
  }

// echo $w_fecha; die(); 

echo "\nFecha Novedades: ", $w_fecha; 

$connection = new PDO('dblib:host=192.168.10.15;dbname=Fidelitas;charset=utf8','sa','KraDQlo');
//$connection->setAttribute(PDO::SQLSRV_ATTR_QUERY_TIMEOUT, 1); 


$w_hora = date("Y-m-d H:i:s"); 
echo "\n", $w_hora;  
echo " - Juicios";
$stmt  = $connection->prepare("EXEC dbo.monitoreos_batch_9 '$w_fecha'");
$stmt->setFetchMode(PDO::FETCH_OBJ);

 if ($stmt) {
  $stmt->execute();
}

$w_hora = date("Y-m-d H:i:s"); 
echo "\n", $w_hora; 
echo " - Central de Deudores";

$stmt  = $connection->prepare("EXEC dbo.monitoreos_batch_10_NEW '$w_fecha'");
$stmt->setFetchMode(PDO::FETCH_OBJ);

 if ($stmt) {
  $stmt->execute();
}

$w_hora = date("Y-m-d H:i:s"); 
echo "\n", $w_hora; 
echo " - Cancelaciones";

$stmt  = $connection->prepare("EXEC dbo.monitoreos_batch_10_cancela '$w_fecha'");
$stmt->setFetchMode(PDO::FETCH_OBJ);

 if ($stmt) {
  $stmt->execute();
}

$w_hora = date("Y-m-d H:i:s"); 
echo "\n", $w_hora; 
echo " - Arba";

$stmt  = $connection->prepare("EXEC dbo.monitoreos_batch_2_arba '$w_fecha'");
$stmt->setFetchMode(PDO::FETCH_OBJ);

 if ($stmt) {
  $stmt->execute();
}

$w_hora = date("Y-m-d H:i:s"); 
echo "\n", $w_hora; 
echo " - Sircreb";

$stmt  = $connection->prepare("EXEC dbo.monitoreos_batch_2_sircreb '$w_fecha'");
$stmt->setFetchMode(PDO::FETCH_OBJ);

 if ($stmt) {
  $stmt->execute();
}

$w_hora = date("Y-m-d H:i:s"); 
echo "\n", $w_hora; 
echo " - Cheques Rechazados";

$stmt  = $connection->prepare("EXEC dbo.monitoreos_cheques '$w_fecha'");
$stmt->setFetchMode(PDO::FETCH_OBJ);
 if ($stmt) {
  $stmt->execute();
}

$w_hora = date("Y-m-d H:i:s"); 
echo "\n", $w_hora; 
echo " - Balances ";

$stmt  = $connection->prepare("EXEC dbo.monitoreos_batch_7 '$w_fecha'");
$stmt->setFetchMode(PDO::FETCH_OBJ);
 if ($stmt) {
  $stmt->execute();
}

$w_hora = date("Y-m-d H:i:s"); 
echo "\n", $w_hora; 
echo " - Generacion htmls\n";

$stmt  = $connection->prepare("EXEC dbo.obtener_novedades '$w_fecha'");
$stmt->setFetchMode(PDO::FETCH_OBJ);
 if ($stmt) {
  $stmt->execute();
}

$novedades = $stmt->fetchAll();
foreach($novedades as $key =>$novedad){
    $html = obtenerInfoNovedades($connection,$novedad->cuit,$novedad->id,strtolower($novedad->tabla),$novedad->nro_cheque,$w_fecha);
}


$w_hora = date("Y-m-d H:i:s"); 
echo "\n", $w_hora; 
echo " - Envio de mails"; 

// Envio de mails:
      
$mail = new PHPMailer;
//$mail->SMTPDebug = 3;                               // Enable verbose debug output
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.mailgun.org';                     // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'servicio@fidelitas.com.ar';        // SMTP username
$mail->Password = '2sendEmail';                        // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25;                                     // TCP port to connect to

$mail->setFrom('compacto@fidelitas.com.ar', 'Fidelitas S.A.');
$mail->addReplyTo('compacto@fidelitas.com.ar', 'Fidelitas S.A.');
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Servicio de Monitoreo Fidelitas';
  
$stmt  = $connection->prepare("EXEC dbo.monitoreos_envio_mails_todos '$w_fecha'");
$stmt->setFetchMode(PDO::FETCH_OBJ);
 if ($stmt) {
  $stmt->execute();
}

$direcciones_mails = $stmt->fetchAll();
foreach($direcciones_mails as $key =>$dirmail){

    echo "\n" , $dirmail->nombre_cliente, " - ", $dirmail->email , " -> " , $dirmail->novedades, " hay Novedades - "; 
    //$mail->Body    = $dirmail->nombre_cliente . '<br><br>Hay novedades en su Cartera de Clientes. <a href="http://www.fidelitas.com.ar">Haga click aqui</a>';
    //$mail->AltBody = 'Hay novedades del dia de ayer. Ingrese a la web de fidelitas para verlas.';

    $mail->Body = '<html><head>';
    $mail->Body .= '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">';
    $mail->Body .= '<title>Fidelitas </title>';
    $mail->Body .= '<style type="text/css">';
    $mail->Body .= 'BODY {margin:0px; FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY:  Verdana, Tahoma, Arial, Helvetica, sans-serif; BACKGROUND-COLOR: #ffffff }';
    $mail->Body .= 'P,TD,TH,DIV,SPAN {FONT-SIZE: 12px; COLOR: #000000; FONT-FAMILY:  Verdana, Tahoma, Arial, Helvetica, sans-serif;}';
    $mail->Body .= 'B, STRONG {FONT-WEIGHT: bold}';
    $mail->Body .= 'I {FONT-STYLE: italic}';
    $mail->Body .= 'EM {FONT-STYLE: italic}';
    $mail->Body .= 'LI.bullet {LIST-STYLE-IMAGE: url(http://imperium.adm.fidelitas.com.ar/images/swpk350Bullet.gif); LIST-STYLE-TYPE: circle}';
    $mail->Body .= 'SMALL {FONT-SIZE: 10px}';
    $mail->Body .= 'BIG {FONT-SIZE: 14px; FONT-WEIGHT: bold;}';
    $mail->Body .= 'INPUT, SELECT, TEXTAREA {FONT-SIZE: 12px; FONT-FAMILY:  Tahoma, Arial, Helvetica, sans-serif}';
    $mail->Body .= 'A {FONT-WEIGHT: bold; COLOR: #083C96; text-decoration: none;  }';
    $mail->Body .= 'A:hover {FONT-WEIGHT: bold; COLOR: #000000; TEXT-DECORATION: underline}';
    $mail->Body .= 'TABLE#HeaderTable {border-collapse:collapse; padding: 2px; height: 50px; width: 100%; background-color: #FFFFFF; BORDER-LEFT: #F1F9FF 1px solid; BORDER-TOP: #c8d6bc 1px solid; BORDER-RIGHT: #c8d6bc 1px solid; BORDER-BOTTOM: #c8d6bc 1px solid;  empty-cells: show;}';
    $mail->Body .= '</style>';
    $mail->Body .= '</head>';
    $mail->Body .= '<body>';
    $mail->Body .= '<table width="100%" border="0" cellspacing="0" cellpadding="3" class="HeaderTable">';
    $mail->Body .= '<tr>';
    $mail->Body .= '<td valign="top" valign="middle"><img src="http://imperium.adm.fidelitas.com.ar/images/fidelitas_email.png" alt="" border="0"></td>';
    $mail->Body .= '</tr>';
    $mail->Body .= '<tr>';
    $mail->Body .= '<td>';
    if ($dirmail->novedades == 'SI')
    {
      $mail->Body .= '<br>Sr. ' . $dirmail->nombre_cliente . ':<br><br>Le informamos que al d&iacute;a ' . $w_fecha_dmy . ' se registraron novedades dentro de su cartera de CUITs en monitoreo';
      $mail->Body .= '<br>Podr&aacute; acceder a las mismas, ingresando a www.fidelitas.com.ar con su usuario y contrase&ntilde;a habitual.';
      $mail->Body .= '<br><br>Atentamente.<br>Fidelitas S.A.<br>';
      $mail->Body .= '</td>';
      $mail->Body .= '</tr>';
      $mail->Body .= '</table></body></html>';

      $mail->AltBody = 'Le informamos que al dia ' . $w_fecha_dmy . ' se registraron novedades dentro de su cartera de CUITs en monitoreo. ' .
                       ' Podra acceder a las mismas, ingresando a www.fidelitas.com.ar con su usuario y contrase&ntilde;a habitual.';
    }
    else 
    {
      $mail->Body .= '<br>Sr. ' . $dirmail->nombre_cliente . ':<br><br>Le informamos que al d&iacute;a ' . $w_fecha_dmy . ' no se registraron novedades dentro de su cartera de CUITs en monitoreo';
      $mail->Body .= '<br><br>Atentamente.<br>Fidelitas S.A.<br>';
      $mail->Body .= '</td>';
      $mail->Body .= '</tr>';
      $mail->Body .= '</table></body></html>';

      $mail->AltBody = 'Le informamos que al dia ' . $w_fecha_dmy . ' no se registraron novedades dentro de su cartera de CUITs en monitoreo. ';
    }
    $mail->ClearAddresses();  // each AddAddress add to list
    $mail->ClearCCs();
    $mail->ClearBCCs();
    $mail->addAddress($dirmail->email); 
    $mail->addBCC('alejandro.burgol@fidelitas.com.ar');
    $mail->addBCC('maria.soria@fidelitas.com.ar');

    if(!$mail->send()) {
        echo 'Message could not be sent. ';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }

}

$w_hora = date("Y-m-d H:i:s"); 
echo "\n\n", $w_hora; 
echo " - Fin del Proceso\n\n"; 

?>
