<?php

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400'); // cache for 1 day
}

error_reporting(E_ERROR | E_PARSE);

//$printer = $_POST['printer'];
//$printer = "\\127.0.0.1\USB002";
$json = $_POST['json'];

include 'funciones.php';

//$totalg = 0.00;

//$json = '{"mesa":4,"puesto":"1","fechai":"2018/12/11  14:48:11","caja":"CA3-SUCURSAL 1","amesa":"CAJERO","cliente":"CLIENTE CONTADO","pedido":"240000129","usuario":"usuario","jsonproductos":[{"po_id_prod":"101","po_cant":"1.00000","po_descripcion":"ARTICULO DE PRUEBA","po_precio":"1.2500","po_itbms":"0.000","porcdesc":"0.00","porcdesc_general":"0.0000"},{"po_id_prod":"30","po_cant":"1.00000","po_descripcion":"prueba 7 ","po_precio":"1.6000","po_itbms":"7.000","porcdesc":"0.00","porcdesc_general":"0.0000"}],"jsonbases":[{"po_itbms":"7.000","imp":"0.112000000000000000000000000000","porcdesc_general":"0.0000"}],"jsonoperacion":[{"op_fecha":"2018-12-11 14:00:04","op_subtotal":"2.8500","op_total":"2.9600","op_desc":"0.0000","operacion":"240000129"}]}';

$obj = json_decode($json);
$productos = $obj->{'jsonproductos'};
$operacion = $obj->{'jsonoperacion'};
$bases = $obj->{'jsonbases'};
$fechaa = "";
$fechai = $obj->{'fechai'};

foreach ($operacion as $valor) {
    $op_subtotal = $valor->{'op_subtotal'};
    $op_total = $valor->{'op_total'};
    $op_desc = $valor->{'op_desc'};
    $neto = number_format($op_subtotal - $op_desc, 2, '.', ',');
    $fechaa = $valor->{'op_fecha'};
    $operacion = $valor->{'operacion'};
    $imp = $valor->{'op_itbms'};
}

$cadena = "";
$cadena = $cadena . "@PRE-CUENTA";
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . "CUENTA:  MESA: " . $obj->{'mesa'} . " PUESTO: " . $obj->{'puesto'} . "";
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . ";"; //salto de linea

