<?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'];
$json = $_POST['json'];
$impconfig = $_POST['impconfig'];

//$json = '{"serie":"","fecha":"2017-07-27 09:13:00","caja":"","control":"","usuario":"","inicioturno":"27/7/2017  9:5:26","finturno":"27/7/2017  9:12:23","numerofactini":293,"numerofactfin":293,"totalfact":1,"totaldev":1,"totalfactaptos":0,"facturas":"117.50","notacred":0,"ventaneta":117.5,"impuestos":"4.90","ventascontado":"122.40","ventascredito":0,"descuentos":"-7.50","aperturacaja":500,"montoentrada":0,"montosalida":0,"diferencia":0,"abonoctes":0,"abonoaptos":0,"abonocert":0,"manejoservicio":0,"totalabono":0,"dinerotturno":622.4,"dinerogaveta":600,"depositorealizar":122.4,"formapago":[{"ind":"EF","ventas":-1.3999999999999986,"pagos":"0.00","es":"0.00","total":-1.3999999999999986},{"ind":"CH","ventas":40,"pagos":"0.00","es":"0.00","total":40},{"ind":"TD","ventas":60,"pagos":"0.00","es":"0.00","total":60},{"ind":"EC","ventas":167.6,"pagos":"0.00","es":"0.00","total":167.6},{"ind":"OT","ventas":0,"pagos":"0.00","es":"0.00","total":0}],"bases":[{"ind":"E","base":47.5,"imp":0,"total":47.5},{"ind":"7.0","base":70,"imp":4.9,"total":74.9},{"ind":"10.0","base":0,"imp":0,"total":0},{"ind":"15.0","base":0,"imp":0,"total":0}],"formaventas":[{"tipo":"Debito","forma":"Manual","monto":60},{"tipo":"Credito","forma":"Manual","monto":167.6},{"tipo":"Cheque","forma":"Manual","monto":40}]}';

$obj = json_decode($json);

$fecha = $obj->{'fecha'};
$caja = $obj->{'caja'};
$nombreempresa = $obj->{'nombreempresa'};
$emp_idfiscal = $obj->{'emp_idfiscal'};
$usuario = $obj->{'usuario'};
$monto = $obj->{'monto'};
$detalle = $obj->{'detalle'};

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, "INICIO DE TURNO");
    @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($monto, 20, " ", STR_PAD_LEFT));
    @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(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(27) . chr(100) . chr(1)); //salto de linea

    @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 . ";";

    if ($tipo == 'e') {
        $cadena = $cadena . "@COMPROBANTE DE SALIDA DE EFECTIVO";
        $cadena = $cadena . ";";
    } else {
        $cadena = $cadena . "@COMPROBANTE DE ENTRADA 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($monto, 20, "!", STR_PAD_LEFT);
    $cadena = $cadena . ";";
    $cadena = $cadena . "Detalle de la transaccion:";
    $cadena = $cadena . ";";
    $cadena = $cadena . $detalle;
    $cadena = $cadena . ";";
    $cadena = $cadena . ";";
    $cadena = $cadena . "------------------------------------------";
    $cadena = $cadena . ";";
    $cadena = $cadena . "Firma Autorizada";
    $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;

};

?>