<?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
}
//echo "hola";
//error_reporting(E_ERROR  | E_PARSE);

$printer = $_POST['printer'];
$json = $_POST['json'];
$impconfig = $_POST['impconfig'];

//$json = '{"fecha":"2017-10-11 10:31:23","caja":"Caja1 - Principal","usuario":"usuario","montoentrada":"579.00","montosalida":"0.00","manejodetalle":"hola","manejoefectivo":"123.00","manejocheque":"456.00","tipo":"e"}';

$obj = json_decode($json);

$fecha = $obj->{'fecha'};
$caja = $obj->{'caja'};
$nombreempresa = $obj->{'nombreempresa'};
$emp_idfiscal = $obj->{'emp_idfiscal'};
$usuario = $obj->{'usuario'};
$tipo = $obj->{'tipo'};
$fecha = $obj->{'fecha'};
$montoentrada = $obj->{'montoentrada'};
$montosalida = $obj->{'montosalida'};
$detalle = $obj->{'manejodetalle'};
$manejoefectivo = $obj->{'manejoefectivo'};
$manejocheque = $obj->{'manejocheque'};

if ($impconfig == 1) {
    $pos = strpos($printer, ".");

    if ($pos !== false) {
        $handle = @fsockopen($printer, 9100);
    } else {
        $handle = @fopen($printer, "w");

    }

    @fwrite($handle, chr(27) . chr(64));
    @fwrite($handle, chr(27) . chr(33) . chr(0)); //normal
    @fwrite($handle, chr(27) . chr(97) . chr(1)); //->Centro
    @fwrite($handle, "DGI");
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, $nombreempresa);
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, chr(27) . chr(97) . chr(0)); //->Izquierda
    @fwrite($handle, "R.U.C.:   " . $emp_idfiscal);
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, $fecha);
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, chr(27) . chr(33) . chr(8)); //negrita
    @fwrite($handle, "DOCUMENTO NO FISCAL");
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea

    @fwrite($handle, "Informe General");
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, chr(27) . chr(33) . chr(0)); //normal

    if ($tipo == 'e') {
        @fwrite($handle, "COMPROBANTE DE ENTRADA DE EFECTIVO");
        @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    } else {
        @fwrite($handle, "COMPROBANTE DE SALIDA DE EFECTIVO");
        @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea

    }

    @fwrite($handle, "__________________________________________");
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, chr(27) . chr(33) . chr(0)); //normal
    @fwrite($handle, str_pad("Caja:", 10, " ", STR_PAD_RIGHT) . str_pad($caja, 20, " ", STR_PAD_RIGHT));
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, str_pad("Usuario:", 10, " ", STR_PAD_RIGHT) . str_pad($usuario, 20, " ", STR_PAD_RIGHT));
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, "==========================================");
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, str_pad("Efectivo:", 22, " ", STR_PAD_RIGHT) . str_pad($manejoefectivo, 20, " ", STR_PAD_LEFT));
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, str_pad("Cheque:", 22, " ", STR_PAD_RIGHT) . str_pad($manejocheque, 20, " ", STR_PAD_LEFT));
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, chr(27) . chr(33) . chr(8)); //negrita

    if ($tipo == 'e') {
        @fwrite($handle, str_pad("Monto:", 22, " ", STR_PAD_RIGHT) . str_pad($montoentrada, 20, " ", STR_PAD_LEFT));
    } else {
        @fwrite($handle, str_pad("Monto:", 22, " ", STR_PAD_RIGHT) . str_pad($montosalida, 20, " ", STR_PAD_LEFT));

    }

    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, chr(27) . chr(97) . chr(0)); //->Izquierda
    @fwrite($handle, "Detalle de la transacción:");
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, $detalle);
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, chr(27) . chr(97) . chr(1)); //->Centro
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, "------------------------------------------");
    @fwrite($handle, chr(27) . chr(100) . chr(1)); //salto de linea
    @fwrite($handle, "Firma Autorizada");
    @fwrite($handle, chr(10) . chr(10) . chr(10) . chr(10) . chr(10) . chr(29) . chr(86) . chr(49) . chr(12));

    @fclose($handle); // cierra el fichero PRN*/

} else {

    $cadena = "";

    $cadena = $cadena . "@DGI";
    $cadena = $cadena . ";";
    $cadena = $cadena . "@" . $nombreempresa;
    $cadena = $cadena . ";";
    $cadena = $cadena . ";";
    $cadena = $cadena . str_pad("R.U.C.:", 10, "!", STR_PAD_RIGHT) . str_pad($emp_idfiscal, 20, "!", STR_PAD_RIGHT);
    $cadena = $cadena . ";";
    $cadena = $cadena . str_pad("Fecha:", 10, "!", STR_PAD_RIGHT) . str_pad($fecha, 20, "!", STR_PAD_RIGHT);

    $cadena = $cadena . ";";
    $cadena = $cadena . "@DOCUMENTO NO FISCAL";
    $cadena = $cadena . ";";
    $cadena = $cadena . "@Informe General";
    $cadena = $cadena . ";";

    if ($tipo == 'e') {
        $cadena = $cadena . "@COMPROBANTE DE ENTRADA DE EFECTIVO";
        $cadena = $cadena . ";";
    } else {
        $cadena = $cadena . "@COMPROBANTE DE SALIDA DE EFECTIVO";
        $cadena = $cadena . ";";

    }

    $cadena = $cadena . "__________________________________________";
    $cadena = $cadena . ";";

    $cadena = $cadena . str_pad("Caja:", 10, "!", STR_PAD_RIGHT) . str_pad($caja, 20, "!", STR_PAD_RIGHT);
    $cadena = $cadena . ";";

    $cadena = $cadena . str_pad("Usuario:", 10, "!", STR_PAD_RIGHT) . str_pad($usuario, 20, "!", STR_PAD_RIGHT);
    $cadena = $cadena . ";";

    $cadena = $cadena . "==========================================";
    $cadena = $cadena . ";";

    $cadena = $cadena . str_pad("Efectivo:", 22, "!", STR_PAD_RIGHT) . str_pad($manejoefectivo, 20, "!", STR_PAD_LEFT);
    $cadena = $cadena . ";";

    $cadena = $cadena . str_pad("Cheque:", 22, "!", STR_PAD_RIGHT) . str_pad($manejocheque, 20, "!", STR_PAD_LEFT);
    $cadena = $cadena . ";";

    if ($tipo == 'e') {
        $cadena = $cadena . str_pad("Monto:", 22, "!", STR_PAD_RIGHT) . str_pad($montoentrada, 20, "!", STR_PAD_LEFT);
    } else {
        $cadena = $cadena . str_pad("Monto:", 22, "!", STR_PAD_RIGHT) . str_pad($montosalida, 20, "!", STR_PAD_LEFT);

    }

    $cadena = $cadena . ";";
    $cadena = $cadena . "Detalle de la transacción:";
    $cadena = $cadena . ";";
    $cadena = $cadena . $detalle;
    $cadena = $cadena . ";";
    $cadena = $cadena . ";";
    $cadena = $cadena . "------------------------------------------";
    $cadena = $cadena . ";";
    $cadena = $cadena . "Firma Autorizada";
    $cadena = $cadena . ";";

    //         echo "entro a cadena".$cadena;

    // $handle = fopen('/dev/ttyUSB0','w');

//abre cupon

    $arre = chr(2) . chr(6) . chr(0) . chr(28) . chr(83) . chr(48) . chr(49) . chr(208) . chr(0);

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

//usleep(600000);

//echo  'listafinal '.$send;

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

// var_dump( explode( ';', $caena1 ) );

//var_dump( explode( ';', $cadena ) );

//$cadena=  str_replace("!", " ", $cadena);

    $array = explode(';', $cadena);

    $longitud = count($array);
//$longitud =20;

    echo $longitud;

    $texto99 = '';

//Recorro todos los elementos
    $imprimel = 0;
    $completo = '';
    for ($i = 0; $i < $longitud; $i++) {
        //saco el valor de cada elemento
        //      echo  str_replace("!", " ", $array[$i]);

        $vacio = $array[$i];

        if ($vacio == '') {
            //echo 'vacioioioioioioioioioioioioio';

        } else {

            $imprimel = $imprimel + 1;

            $lalinea = str_replace("!", " ", $array[$i]);

            $lalinea = str_pad($lalinea, 48, " ", STR_PAD_RIGHT);

            $texto1 = $texto1 . $lalinea;

            //  echo  'ototototototot: ' .$imprimel;

            if ($imprimel == 1) {

                echo $texto1;
                echo "\n";

                $imprimel = 0;
                $termino = imprime($texto1);

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

//echo $termino;

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

//usleep(600000);
                $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);
//$data_string99=$json;

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

//print_r($caena1);
    //$json1->cierrefiscal = $caena1;
    //print_r($json1);
    //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;

};

?>