$cadena = $cadena . str_pad("Num. Refer.:", 20, " ", STR_PAD_RIGHT) . str_pad($operacion, 22, " ", STR_PAD_RIGHT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . str_pad("Fecha Apertura:", 20, " ", STR_PAD_RIGHT) . str_pad($fechaa, 22, " ", STR_PAD_RIGHT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . str_pad("Fecha IMpresion:", 20, " ", STR_PAD_RIGHT) . str_pad($fechai, 22, " ", STR_PAD_RIGHT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . str_pad("Nombre Caja:", 20, " ", STR_PAD_RIGHT) . str_pad($obj->{'caja'}, 22, " ", STR_PAD_RIGHT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . str_pad("Abrio Mesa:", 20, " ", STR_PAD_RIGHT) . str_pad($obj->{'amesa'}, 22, " ", STR_PAD_RIGHT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . str_pad("Nombre Cliente:", 20, " ", STR_PAD_RIGHT) . str_pad($obj->{'cliente'}, 22, " ", STR_PAD_RIGHT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . str_pad("Numero Pedido:", 20, " ", STR_PAD_RIGHT) . str_pad($operacion, 22, " ", STR_PAD_RIGHT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . str_pad("Usuario:", 20, " ", STR_PAD_RIGHT) . str_pad($obj->{'usuario'}, 22, " ", STR_PAD_RIGHT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . str_pad("Codigo:", 20, " ", STR_PAD_RIGHT) . str_pad("Descripcion", 22, " ", STR_PAD_RIGHT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . str_pad("Precio Bruto:", 20, " ", STR_PAD_RIGHT) . str_pad("%Desc.     Precio Net", 22, " ", STR_PAD_LEFT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . "------------------------------------------";
$porcdesc_general = 0;
foreach ($productos as $valor) {

    $po_id_prod = $valor->{'po_id_prod'};
    $po_itbms = $valor->{'po_itbms'};
    $po_cant = $valor->{'po_cant'};
    $po_precio = $valor->{'po_precio'};
    $porcdesc = $valor->{'porcdesc'};
    $porcdesc_general = $valor->{'porcdesc_general'};
    $tdescu = $tdescu + ($po_precio * $po_cant) * $porcdesc / 100;
    $descu = number_format(($po_precio * $po_cant) * $porcdesc / 100, 2, '.', ',');

    $total_linea = ($po_precio * $po_cant) - $descu;
    $desclinglobal = ($total_linea * $porcdesc_general) / 100;
    $descuento_g = $descuento_g + $desclinglobal;

    $total = number_format(($po_precio * $po_cant) - $descu, 2, '.', ',');
    $po_descripcion = $valor->{'po_descripcion'};

    $cadena = $cadena . ";"; //salto de linea
    $cadena = $cadena . str_pad($po_id_prod, 10, " ", STR_PAD_RIGHT) . str_pad("(" . number_format($po_itbms, 2, '.', ',') . "%) ", 8, " ", STR_PAD_LEFT) . str_pad($po_descripcion, 8, " ", STR_PAD_RIGHT);
    $cadena = $cadena . ";"; //salto de linea
    $cadena = $cadena . str_pad(number_format($po_cant, 2, '.', ',') . " x " . number_format($po_precio, 2, '.', ','), 20, " ", STR_PAD_RIGHT) . str_pad("-" . $descu, 8, " ", STR_PAD_LEFT) . str_pad($total, 14, " ", STR_PAD_LEFT);

}

$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . "------------------------------------------";
$cadena = $cadena . ";"; //salto de linea

$totalg = $neto;

$cadena = $cadena . str_pad("Sub.Bruto:", 14, " ", STR_PAD_LEFT) . str_pad("Desc.Prod.:", 14, " ", STR_PAD_LEFT) . str_pad("Sub.Neto", 14, " ", STR_PAD_LEFT);
$cadena = $cadena . ";"; //salto de linea

//$descfact =$op_desc - $tdescu;
$cadena = $cadena . str_pad(number_format($op_subtotal, 2, '.', ','), " 14", " ", STR_PAD_LEFT) . str_pad(number_format("-" . $tdescu, 2, '.', ','), 14, " ", STR_PAD_LEFT) . str_pad($neto, 14, " ", STR_PAD_LEFT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . str_pad($porcdesc_general . "% ", " 15", " ", STR_PAD_LEFT) . str_pad("Desc.Fact.:", 14, " ", STR_PAD_LEFT) . str_pad(number_format("-" . $descuento_g, 2, '.', ','), 13, " ", STR_PAD_LEFT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . "------------------------------------------";
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . str_pad("", 14, " ", STR_PAD_LEFT) . str_pad("Sub Total:", 14, " ", STR_PAD_LEFT) . str_pad($neto, 14, " ", STR_PAD_LEFT);

//foreach ($bases as $valor) {

//    $imp = $valor->{'imp'};
//    $po_itbms = $valor->{'po_itbms'};
$cadena = $cadena . ";"; //salto de linea
//$cadena = $cadena.str_pad("ITBMS:  ".number_format($po_itbms, 2, '.', ',')."%:",  30, " ", STR_PAD_LEFT).str_pad(number_format($imp, 2, '.', ','),  12, " ", STR_PAD_LEFT);
$cadena = $cadena . str_pad("", 14, " ", STR_PAD_LEFT) . str_pad("ITBMS:", 14, " ", STR_PAD_LEFT) . str_pad(number_format($imp, 2, '.', ','), 14, " ", STR_PAD_LEFT);
//$totalg = $totalg + $imp;
//}

$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . "               ---------------------------";
$cadena = $cadena . ";"; //salto de linea
//$cadena = $cadena.str_pad("Total:",  30, " ", STR_PAD_LEFT).str_pad(number_format($op_total, 2, '.', ','),  12, " ", STR_PAD_LEFT);
$cadena = $cadena . str_pad("", 14, " ", STR_PAD_LEFT) . str_pad("Total:", 14, " ", STR_PAD_LEFT) . str_pad(number_format($op_total, 2, '.', ','), 14, " ", STR_PAD_LEFT);
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . "               ---------------------------";
$cadena = $cadena . ";"; //salto de linea
$cadena = $cadena . ";"; //salto de linea
//$cadena = $cadena.";";//salto de linea
//$cadena = $cadena.str_pad("0% Servicio Sugerido:",  22, " ", STR_PAD_RIGHT).str_pad("0.00",  20, " ", STR_PAD_LEFT);
//$cadena = $cadena.";";//salto de linea
//$cadena = $cadena.str_pad("Total:",  22, " ", STR_PAD_RIGHT).str_pad(number_format($totalg, 2, '.', ','),  20, " ", STR_PAD_LEFT);
//$cadena = $cadena.";";//salto de linea
//$cadena = $cadena.";";//salto de linea

//$cadena = $cadena."@Gracias por su visita";
$cadena = $cadena . ";"; //salto de linea

$arre = chr(2) . chr(6) . chr(0) . chr(28) . chr(83) . chr(48) . chr(49) . chr(208) . chr(0);
$arre = chr(2) . chr(6) . chr(0) . chr(28) . chr(20) . chr(112) . chr(10) . chr(170) . chr(0);
echo "\n";
echo "\n";
echo 'hexadec: ' . strToHex($arre);

$conv = strToHex($arre);
echo "\n";
echo "\n";

echo 'mandando' . hexToStr($conv);

$caena1 = nl2br($cadena);
$array = explode(';', $cadena);
$longitud = count($array);

echo $longitud;

$texto99 = '';
$imprimel = 0;
$completo = '';
for ($i = 0; $i < $longitud; $i++) {

    $vacio = $array[$i];

    if ($vacio == '') {

    } else {

        $imprimel = $imprimel + 1;
        $lalinea = str_replace("!", " ", $array[$i]);
        $lalinea = str_pad($lalinea, 48, " ", STR_PAD_RIGHT);
        $texto1 = $texto1 . $lalinea;

        if ($imprimel == 5) {

            echo $texto1;
            echo "\n";
            $imprimel = 0;
            $termino = imprime($texto1);

            $completo = $completo . ';' . strToHex($termino);

            $texto1 = '';

        }
    }
}

$arre = chr(2) . chr(4) . chr(0) . chr(28) . chr(21) . chr(49) . chr(0);

echo 'hexadec: completo ' . $completo . ';' . strToHex($arre);

$url1 = "http://localhost:8080/webservice.carlos/rest/todos/fiscalcierre";

$data_string99 = $completo . ';' . strToHex($arre);

$url1 = "http://localhost:8080/webservice.carlos/rest/todos/fiscalcierre";

$ch = curl_init($url1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string99);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string99))
);
$result = curl_exec($ch);
curl_close($ch);

$json1->cierrefiscal = $caena1;

if ($_SESSION['codigo'] == "99") {

    $json1->datos = "false";

} else {
    $json1->datos = "true";
}

print_r(json_encode($json1));

function strToHex($string)
{
    $hex = '';
    for ($i = 0; $i < strlen($string); $i++) {
        $ord = ord($string[$i]);
        $hexCode = dechex($ord);
        $hex .= substr('0' . $hexCode, -2);
    }
    return strToUpper($hex);
}
function hexToStr($hex)
{
    $string = '';
    for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
        $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
    }
    return $string;
}
function letratohexa($palabra)
{
    $matriz1 = str_split($palabra);

    $stringlisto = '';
    $suma = 0;
    foreach ($matriz1 as $key => $num) {
//    echo ' letra:  '.  $num.' hex '.strToHex($num).' Dec'. hexdec(strToHex($num));

        $suma = $suma + hexdec(strToHex($num));

//      echo '  Sumando:'.($suma+58);

        $_SESSION['suma'] = dechex($suma + 58);

        echo "\n";

        $stringlisto = $stringlisto . ' ' . hexdec(strToHex($num));
    }

    echo "\n";
    echo "\n";

    return $stringlisto;
}
function imprime($texto1)
{

    $arre0 = chr(2);

    $cmd = chr(28);
    $fijo1 = chr(20);
    $fijo2 = chr(10);

    $texto = str_replace("<br />", "", $texto1);

    $texto = str_replace("!", " ", $texto);

    $texto = str_replace("enter", "
", $texto);
    $texto = substr($texto, 0, 240);

//echo 'sql' .$texto;
    $send = letratohexa($texto);

    $textofinal = $fijo1 . $texto . $fijo2;

    $tamini = (strlen($textofinal) + 3);

    $tam = strlen($_SESSION['suma']);

    echo 'tamaño' . $tam;
    echo "\n";

    if ($tam < 4) {
        $sumi = '0' . $_SESSION['suma'];

        echo 'menos de 4';
        echo "\n";

    } else {
        echo 'mas de 4';
        echo "\n";

        $sumi = $_SESSION['suma'];}
    ;

    echo substr($sumi, 0, 2);
    echo "\n";
    echo substr($sumi, 2, 2);

    $min = hexdec(substr($sumi, 0, 2));
    $max = hexdec(substr($sumi, 2, 2));
    echo "\n";
    echo 'Maximo' . $max;
    echo "\n";
    echo 'min' . $min;

    $NBL = chr($tamini);

    $NBS = chr(0);

    $CSL = chr($max);
    $CSH = chr($min);

    $arre = $arre0 . $NBL . $NBS . $cmd . $textofinal . $CSL . $CSH;

//@fwrite($handle,$arre );

//usleep(600000);

    return $arre;

};

?>