<?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');
//include_once('../ws/COFIDI/wsExec.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=$_SESSION["empNit"];
$usuNom = utf8_decode($_SESSION['usuNom']);
$pCaja=utf8_decode($_SESSION["pCaja"]);
$establecimiento=$_SESSION['establecimiento'];

$numdoc=$_POST["numdoc"];
$seriedoc=$_POST["selTipoCod"];
$TdocNom=$_POST["TdocNom"];
$totLetras=$_POST["totLetras"];
$vuelto=$_POST["vuelto"];
$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,
    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 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'";

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

$lineWidth=8;
$lineHeight=0.4;


$db = new dbExec();

$func = new functions();

// Definir y activar impresoar
$nombre_impresora = "POS-80C"; 
//$nombre_impresora = "Epson LX-300";
$connector = new WindowsPrintConnector($nombre_impresora);
$printer = new Printer($connector);

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

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

$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->text($rec["caj_dirt"] . "\n");
$printer->text("TELEFONO: ".$rec["caj_telt"] . "\n");
$printer->text("NIT: ".$empNit . "\n");
$printer->text("ENVIO DE MERCADERIA" . "\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("Caja: ".$establecimiento." 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;
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,18);
    $ldesc=strlen(TRIM($recDet["factd_desc"]));
    if ($ldesc>18) {
        $difdesc=0;
        $desc1=substr($recDet["factd_desc"],18,36);
    } else {
        $difdesc=18-$ldesc;
        $desc1="";
    }  
    $spadesc="";
    if ($difdesc<18 && $difdesc>0) {
        for ($q=1; $q < $difdesc+1; $q++) { 
            $spadesc=$spadesc." ";
        }
    }
    $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");
    if ($desc1!="") {
        $printer->text("       ".$desc1.""."". "\n");
    }
    $sumsub+=$recDet["factd_sub"];
    $sumdescv+=$recDet["factd_descuv"];
    $sumtot+=$recDet["factd_tot"];
}
//$printer->text("----------------------------------------" . "\n");
//$printer->text("      "."      (-) Descuento   Q.".number_format($sumdescv,2) . "\n");
$printer->text("========================================" . "\n");
$printer->text("      "."       TOTAL A PAGAR  Q.".number_format($sumtot,2) . "\n");
$printer->text(" " . "\n");
$printer->text("      "."       CAMBIO         Q.".number_format($vuelto,2) . "\n");
$printer->text(" " . "\n");
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->text("**** DOCUMENTO INTERNO  ****" . "\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 COMPRA **" . "\n");
$printer->text("LE ATENDIO: ".TRIM($rec["vend_nom"]) . "\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("-----------------------------------------------" . "\n");
    $printer->text(" " . "\n");
    $printer->text("Nombre: ".utf8_encode($rec["fact_nomped"]) . "\n");
    $printer->text("Entregar en: ".utf8_encode($rec["fact_dirped"]) . "\n");
    $printer->text("Celular: ".TRIM($rec["fact_cel"])." Tel: ".TRIM($rec["fact_tel"]) . "\n");
    $printer->text(utf8_encode($rec["fact_obsped"]) . "\n");
}    

$printer->feed(3);

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

$db->close();

$resp["respuesta"] = "Se imprimio el ticket";
echo json_encode($resp);

?>