<?php
include_once("../../../php/sessionStart.php"); 
include_once("../../../php/db/dbExec.php");
include_once('../../../php/functions.php');
include_once("../../../php/fpdf/functions.php");
include_once('../../../php/timezone.php');
include_once('../../../php/maxExecTime.php');
include_once('../ws/COFIDI/wsExec.php');

// email
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

include_once("../../../php/PHPMailer/src/PHPMailer.php");
include_once("../../../php/PHPMailer/src/SMTP.php");
include_once("../../../php/PHPMailer/src/Exception.php");
// email

$empCod=utf8_decode($_SESSION["empCod"]);
$empNom=utf8_decode($_SESSION["empNom"]);
$empNomc=utf8_decode($_SESSION["empNomc"]);
$empDir=utf8_decode($_SESSION["empDir"]);
$empNit=str_replace('-','',$_SESSION["empNit"]);
$usuNom = utf8_decode($_SESSION['usuNom']);
$correoe=$_POST["correoe"];
$correoe1=$_POST["correoe1"];
$correoe2=$_POST["correoe2"];

$jsonFac=json_decode($_POST['tblFac']);

$arrayError=array();

# QUERYS
function sNotas($IDInterno) {
    global $empCod;
    return "SELECT nc.*,
    TRIM(nc.fact_nom) AS fact_nom,
    TRIM(nc.fact_dir) AS fact_dir,
    TRIM(nc.fact_tel) AS fact_tel,
    TRIM(nc.fact_nit) AS fact_nit,
    nc.fact_fec AS fact_fec,
    fac.fact_fec AS fact_fecf,
    TRIM(tv.tv_nom) AS tv_nom
    FROM notas nc
    LEFT JOIN tipov tv ON nc.fact_tipo=tv.tv_cod
    LEFT JOIN facturas fac ON nc.fact_emp=fac.fact_emp and nc.fact_tipof=fac.fact_serie and nc.fact_numf=fac.fact_num
    WHERE nc.fact_emp='$empCod' AND nc.fact_transac='$IDInterno'";
}

function sNotas_det($IDInterno) {
    global $empCod, $pCaja;
    return "SELECT *,
            TRIM(factd_cod) AS factd_cod,
            TRIM(factd_desc) AS factd_desc
            FROM notas_det WHERE factd_emp='$empCod' AND factd_transac='$IDInterno'";
}

/* function uCliIva($nit) {
    global $empCod, $pCaja, $correoe;
    return "UPDATE clien SET cli_email='$correoe' WHERE cli_nit='$nit'";
} */


$lineWidth=19;
$lineHeight=0.42;
$lineHeight7=042;

# EJECUCION DE QUERYS
$db = new dbExec();
//$db->query($uCliIva);

class generatePDF extends PDF_MC_Table {
    function Header() {
    }
    
    function Footer() { 
    }
}

$db = new dbExec();
$func = new functions();

# GENERAR PDF
//$pdf = new generatePDF("P","cm", "Letter");

foreach ($jsonFac as $obj) {
    $IDInterno =  $obj->IDInterno;
    //$correoe =  $obj->correo;
    $select["notas"] = $db->query(sNotas($IDInterno));
    $select["notas_det"] = $db->query(sNotas_det($IDInterno));
    $rec = $db->fetchAssoc($select["notas"]);
    $totLetras = $obj->totLetras;
    $TdocNom = $rec["tv_nom"];
    $fecp=$obj->fecp;
    $pdf = new generatePDF("P","cm", "Letter");

//    $nit=$rec["fact_nit"];
//    $db->query(uCliIva($nit));

    include('../felPrint/FELNC.php');

    $emailAttachment = $pdf->Output('','S');
    // Enviar por email
    $mail = new PHPMailer(true);

    try {
        //Server settings
        $mail->SMTPDebug = 0;//SMTP::DEBUG_SERVER;
        $mail->isSMTP();

        $mail->Host       = 'asesoriaensis2022.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'facturacion.colegiojrg@asesoriaensis2022.com';
        $mail->Password   = 'Sjireh_110263%';

        $mail->SMTPSecure = 'ssl';//PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 465;

        //Recipients
        $mail->setFrom('facturacion.colegiojrg@asesoriaensis2022.com', $empNomc);

/*        $mail->Host       = 'smtp.greenprint.com.gt';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'asistente@greenprint.com.gt';
        $mail->Password   = 'GPfacturas!';
        $mail->SMTPSecure = 'ssl';//PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 465;

        //Recipients
        $mail->setFrom('asistente@greenprint.com.gt', $empNomc); */


        $mail->addAddress($correoe);
        if ($correoe1 != "") {
           $mail->addAddress($correoe1);
        }
        if ($correoe2 != "") {
          $mail->addAddress($correoe2);
        }

/*        while ($rec = $db->fetchAssoc($select["cliencc"])) {
            $mail->addAddress($rec["cm_mail"]);
        }  */
        $mail->addCC('asistente@greenprint.com.gt');
        $mail->AddStringAttachment($emailAttachment, utf8_decode('Nota Credito.pdf'), 'base64', 'application/pdf');
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Notas de Credito '.$empNomc;
        $mail->Body    = utf8_decode('Buena día estimado Cliente,<br><br>Adjunto Nota de Credito Electronica');

        $mail->send();
    } catch (Exception $e) {
        array_push($arrayError, array("Nota Credito"=>$rec["fact_num"], "ErrorInfo"=>''.$mail->ErrorInfo));
    }
}

$db->close();

// Por si no se pudo guardar la factura de algún cliente
$sizeError = sizeof($arrayError);
$title = "";
$text = "";
if ($sizeError != 0) {
    $title = "email";
    $text .='<div style="margin: 0 auto"><b>No se pudo enviar todos los mensajes</b></div>';
    $text .='<table style="margin: 0 auto"><tr><td width="70">Código</td><td width="">Descripción</td>';
    foreach($arrayError as $row) {
        $text .="<tr><td class='text-center'>{$row['Factura']}</td><td class='text-center'>{$row['ErrorInfo']}</td></tr>";
    }
    $text .='</table>';
    $resp = $db->rErrorPublic($title, $text);
} else {
    $resp = $db->rSuccess("Mensajes enviados con éxito");
}

//return $func->jsonEncodeArray($resp, "msg");
echo json_encode($resp);

?>