<?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=TRIM(utf8_decode($_SESSION["empNom"]));
$empNomc=utf8_decode($_SESSION["empNomc"]);
$empDir=utf8_decode($_SESSION["empDir"]);
$empNit=$_SESSION["empNit"];
$usuNom = utf8_decode($_SESSION['usuNom']);

$numdoc=$_POST["numdoc"];
$seriedoc=$_POST["selTipoCod"];
$TdocNom=$_POST["TdocNom"];
$totLetras=$_POST["totLetras"];
$correoe=$_POST["correoe"];
$correoe1=$_POST["correoe1"];
$correoe2=$_POST["correoe2"];
$idinterno=$_POST["idinterno"];

$arrayError=array();

# QUERYS
$sFactura = "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
    FROM facturas fac
    WHERE fact_emp='$empCod' AND fact_transac='$idinterno'";

$sFact_det = "SELECT * FROM fact_det WHERE factd_emp='$empCod' AND factd_transac='$idinterno'";

$lineWidth=19.5;
$lineHeight=0.4;

class generatePDF extends PDF_MC_Table {
    function Header() {
    }
    
    function Footer() { 
        // Posición: a 1,5 cm del final
    /*    $func = new functions();
        $this->SetY(-2);
        $this->SetFont("Arial","I",7);
        $this->Cell(0,1,strftime("%d/%m/%Y %T"),0,0,"L");   */
    }
}


# GENERAR PDF
//$pdf = new generatePDF("P", "cm", "A4");
$pdf = new generatePDF("P", "cm", "Letter");
# EJECUCION DE QUERYS
$db = new dbExec();

$func = new functions();

$select["facturas"] = $db->query($sFactura);
$select["fact_det"] = $db->query($sFact_det);

$rec = $db->fetchAssoc($select["facturas"]);


    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       = '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->addAddress($correoe);

/*        while ($rec = $db->fetchAssoc($select["cliencc"])) {
            $mail->addAddress($rec["cm_mail"]);
        }  */
        if ($correoe1 != "") {
           $mail->addAddress($correoe1);
        }
        if ($correoe2 != "") {
          $mail->addAddress($correoe2);
        }
        $mail->AddStringAttachment($emailAttachment, utf8_decode('Factura.pdf'), 'base64', 'application/pdf');
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Factura '.$empNomc;
        $mail->Body    = utf8_decode('Buena día estimado Cliente,<br><br>Adjunto Factura Electronica');

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


    //La linea de abajo se desbloquea, si se puede configurar media carta en la impresora que usen
//    $pdf->AddPage();

$db->close();

//$pdf->Output(utf8_decode("Recibos").".pdf","I");
// 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);
?>