<?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"]);
$pCaja=utf8_decode($_SESSION["pCaja"]);
$cajNombre=utf8_decode($_SESSION["cajNombre"]);

$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 *, SUM(fact_efec) AS fact_sefec, SUM(fact_exenval) AS fact_sexenval, SUM(fact_chval) AS fact_schval, SUM(fact_tarj) AS fact_starj, 
                  SUM(fact_vale) AS fact_svale, SUM(fact_cred) AS fact_scred, SUM(fact_dolares) AS fact_sdolares 
                  FROM facturas 
                  WHERE fact_emp='$empCod' AND fact_caja='$pCaja' AND fact_fec>='$dtFecIni' AND fact_fec<='$dtFecFin' GROUP BY fact_emp,fact_caja";
} else {
    $sFacturas = "SELECT *, SUM(fact_efec) AS fact_sefec, SUM(fact_exenval) AS fact_sexenval, SUM(fact_chval) AS fact_schval, SUM(fact_tarj) AS fact_starj, 
                  SUM(fact_vale) AS fact_svale, SUM(fact_cred) AS fact_scred, SUM(fact_dolares) AS fact_sdolares 
                  FROM facturas 
                  WHERE fact_emp='$empCod' AND fact_caja='$pCaja' AND fact_fec>='$dtFecIni' AND fact_fec<='$dtFecFin' AND fact_vend='$selVend' GROUP BY fact_emp,fact_caja,fact_vend";
}
# 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=19;
$lineHeight=0.65;
class generatePDF extends PDF_MC_Table {
    function Header() {
        global $empNom, $pCaja, $lineWidth, $lineHeight, $selVendNom, $cajNombre;
        $lineWidth=22;
        $dtFecIni = date('d/m/Y', strtotime($_POST["dtFecIni"]));
        $dtFecFin = date('d/m/Y', strtotime($_POST["dtFecFin"]));
        $this->SetMargins(2, 1, 2);
        $this->SetFont("Arial","B",16);
        $this->Cell(0, 0, "", 0, 1);
        $this->MultiAlignCell($lineWidth, $lineHeight, utf8_decode($empNom),0,1,"L");
        $this->MultiAlignCell($lineWidth/1, $lineHeight, "CORTE DE CAJA DEL $dtFecIni AL $dtFecFin",0,1,"L");
        $this->SetFont("Arial","B",12);
        $this->MultiAlignCell($lineWidth/1, $lineHeight, "CORRESPONDIENTE A $selVendNom  Caja: $cajNombre",0,1,"L");
        $this->Ln();

        // Derecha
        $this->SetY(.7);
        $this->Cell(0,1, utf8_decode("PÁGINA: ".((string)($this->PageNo()))),0,1,"R");
        $this->SetY(3.2);
        $lineWidth=14;
        $header = array(utf8_decode("RUBRO"),"MONTO");
        $this->SetFont("","B",15);
        $this->SetWidths(array(10,4));
        $this->SetAligns(array("C","C"));
        $this->RowLHColor($header, $lineWidth, $lineHeight, array(192,192,192), array(0,0,0));
        $this->SetFont("");
        $this->SetAligns(array("L","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("P", "cm", "Letter");
//$pdf = new FPDF('P','mm',array(500,150));
$pdf->AddPage();

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

$totDocumentos=0;
$totDocumentos += round(($rec["fact_sefec"]+$rec["fact_sexenval"]+$rec["fact_schval"]+$rec["fact_starj"]+$rec["fact_svale"]+$rec["fact_scred"]), 2);

$body = array("EFECTIVO",number_format($rec["fact_sefec"], 2),);
$pdf->RowBorderHidden($body, $lineHeight);
$body = array("EXENCION",number_format($rec["fact_sexenval"], 2),);
$pdf->RowBorderHidden($body, $lineHeight);
$body = array("VALOR CHEQUES",number_format($rec["fact_schval"], 2),);
$pdf->RowBorderHidden($body, $lineHeight);
$body = array("TARJETA CREDITO",number_format($rec["fact_starj"], 2),);
$pdf->RowBorderHidden($body, $lineHeight);
$body = array("VALE",number_format($rec["fact_svale"], 2),);
$pdf->RowBorderHidden($body, $lineHeight);
$body = array("CREDITO",number_format($rec["fact_scred"], 2),);
$pdf->RowBorderHidden($body, $lineHeight);
$pdf->line($pdf->GetX(), $pdf->GetY(), 16, $pdf->GetY());
$body = array(
    "                        TOTAL MONEDA LOCAL",
    number_format($totDocumentos, 2),
);
$pdf->RowBorderHidden($body, $lineHeight);
$pdf->line($pdf->GetX(), $pdf->GetY(), 16, $pdf->GetY());
$body = array("DOLARES",number_format($rec["fact_sdolares"], 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       = 'asjireh.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'facturacionsenoro@asjireh.com';
        $mail->Password   = 'so_25341630';
        $mail->SMTPSecure = 'ssl';//PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 465;

        //Recipients
        $mail->setFrom('facturacionsenoro@asjireh.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('CortedeCaja.pdf'), 'base64', 'application/pdf');
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Resumen Corte de Caja: '.$cajNombre;
        $mail->Body    = utf8_decode('Buena día,<br><br>Adjunto Corte de Caja');

        $mail->send();
    } catch (Exception $e) {
        array_push($arrayError, array("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);
?>