<?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');

// 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']);
$pCaja=utf8_decode($_SESSION["pCaja"]);
$correoe=$_POST["correoe"];
$correoe1=$_POST["correoe1"];
$correoe2=$_POST["correoe2"];

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

$arrayError=array();

# QUERYS
function sFacturas($IDInterno) {
    global $empCod, $pCaja;
    return "SELECT *, 
    TRIM(fac.fact_nom) AS fact_nom,
    TRIM(fac.fact_dir) AS fact_dir,
    TRIM(fac.fact_tel) AS fact_tel,
    TRIM(fac.fact_nit) AS fact_nit,
    TRIM(ca.caj_resolu) AS caj_resolu,
    TRIM(ca.caj_nomt) AS caj_nomt,
    TRIM(ca.caj_dirt) AS caj_dirt,
    TRIM(ca.caj_telt) AS caj_telt,
    TRIM(ca.caj_mailt) AS caj_mailt,
    TRIM(ca.caj_leyen1) AS caj_leyen1,
    TRIM(ca.caj_leyen2) AS caj_leyen2,
    TRIM(res.res_num) AS res_num,
    TRIM(res.res_serie) AS res_serie,
    TRIM(vend.vend_nom) AS vend_serie
    FROM facturas fac
    LEFT JOIN tipov tv ON fac.fact_tipo=tv.tv_cod
    LEFT JOIN caja ca ON ca.caj_emp='$empCod' AND ca.caj_cod='$pCaja'
    LEFT JOIN resolu res ON res.res_emp='$empCod' AND res.res_num=ca.caj_resolu
    LEFT JOIN vendedor vend ON fac.fact_vend=vend.vend_cod 
    WHERE fact_emp='$empCod' AND fact_transac='$IDInterno'";
}

function sFact_det($IDInterno) {
    global $empCod, $pCaja;
    return "SELECT *,
            TRIM(factd_cod) AS factd_cod,
            TRIM(factd_desc) AS factd_desc
            FROM fact_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;
    $idinterno =  $obj->IDInterno;
//    $correoe =  $obj->correo;
    $select["facturas"] = $db->query(sFacturas($IDInterno));
    $select["fact_det"] = $db->query(sFact_det($IDInterno));
    $rec = $db->fetchAssoc($select["facturas"]);
    $totLetras = $obj->totLetras;
    $TdocNom = $rec["tv_nom"];

    $pdf = new generatePDF("P","cm", "Letter");

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

    include('../felPrint/FEL.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       = 'smtp.titan.email';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'facturacionarcoiris@asesoriaensis.com';
        $mail->Password   = 'dE628UC9Vr';

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

        //Recipients
        $mail->setFrom('facturacionarcoiris@asesoriaensis.com', $empNomc);
*/
        $mail->Host       = 'asesoriaensis2022.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'arcoiris@asesoriaensis2022.com';
        $mail->Password   = 'Sjireh_110263%';

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

        //Recipients
        $mail->setFrom('arcoiris@asesoriaensis2022.com', $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('facturaelectronica@megared.com.gt');
        $mail->AddStringAttachment($emailAttachment, utf8_decode('Factura.pdf'), 'base64', 'application/pdf');
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Factura '.$empNomc;
        $mail->Body    = utf8_decode('Buen día estimado Cliente,<br><br>Adjunto Factura');

        $mail->send();
    } catch (Exception $e) {
        array_push($arrayError, array("Factura No. "=>$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['numdoc']}</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);

?>