<?php
    session_start();
    require '../vendor/autoload.php';
    use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
    use Mike42\Escpos\CapabilityProfile;
    use Mike42\Escpos\Printer;

    use Mike42\Escpos\EscposImage;
    #=================== Guardando los datos en BD ==================== #
    require ('../functions/ticket_nota.php');
    $id_nota = $_POST["id_nota"] ;
    
    $tipo_pago = $_POST["tipo_pago"];
    $_SESSION['cveNota'] = $id_nota;

    if (isset($_POST['pago_total_efectivo']) && isset($_POST['pago_total_tarjeta'])) {
        $pago_total_tarjeta = $_POST['pago_total_tarjeta'];
        $pago_total_efectivo = $_POST['pago_total_efectivo'];
    }else{
        $pago_total_tarjeta = 0;
        $pago_total_efectivo = 0;
    }
    $query = query("SELECT * FROM productos_nota WHERE id_nota_venta='$id_nota'");
    $query2= query("SELECT * FROM notas_venta WHERE ntv_no_personas > 0 AND id='$id_nota'");

    if($query->num_rows > 0 && $query2->num_rows >0){
        $nota_zona_venta_piso =query("SELECT * FROM notas_venta WHERE ntv_zona_ate = 'Venta en piso' AND id='$id_nota'");
        $no_mesa = query("SELECT * FROM notas_venta WHERE ntv_no_mesa > 0 and id='$id_nota'");
        if ($nota_zona_venta_piso->num_rows > 0 && $no_mesa->num_rows > 0) {
            $res = query("UPDATE notas_venta SET ntv_id_tipo_pago='$tipo_pago', ntv_tarjeta='$pago_total_tarjeta', ntv_efectivo='$pago_total_efectivo' WHERE id='$id_nota'");
            ///$resultado=mysqli_fetch_assoc($res);
            $result=1;
        }else{
            $nota_zona_venta_para_llevar=query("SELECT * FROM notas_venta WHERE ntv_zona_ate = 'Para llevar' AND id='$id_nota'");
            if ($nota_zona_venta_para_llevar->num_rows > 0) {
                $res = query("UPDATE notas_venta SET ntv_id_tipo_pago='$tipo_pago', ntv_tarjeta='$pago_total_tarjeta', ntv_efectivo='$pago_total_efectivo' WHERE id='$id_nota'");
                ///$resultado=mysqli_fetch_assoc($res);
                $result=1;
            }else{
                $result = 0;
            }
        }
        
        #========================================================= #
        #=================== Recibiendo datos ==================== #
        
        $nota = get_nota($id_nota);
        $campo = get_productos_nota($id_nota);
        $no_nota = $nota[0]['CLAVE'];
        $mesero = $nota[1]['NOMBRE'];
        $tipo_venta = $nota[2]['ZONA'];
        $p=$nota[4]['PERSONAS'];  //Personas 
        $m=$nota[3]['MESA']; // Numero de mesa
        $subtotal=$nota[5]["SUBTOTAL"];
        $descuento=$nota[6]["DESCUENTO"];
        $total=$nota[7]["TOTAL"];
        $descuento_total = ($subtotal*$descuento)/100;

        date_default_timezone_set('America/Mexico_City');
        $hoy=new DateTime();

        #========================================================= #

        #=================== Datos de la impresora =============== #
        $name = $_POST['opcionImprComanda'];
        $profile = CapabilityProfile::load("simple");
        $connector = new WindowsPrintConnector($name);
        $printer = new Printer($connector, $profile);

        #========================================================= #

        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->setEmphasis(true);
        $printer->setTextSize(2, 2);
        $printer->text("Mi Restaurant \n");

        $printer->text("\n");
        /*
        try {
            $logo = EscposImage::load("cabanita.png", false);
            $printer->bitImage($logo);
            $printer->text("Regular Tux (bit image).\n");
            $printer->feed();
            $printer->bitImage($logo, Printer::IMG_DOUBLE_WIDTH);
            $printer->text("Wide \n");
            $printer->feed();
            $printer->bitImage($logo, Printer::IMG_DOUBLE_HEIGHT);
            $printer->text("Tall \n");
            $printer->feed();
            $printer->bitImage($logo, Printer::IMG_DOUBLE_WIDTH | Printer::IMG_DOUBLE_HEIGHT);
            $printer->text("Large \n");
        } catch (Exception $e) {
            
            $printer->text($e->getMessage() . "\n");
        }
            
        try {
            $logo = EscposImage::load("cabanita.png", false);
            
            $printer -> graphics($logo);
            $printer -> text("Regular.\n");
            $printer -> feed();
            
            $printer -> graphics($logo, Printer::IMG_DOUBLE_WIDTH);
            $printer -> text("Wide .\n");
            $printer -> feed();
            
            $printer -> graphics($logo, Printer::IMG_DOUBLE_HEIGHT);
            $printer -> text("Tall.\n");
            $printer -> feed();
            
            $printer -> graphics($logo, Printer::IMG_DOUBLE_WIDTH | Printer::IMG_DOUBLE_HEIGHT);
            $printer -> text("Large.\n");
            
            
        } catch (Exception $e) {
            $printer -> text($e -> getMessage() . "\n");
        }
        try {
            $printer->setJustification(Printer::JUSTIFY_CENTER);

            $logo = EscposImage::load("cabanita.png", false);
            $printer->bitImage($logo);
        } catch (Exception $e) {
            $printer -> text($e -> getMessage() . "\n");
        }*/

        $printer->setTextSize(1, 1);
        $printer -> selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
        $printer->text("NOTA DE VENTA \n");
        $printer -> selectPrintMode();
        $printer->setJustification(Printer::JUSTIFY_CENTER);
       
        $printer->text("Martha Angélica Samperio Fosado". "\n");
        $printer->text("RFC: SAFM780520L77". "\n");

        $printer->text("Carretera Federal Pahuca-Tulancingo". "\n");
        $printer->text("Kilometro 19.5". "\n");
        $printer->text("Teléfono: 7751365015". "\n");
        $printer->text("Sitio Web: www.micabanita.mx". "\n");
        $printer->text("------------------------------------------". "\n");

        #La fecha también
        $printer->text("Fecha:".date("Y-m-d H:i:s") . "\n");
        $printer->text("Tipo de venta:" . $tipo_venta . "\n");
        $printer->setTextSize(2, 1);
        $printer->text("M:" . $m . "\n");
        $printer->setTextSize(1, 1);
        $printer->text("Mesero: " . $mesero . "\n");
        $printer->text("No. Nota: " . $no_nota . "\n");
        $printer->text("------------------------------------------". "\n");
        $printer->text("Cant       Desc        Precio     Total \n");
        $printer->text("------------------------------------------". "\n");

        foreach($campo as $cam) {
            $pro_total = $cam['PRECIO'] *$cam['CANTIDAD'];
            $printer->setJustification(Printer::JUSTIFY_CENTER);

            $printer->setEmphasis(false);
            $printer->setTextSize(1, 1);
            $printer->text($cam['PRO_NOMBRE']."\n"); 

            $printer->setJustification(Printer::JUSTIFY_LEFT);
            $printer->text("  ".$cam['CANTIDAD']  . "          " . " 0 " . "         " .  "$ ".$cam['PRECIO']  . "     " . "$ ".$pro_total. "\n");
           
        }
        $printer->text("\n");
        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->setTextSize(1, 1);
        $printer->text("Subtotal:" . "$ " . $subtotal . "\n");
        $printer->text("Desc p/Partida:" . $descuento . " %" . "\n");
        $printer->text("Desc Gral:" . "$ " . $descuento_total . "\n");
        $printer->text("----------------------------------------". "\n");

        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->setEmphasis(true);
        $printer->setTextSize(2, 1);

        $printer->text("TOTAL:" . " $ " . $total . "\n");
        $printer->setEmphasis(false);


        $printer->setTextSize(1, 1);
        $printer->text("\n");
        $printer->text("¡GRACIAS POR TU VISITA!\n");

         // Cortar el papel
         $printer->cut();

         // Enviar un pulso de apertura del cajón de efectivo
         $printer->pulse();
     
         // Esperar un segundo para que la impresora procese la orden
         sleep(1);

        // Cerrar la impresora
        $printer->close();
        
        //
        $res = query("UPDATE notas_venta SET ntv_estatus='pagado' WHERE id='$id_nota'");
    }else{
        $result = 0;
    }

?>