<?php

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/coneccion/conecta_pdo.php';

require __DIR__ . '/helpers/LockHelper.php';

use Pheanstalk\Pheanstalk;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;


$lock = new LockHelper('pheanstalk_envio.lock');

if($lock->existeLock())
    die('Lock activado.');
$lock->creaLock();


$pheanstalk = Pheanstalk::create('127.0.0.1');
$watch = 'EnviaMail';
// we want jobs from 'testtube' only.
$pheanstalk->watch( $watch );

echo " :) Escuchando en $watch ".date("Y-m-d h:r:s")."...".PHP_EOL;

// this hangs until a Job is produced.
while($job = $pheanstalk->reserve(0)){


    //try {
        $datos = json_decode( $job->getData(), true);

        //envio email
        $estado_envio = enviaMail ($datos);
        if ($estado_envio == true) {
            echo "se ha enviado el documento";
        }else{
            echo "Error: ".$estado_envio;
        }
        //sleep(2);
        // If it's going to take a long time, periodically
        // tell beanstalk we're alive to stop it rescheduling the job.
        //$pheanstalk->touch($job);
        //sleep(2);

        // eventually we're done, delete job.
        $pheanstalk->delete($job);
    /*}
    catch(\Exception $e) {
        // handle exception.
        // and let some other worker retry.
        $pheanstalk->release($job);
    }*/
}

echo 'No hay tareas pendientes.'.PHP_EOL;

$lock->destruyeLock();


function consultaDTE($datos){
    //https://api.bigdte.cl/v1/pdfs/".$rut_empresa."/".$tipo."/".$folio,
    $rut_empresa = $datos['rut_empresa'];
    $tipo = $datos['tipo'];
    $folio = $datos['folio'];
    $nombre_contacto = $datos['nombre_contacto'];
    $email_contacto = $datos['email_contacto'];

    $api = new RestClient([
        'base_url' => "https://api.bigdte.cl/v1/",
        //'format' => "json",
         // https://dev.twitter.com/docs/auth/application-only-auth
        //'headers' => ['Authorization' => 'Bearer '.OAUTH_BEARER],
        'headers' => ['x-api-key' => 'eM+Gz/k/6WUFqOj3PksDBryGmKCspxrpJEcNYd6EGgc='],
    ]);

    $url = "pdfs/".$rut_empresa."/".$tipo."/".$folio;

    $result = $api->get($url);
    //print_r($result);

    //$result = $api->get("search/tweets", ['q' => "#php"]);
    // GET http://api.twitter.com/1.1/search/tweets.json?q=%23php

    $url_pdf = "";
    if($result->info->http_code == 200){
        $url_pdf = $result->decode_response();
    }

    return $url_pdf;

}

function enviaMail ($datos){
    $rut_empresa = $datos['rut_empresa'];
    $tipo = $datos['tipo'];
    $folio = $datos['folio'];
    $nombre_contacto = $datos['nombre_contacto'];
    $email_contacto = $datos['email_contacto'];


    $coneccion = conectaPDO();
    $coneccion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);



    $consulta = "SELECT * FROM tbl_config_cobranza WHERE ID_EMPRESA=:rut_empresa ";
    $consulta = $coneccion->prepare($consulta);
    $consulta->bindValue(':rut_empresa', $rut_empresa, PDO::PARAM_STR);
    $consulta->execute();
    $consulta = $consulta->fetch(PDO::FETCH_ASSOC);
    $email_dte_envia = $consulta['api'];
    $email_dte_copia = $consulta['api_cc'];

    //consultaDTE
    $url_pdf = consultaDTE($datos);
    //print_r($url_pdf->signedURL);

    $tmpfname = tempnam('.', 'DOCADJ');
    $handle = fopen($tmpfname, 'w');
    fwrite($handle, file_get_contents($url_pdf->signedURL));
    fclose($handle);




    $body = bodyMail($datos);


    //log envios
    $fecha = date('Y-m-d');
    $hora = date('H:i:s');


    $consulta = "INSERT INTO `detalle_envio` (`RUT_EMPRESA`, `FECHA_ENVIO`, `EMAIL_ENVIO`, `HORA_ENVIO`, `TIPO_DOC`, `FOLIO_DOC`, `ADICIONAL6`, `ID_ADICIONALES`) VALUES (:rut_empresa,:fecha,:email_contacto,:hora,:tipo,:folio,'','')";
    $consulta = $coneccion->prepare($consulta);
    $consulta->bindValue(':rut_empresa', $rut_empresa, PDO::PARAM_STR);
    $consulta->bindValue(':fecha', $fecha, PDO::PARAM_STR);
    $consulta->bindValue(':email_contacto', $email_contacto, PDO::PARAM_STR);
    $consulta->bindValue(':hora', $hora, PDO::PARAM_STR);
    $consulta->bindValue(':tipo', $tipo, PDO::PARAM_STR);
    $consulta->bindValue(':folio', $folio, PDO::PARAM_STR);
    $consulta->execute();

    // Instantiation and passing `true` enables exceptions
    $mail = new PHPMailer(true);


    try {
        //Server settings
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;          // Enable verbose debug output
        $mail->isSMTP();                                // Send using SMTP
        $mail->Host = 'softnet.cl';        // Set the SMTP server to send through
        $mail->SMTPAuth   = true;                       // Enable SMTP authentication
        $mail->Username   = 'erp@softnet.cl';                     // SMTP username
        $mail->Password   = '7852';                               // SMTP password
        //$mail->From = $email_dte_envia;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
        $mail->Port       = 587;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above


        //$email_dte_copia


        //Recipients
        $mail->setFrom($email_dte_envia);
        //$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
        $mail->addAddress($email_contacto,$nombre_contacto);               // Name is optional
        //$mail->addReplyTo('info@example.com', 'Information');
        //$mail->addCC('cc@example.com');
        //$mail->addBCC('bcc@example.com');

        // Attachments
        //$mail->addAttachment($fichero);         // Add attachments
        $mail->AddAttachment($tmpfname, 'DTE_T'.$tipo.'_F'.$folio."_R$rut_empresa.pdf");
        //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

        // Content
        $mail->isHTML(true);                                  // Set email format to HTML
        // Activo condificacción utf-8
        $mail->CharSet = 'UTF-8';

        $mail->Subject = "Envio de Documento Electronico Folio Nº ".$folio;
        $mail->Body    = $body;
        //$mail->AltBody = 'Aca no recuerdo que se agrega';

        $mail->send();




        return true;
    } catch (Exception $e) {

        return "Mensaje no pudo ser enviado. Mailer Error: {$mail->ErrorInfo}";
    }

    unlink($tmpfname);
}


