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

require '../../../ticket/autoload.php'; 
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;

$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"]);
$establecimiento=$_SESSION['establecimiento'];

$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_nom,
    TRIM(vend.vend_pnom) AS vend_pnom
    FROM facturas fac
    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'";
}

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

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

# GENERAR PDF

foreach ($jsonFac as $obj) {
    $IDInterno =  $obj->IDInterno;
    $select["facturas"] = $db->query(sFacturas($IDInterno));
    $select["fact_det"] = $db->query(sFact_det($IDInterno));
    $rec = $db->fetchAssoc($select["facturas"]);

    // Definir y activar impresoar
    $nombre_impresora = "POS-80"; 
    //$nombre_impresora = "EPSON TM-T20II Receipt5";
    $connector = new WindowsPrintConnector($nombre_impresora);
    $printer = new Printer($connector);

    $lineHeight7 = .6;
    /*$img = '../img/logo2.jpg';
    $pdf->Image($img,1,1,2.2);
    $pdf->SetMargins(1, 1, 1);
    $pdf->SetY(1.75);
    $pdf->Cell(0, 0, "", 0, 1);*/
    //$pdf->Cell($lineWidth/4, $lineHeight7, "");
    $printer->setJustification(Printer::JUSTIFY_CENTER);
    $printer->text(utf8_encode($empNom) . "\n");
    $printer->text(utf8_encode($rec["caj_nomt"]) . "\n");
//    $printer->setJustification(Printer::JUSTIFY_LEFT);
    $printer->text(utf8_encode($rec["caj_dirt"]) . "\n");
    $printer->setJustification(Printer::JUSTIFY_CENTER);
    $printer->text("TELEFONO: ".$rec["caj_telt"] . "\n");
    $printer->text("NIT: ".$empNit . "\n");
    $printer->text("DOCUMENTO TRIBUTARIO ELECTRONICO" . "\n");
    $printer->text("FACTURA ELECTRONICA" . "\n");
    $printer->setJustification(Printer::JUSTIFY_LEFT);
    $printer->text("Serie: ".$rec["fact_serie"]." Numero: ".$rec["fact_num"] . "\n");
    $printer->text("Fecha: ".strftime("%d/%m/%Y", strtotime($rec["fact_fec"])) . "\n");
    $printer->text("Cliente: ".utf8_encode($rec["fact_nom"]) . "\n");
    $printer->text("Direccion: ".$rec["fact_dir"] . "\n");
    $printer->text("Nit: ".$rec["fact_nit"] . "\n");
    $printer->text("ID Interno: ".$rec["fact_idinterno"] . "\n");
    $printer->text("------------------------------------------------" . "\n");

    // Derecha
    $y = 1.3;
    $x = 9;

    //$pdf->Ln();

    $lineHeight=0.4;
    $printer->text("Cant.  "."Descripcion           "." Unit.  "."  Total" . "\n");

    // Lineas separadoras del detalle
    $detX = 0;
    $sumsub=0;
    $sumdescv=0;
    $sumtot=0;
    $sumExen=0;
    $sumGrav=0;
    while ($recDet = $db->fetchAssoc($select["fact_det"])) {
        $lcant=strlen(TRIM($recDet["factd_cant"]))-3;
        if ($lcant>7) {
            $difcant=0;
        } else {
          $difcant=7-$lcant;
        }  
        $spacant="";
        if ($difcant<7 && $difcant>0) {
            for ($q=1; $q < $difcant+1; $q++) { 
                $spacant=$spacant." ";
            }
        }
        $desc=substr($recDet["factd_desc"],0,22);
        $ldesc=strlen($recDet["factd_desc"]);
        if ($ldesc>22) {
            $difdesc=0;
            $desc1=substr($recDet["factd_desc"],22,44);
        } else {
          $difdesc=22-$ldesc;
          $desc1="";
        }  
        $spadesc="";
        if ($difdesc<22 && $difdesc>0) {
            for ($q=1; $q < $difdesc+1; $q++) { 
                $spadesc=$spadesc." ";
            }
        }

        if ($recDet["factd_exensn"]=='S') {
            $printer->text(number_format($recDet["factd_cant"],0).$spacant.$desc.$spadesc." ".number_format(round(($recDet["factd_tot"]/$recDet["factd_cant"]),4),4)." ".number_format($recDet["factd_tot"],2).' E' . "\n");
                $sumExen+=$recDet["factd_tot"];
        } else {
            $printer->text(number_format($recDet["factd_cant"],0).$spacant.$desc.$spadesc." ".number_format(round(($recDet["factd_tot"]/$recDet["factd_cant"]),4),4)." ".number_format($recDet["factd_tot"],2) . "\n");
                $sumGrav+=$recDet["factd_tot"];
        }  
        if ($desc1!="") {
            $printer->text("       ".$desc1.""."". "\n");
        }
        $sumsub+=$recDet["factd_sub"];
        $sumdescv+=$recDet["factd_descuv"];
        $sumtot+=$recDet["factd_tot"];
    }
    $printer->text("------------------------------------------------" . "\n");
    $printer->text("Total Exento: ".number_format($sumExen,2)." / Total Gravado: ".number_format($sumGrav,2) . "\n");
    $printer->text("(E) EXENTO DE IVA Según Art. 7 numeral 15" . "\n");
    $printer->text("    Ley del IVA" . "\n");
    $printer->text("================================================" . "\n");

    $printer->text("      "."       TOTAL A PAGAR  Q.".number_format($sumtot,2) . "\n");
    $printer->text(" " . "\n");
    $printer->setJustification(Printer::JUSTIFY_CENTER);
    $printer->text("** SUJETO A PAGOS TRIMESTRALES **" . "\n");
    $printer->text("----- CERTIFICADOR -----" . "\n");
    $printer->text("      INFILE, S.A." . "\n");
    $printer->text("NIT CERTIFICADOR: 12521337" . "\n");
    $printer->setJustification(Printer::JUSTIFY_LEFT);
    $printer->text("Autorizacion FEL:" . "\n");
    $printer->text($rec["fact_documentguid"] . "\n");
    $printer->text("Fecha Certificacion: ".$rec["fact_guardado"] . "\n");
    $printer->text("** GRACIAS POR SU PREFERENCIA **" . "\n");
    $printer->text("CAJERO: ".TRIM($rec["vend_pnom"]) . "\n");

    $printer->setJustification(Printer::JUSTIFY_CENTER);
    if ($rec["caj_leyen1"]!='') {
       $printer->text($rec["caj_leyen1"] . "\n");
    }
    if ($rec["caj_leyen2"]!='') {
       $printer->text($rec["caj_leyen2"] . "\n");
    }
    if ($rec["caj_mailt"]!='') {
       $printer->text("Mail: ".$rec["caj_mailt"] . "\n");
    }

    if ($rec["fact_adomicilio"]=='S') {
        $printer->setJustification(Printer::JUSTIFY_LEFT);
        $printer->text(" " . "\n");
        $printer->text("Entregar en: ".$rec["fact_dirped"] . "\n");
    }    

    $printer->feed(3);

    $printer->cut();
    $printer->close();
}

$db->close();
?>