<?php
include_once("../../../php/sessionStart.php"); 
include_once("../../../php/db/dbExec.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=$_SESSION["empNom"];
$empNomc=utf8_decode($_SESSION["empNomc"]);

$dtFecIni = $_POST["dtFecIni"];
$dtFecFin = $_POST["dtFecFin"];
$selVend = $_POST["selVend"];
$selVendNom = TRIM($_POST["selVendNom"]);
$correoe = TRIM($_POST["correoe"]);
$correoe1 = TRIM($_POST["correoe1"]);
$correoe2 = TRIM($_POST["correoe2"]);

$arrayError=array();

# QUERYS
if ($selVend=="000"){
    $sFacturas = "SELECT *
              FROM facturas 
              WHERE fact_emp='$empCod' AND fact_fec>='$dtFecIni' AND fact_fec<='$dtFecFin' ORDER BY fact_emp,fact_fec,fact_serie,fact_num";
} else {
    $sFacturas = "SELECT *
              FROM facturas 
              WHERE fact_emp='$empCod' AND fact_fec>='$dtFecIni' AND fact_fec<='$dtFecFin' AND fact_vend='$selVend' ORDER BY fact_emp,fact_fec,fact_serie,fact_num";
}

# EJECUCION DE QUERYS
$db = new dbExec();

//$s = $sFacturas;
/*$cr["documentos"] = "";
$cr["formaPago"] = "";
switch ($selTipoCod[0]) {
    case 'F':
        $s = $sFacturas;
        $cr["documentos"] = utf8_decode("DOCUMENTOS: {$_GET["crAnuNom"]}");
        $cr["formaPago"] = utf8_decode("FORMA DE PAGO: {$_GET["crFpagNom"]}");
        break;
    
    default:
        $s = $sNotas;
        break;
}*/
$select["documentos"] = $db->query($sFacturas);

$lineWidth=17.5;
$lineHeight=0.35;
class generatePDF extends PDF_MC_Table {
    function Header() {
        global $empNom, $lineWidth, $lineHeight, $selVendNom,$cajNombre;
        $dtFecIni = date('d/m/Y', strtotime($_POST["dtFecIni"]));
        $dtFecFin = date('d/m/Y', strtotime($_POST["dtFecFin"]));
        $this->SetMargins(2, 1, 2);
        $this->SetFont("Arial","",9);
        $this->Cell(0, 0, "", 0, 1);
        $this->MultiAlignCell($lineWidth, $lineHeight, utf8_decode($empNom),0,1,"L");
        $this->MultiAlignCell($lineWidth/1, $lineHeight, "CORTE DE CAJA DETALLADO DEL $dtFecIni AL $dtFecFin",0,1,"L");
        $this->MultiAlignCell($lineWidth/1, $lineHeight, "CORRESPONDIENTES A $selVendNom",0,1,"L");

        // Derecha
        $this->SetY(.7);
        $this->Cell(0,1, utf8_decode("PÁGINA: ".((string)($this->PageNo()))),0,1,"R");
        $this->SetY(2.2);

        $header = array("Serie",utf8_decode("Número"),"Fecha","Cliente","Efectivo","Deposito","Tarjeta","Credito","Total");
        $this->SetFont("","B",8);
        $this->SetWidths(array(2,2,2,8,2,2,2,2,2));
        $this->SetAligns(array("C","C","C","C","C","C","C","C","C"));
        $this->RowLHColor($header, $lineWidth, $lineHeight, array(192,192,192), array(0,0,0));
        $this->SetFont("");
        $this->SetAligns(array("L","L","L","L","R","R","R","R","R"));
    }
    
    function Footer() {
        $this->SetY(-1.5);
        $this->SetFont("Arial","I",6);
        $this->Cell(0,1,strftime("%d/%m/%Y %T"),0,0,"C");
    }
}

# GENERAR PDF
$pdf = new generatePDF("L", "cm", "Letter");
//$pdf = new FPDF('P','mm',array(500,150));
$pdf->AddPage();
$sefec = 0;
$sdepo = 0;
$starj = 0;
$scred = 0;
$stotal=0;
while ($rec = $db->fetchAssoc($select["documentos"])) {
    $sefec += round($rec["fact_efec"], 2);
    $sdepo += round($rec["fact_depo"], 2);
    $starj += round($rec["fact_tarj"], 2);
    $scred += round($rec["fact_cred"], 2);
    $total = round($rec["fact_efec"]+$rec["fact_depo"]+$rec["fact_tarj"]+$rec["fact_cred"], 2);
    $stotal += $total;
    $body = array(
        trim($rec["fact_serie"]),
        $rec["fact_num"],
        date('d/m/Y', strtotime($rec["fact_fec"])),
        trim($rec["fact_nom"]),
        ($rec["fact_efec"] != 0) ? number_format($rec["fact_efec"], 2, '.', ',') : "",
        ($rec["fact_depo"] != 0) ? number_format($rec["fact_depo"], 2, '.', ',') : "",
        ($rec["fact_tarj"] != 0) ? number_format($rec["fact_tarj"], 2, '.', ',') : "",
        ($rec["fact_cred"] != 0) ? number_format($rec["fact_cred"], 2, '.', ',') : "",
        ($total != 0) ? number_format($total, 2, '.', ',') : "",
    );
    $pdf->RowBorderHidden($body, $lineHeight);
}
$pdf->line($pdf->GetX(), $pdf->GetY(), 26, $pdf->GetY());
$body = array(
    "",
    "",
    "",
    "                                  TOTAL",
    number_format($sefec, 2),
    number_format($sdepo, 2),
    number_format($starj, 2),
    number_format($scred, 2),
    number_format($stotal, 2),
);
$pdf->RowBorderHidden($body, $lineHeight);

    $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);

        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('DetalleCortedeCaja.pdf'), 'base64', 'application/pdf');
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Detalle Corte de Caja: '.$cajNombre;
        $mail->Body    = utf8_decode('Buena día,<br><br>Adjunto el Detalle del Corte de Caja');

        $mail->send();
    } catch (Exception $e) {
        array_push($arrayError, array("Detalle Corte de Caja", "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['cod']}</td><td class='text-center'>{$row['ErrorInfo']}</td></tr>";
    }
    $text .='</table>';
    $resp = $db->rErrorPublic($title, $text);
} else {
    $resp = $db->rSuccess("Mensaje enviado con éxito");
}

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

?>