function bodyMail($datos){

    $rut_empresa = $datos['rut_empresa'];
    $tipo = $datos['tipo'];
    $folio = $datos['folio'];
    $nombre_contacto = $datos['nombre_contacto'];
    $email_contacto = $datos['email_contacto'];




    //sin imagenes
    if ($rut_empresa == '76525599-6' or $rut_empresa == '22222222-2') {
        $bodytext = "
        <head>
          <meta charset='utf-8'>
          <title>Softnet</title>
          <style>
            @import url('https://fonts.googleapis.com/css?family=Titillium+Web:400,700');
            body{
              font-family: 'Titillium Web', sans-serif;
            }
            body strong{
              font-weight: bold;
            }
          </style>
        </head>
        <body style='background-color:#f2f2f2; font-size: 12px; padding:0px; border:0px; margin:0px;'>

          <div style='box-sizing:border-box; width:90%; margin:auto; padding:2%; overflow:auto; background-color:#fff; padding:5%; '>
            <div style='overflow:auto;'>
              <div style='display:inline-block; width:50%; float:left;'>
                <p style='margin:0; margin-bottom:10px; font-size:13px;'>Estimado(a) :</p>
                <strong style='text-transform:uppercase;'>".utf8_encode($nombre_contacto)."</strong>
              </div>
              <div style='display:inline-block; width:50%; float:left;'>
                <p style='margin:0; margin-bottom:10px; font-size:13px;'>
                Se adjunta documento.
                </p>

              </div>

            </div>
            <div style='display:block; width:200px; margin-left: -8%; border-top: solid 1px #d6d6d6 !important; margin-bottom:2.5em;'></div>
            <p style='font-size:13px;'></p>
            <p style='font-size:13px; margin-bottom:0px;'>Atentamente.</p>
          </div>
        </body>

        ";
    }else{
        $bodytext = "
          <head>
            <meta charset='utf-8'>
            <title>Softnet</title>
            <style>
              @import url('https://fonts.googleapis.com/css?family=Titillium+Web:400,700');
              body{
                font-family: 'Titillium Web', sans-serif;
              }
              body strong{
                font-weight: bold;
              }
            </style>
          </head>
          <body style='background-color:#f2f2f2; font-size: 12px; padding:0px; border:0px; margin:0px;'>
            <div style='background-color:#1b526b; box-sizing:border-box; width:90%; margin:auto; padding:2%; padding-bottom:20px; height:auto; overflow:auto; position:relative;'>
              <img style='width:150px; min-width:100px; margin-top:1em;' src='http://www.erpsoftnet.cl/correo-sistem/logo.png' alt=''>
              <div style='position:absolute; margin-top:0px; right: 30px; bottom: 10px; margin-right:-15px;'>
                <div style='text-align:right; color:#fff; font-size:1em; letter-spacing:2px; margin-bottom:5px; margin-right:10px;'>S&iacute;guenos</div>
                <a href='https://www.facebook.com/erpsoftnet/?ref=settings' target='_blank' style='margin:10px;' ><img src='http://www.erpsoftnet.cl/correo-sistem/facebook.png' alt=''></a>
                <a href='https://twitter.com/softnetcl' target='_blank' style='margin:10px;' ><img src='http://www.erpsoftnet.cl/correo-sistem/twitter.png' alt=''></a>
                <a href='https://www.youtube.com/channel/UCM2Yl07IbCb4Y-eINU4XKfg' target='_blank' style='margin:10px;' ><img src='http://www.erpsoftnet.cl/correo-sistem/youtube.png' alt=''></a>
              </div>
            </div>
            <div style='height:7px; background-color:#32839f; width:90%; margin:auto; box-sizing: border-box;'></div>
            <div style='box-sizing:border-box; width:90%; margin:auto; padding:2%; overflow:auto; background-color:#fff; padding:5%; '>
              <div style='overflow:auto;'>
                <div style='display:inline-block; width:50%; float:left;'>
                  <p style='margin:0; margin-bottom:10px; font-size:13px;'>Estimado(a) :</p>
                  <strong style='text-transform:uppercase;'>".utf8_encode($nombre_contacto)."</strong>
                </div>
                <div style='display:inline-block; width:50%; float:left;'>
                  <p style='margin:0; margin-bottom:10px; font-size:13px;'>
                  Se adjunta documento.
                  </p>

                </div>

              </div>
              <div style='display:block; width:200px; margin-left: -8%; border-top: solid 1px #d6d6d6 !important; margin-bottom:2.5em;'></div>
              <p style='font-size:13px;'></p>
              <p style='font-size:13px; margin-bottom:0px;'>Atentamente.</p>
            </div>
          </body>
        ";
    }

    return utf8_encode($bodytext);
}

?>
