<?php

namespace App\Http\Controllers;

use Mike42\Escpos\Printer; 
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\RawbtPrintConnector;
use Mike42\Escpos\CapabilityProfile;

use Illuminate\Http\Request;
use DataTables;
use Auth;
use DB;
use Session;

use App\User;
use App\City;
use App\User_logs;
use App\Setting;
use App\Customer;
use App\Area;
use App\MSOut;
use App\DTOut;
use App\Product;
use App\Stock;
use App\Gudang;


class KeluarController extends Controller
{
    
    public function index(){
        
        /*
        $prd = DB::table('ms_stock as A')
                    ->select('A.id','A.product_id','B.nama_brg')
                    ->leftjoin('ms_product as B', function($join){
                        $join->on('A.product_id','=','B.id');
                    })
                    ->where('A.gudang_id')
        */
        
        $gdg = Gudang::all();
        
        return view('keluar.index', compact('gdg'));
    }

    public function fakturcount(){
        $ftr = MSOut::with('get_customer', 'get_sales')
                        ->where('is_batal',0)
                        ->where('is_posted',0)
                        ->orderBy('id', 'DESC')
                        ->get();
        
        $data=[];
        foreach($ftr as $ff){ 
            $row=[];
            $row[] = $ff->id;
            $row[] = '<li>'.$ff->sale_no.' - '.$ff->get_customer->cus_name.'</li>';
            $data[]=$row;
        }
        
        return response()->json(["data"=>$data]);
    }
    
    
    public function jumlahFaktur(){
        $ftr = MSSale::where('is_batal',0)
                        ->where('is_posted',0)
                        ->count();
                        
        echo json_encode(["jumlah"=>$ftr]);
    }
    
    public function datakeluar(){
    
        $tgl = date('Y-m-d');
        
        $do = MSOut::with('get_gudang')
                        ->where('is_posted',0)
                        ->where('is_batal',0)
                        ->get();
                        
        $data=[];
        foreach($do as $dt){
            
            $row=[];
            $row[] = $dt->out_no;
            $row[] = tanggal_indonesia($dt->out_tgl, false);
            $row[] = $dt->get_gudang->nama;
            $row[] = $dt->tujuan;
            $row[] = $dt->deskripsi;

            if($dt->is_posted==1){
            $row[]=
	              '<div class="btn-group">
                    <a  class="btn btn-flat btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    </a>
                        <ul class="dropdown-menu dropdown-menu-right" style="border:2px black solid;" id="dropMenu">
                            <li><a onclick="displayDetail('.$dt->id.')"><i class="fa fa-eye"></i>Display Detail</a></li>
                        </ul>
                    </div>';
                
            }else{
            $row[]=
	              '<div class="btn-group">
                    <a  class="btn btn-flat btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    </a>
                        <ul class="dropdown-menu dropdown-menu-right" style="border:2px black solid;" id="dropMenu">
                            <li><a onclick="addDetail('.$dt->id.')"><i class="fa fa-plus"></i>Input Detail</a></li>
                            <li><a onclick="editHeader('.$dt->id.')"><i class="fa fa-pencil"></i>Edit Header </a></li>
                            <li><a onclick="batal('.$dt->id.')"><i class="fa fa-trash"></i>Batal Penjualan</a></li>
                        </ul>
                    </div>';
            }
            
            $data[]=$row;
        }
        
        return response()->json(["data"=>$data]);
        
    }

    public function store(Request $request){
        
        $gdg = Gudang::find($request['asal']);
        $nodo = $this->cekNoDO($gdg->kode);
        
        $dt = new MSOut;
        $dt->out_tgl    = date('Y-m-d');
        $dt->out_no     = $nodo;
        $dt->tujuan     = $request['tuju'];
        $dt->gudang_id  = $request['asal'];
        $dt->deskripsi  = $request['ket'];
        $dt->user_id    = Auth::user()->id;

        $dt->save();
        
	// insert logs
		$usrnm	= Auth::user()->username;
		
		$userlog = New User_logs;
		$userlog->title		= 'Keluar Barang(DO)';
		$userlog->content	= 'DO '.$nodo.' berhasil dibuat oleh '.$usrnm;
		$userlog->user_id	= Auth::user()->id;
		$userlog->save();

		echo json_encode(array('msg'=>'success'));        
        
    }

    public static function cekNoDO($gdg){
    	/* cek no terakhir */

		$noftr	= '';
		$tahun	= date('y');
		$bulan  = date('m');
		$nomor	= $gdg.'/'.$tahun.$bulan."/";		/* FTR/2205/0001*/
			
		$ada_no	= DB::table('ms_out')
						->select(DB::raw('SUBSTR(MAX(out_no),10,4) as last_no'))
						->where('out_no', 'LIKE', "$nomor%" )
						->first();
			
		if (!empty($ada_no))
		{
			$no	= $ada_no->last_no + 1;
				
			$nomorbaru 	= sprintf("%04s", $no);		//format: IN/202101/0001
			$noftr = $nomor.$nomorbaru;
			
		} else {
			$nomorbaru = "0001";
			$noftr = $nomor.$nomorbaru;
		}
		
		return $noftr;
    }		

    public function edit($id){
        $dt = MSOut::find($id);
        $gdg= Gudang::find($dt->gudang_id);

        echo json_encode(array_merge(json_decode($gdg, true), json_decode($dt, true)));

    }

    public function batal($id){
        $dt = MSSale::find($id);
        
        $ada = DTSale::where('sale_id',$id)
                        ->where('qty','>',0)
                        ->count();
                        
        if($ada>0){ return json_encode(["msg"=>"error-1"]); }
        
        $dt->is_batal = 1;
        $dt->is_posted= 1;
        $dt->update();

	// insert logs
		$usrnm	= Auth::user()->username;
		
		$userlog = New User_logs;
		$userlog->title		= 'Batal Faktur Penjualan';
		$userlog->content	= 'Faktur '.$dt->sale_no.' berhasil dibatalkan oleh '.$usrnm;
		$userlog->user_id	= Auth::user()->id;
		$userlog->save();

		echo json_encode(array('msg'=>'success'));            
    }

    public function show($id){
        $dt = MSOut::find($id);
        echo json_encode($dt);
    }
    
    public function update(Request $request, $id){

        $dt = MSOut::find($id);
        $dt->tujuan     = $request['tuju'];
        $dt->deskripsi  = $request['ket'];
        $dt->user_id    = Auth::user()->id;
        
        $dt->update();
        

	// insert logs
		$usrnm	= Auth::user()->username;
		
		$userlog = New User_logs;
		$userlog->title		= 'Edit Barang Keluar';
		$userlog->content	= 'DO '.$dt->out_no.' berhasil diedit oleh '.$usrnm;
		$userlog->user_id	= Auth::user()->id;
		$userlog->save();

		echo json_encode(array('msg'=>'success'));        
        
    }
    

    public function dataDetail($id){
        
        $mdo = MSOut::find($id);
        $do = DTOut::where('out_id', $id)
                        ->get();
                        
        $data=[];
    
        foreach($do as $dt){
            
            $row=[];

            $row[]=$dt->product_name;
            $row[]=$dt->satuan.'/'.$dt->isi;
            $row[]='<div style="text-align:right">'.format_uang($dt->qty).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            $row[]=$dt->deskripsi;

            if($mdo->is_posted==1){
                $row[]="";
            }else{
                $row[]='<a onclick="editDetail('.$dt->id.')" class="btn btn-flat btn-xs"><i class="fa fa-pencil"></i></a>';
            }
            
            $data[]=$row;
        }
        

        return response()->json(["data"=>$data]);
    }
    
    public function listProduct($id){
        
        $ms = MSOut::find($id);
        
        $prd = DB::table('ms_stock as A')
                    ->select('A.id', 'A.product_id', 'A.stock_akhir', 'B.nama_brg', 'B.satuan', 'B.isi')
                    ->leftjoin('ms_product as B', function($join){
                        $join->on('A.product_id','=','B.id');            
                    })
                    ->where('A.gudang_id', $ms->gudang_id)
                    ->orderBy('B.nama_brg')
                    ->get();


		$data = [];
		
		foreach($prd as $list){
			$row = [];
			$row[] = $list->nama_brg;
			$row[] = $list->satuan.'/'.$list->isi ;
            $row[] = '<div style="text-align:right">'.format_uang($list->stock_akhir).'</div>' ;
			
  		    $row[] = '<div class="btn-btn">
						<a onclick="selectProduk('.$list->id.')" class="btn btn-primary btn-sm"><i class="fa fa-check"></i></a>
					</div>';

			$data[] = $row;
        }

        return response()->json(["data"=>$data]);        
    }
    	
    
    public function addDetail(Request $request){
        
        $iddo   = $request['id_do2'];       /* pada form add_detail */
        $idstk  = $request['prd2'];         /* id stock */
        $qty    = $request['qty'];
        $ket    = $request['ket2'];

        $mdo = MSOut::find($iddo);
        $stk = Stock::find($idstk);
        $prd = Product::find($stk->product_id);

        try{  
            $dt = new DTOut;
            
            $dt->out_id         = $iddo;
            $dt->product_id     = $prd->id;
            $dt->product_name   = $prd->nama_brg;
            $dt->satuan         = $prd->satuan;
            $dt->isi            = $prd->isi;
            $dt->qty            = $qty;
            $dt->deskripsi      = $ket;
            $dt->save();
            
    	// insert logs
    		$usrnm	= Auth::user()->username;
    		
    		$userlog = New User_logs;
    		$userlog->title		= 'Input Detail DO '.$mdo->out_no;
    		$userlog->content	= $prd->nama_brg.' QTY '.$qty.' oleh '.$usrnm;
    		$userlog->user_id	= Auth::user()->id;
    		$userlog->save();            
            
            echo json_encode(['msg'=>'success']);
        }
        catch (Exeption $e){
            return response (['status' => false,'errors' => $e->getMessage()]);
        }            
    }
    
    public function editDetail($id){
        
        $dt = DTOut::find($id);
        echo json_encode($dt);
        
    }
    
    public function simpanEdit(Request $request, $id){
        
        $dt  = DTOut::find($id);
        $mdt = MSOut::find($dt->out_id);

        $dt->qty            = $request['qty'];
        $dt->deskripsi      = $request['ket2'];
        $dt->update();

    	// insert logs
    		$usrnm	= Auth::user()->username;
    		
    		$userlog = New User_logs;
    		$userlog->title		= 'Edit Detail DO '.$mdt->out_no;
    		$userlog->content	= $dt->product_name.'  QTY ->'.$request['qty'].' oleh '.$usrnm;
    		$userlog->user_id	= Auth::user()->id;
    		$userlog->save();            

        echo json_encode(['msg'=>'success']);
        
    }
    
    public function printFaktur($id){
        
        $mdo = MSOut::find($id);
        $dt  = DTOut::where('out_id', $id)
                            ->where('qty','>',0)
                            ->get();  
                            
        $gdg = Gudang::find($mdo->gudang_id);                    

        return view('keluar.faktur', compact('mdo','dt','gdg'));
    }
    
    
    public function posting(Request $request){
        
        $dt = MSOut::find($request['id_do']);
        
        $dtl = DTOut::where('out_id', $dt->id)
                        ->where('is_posted',0)
                        ->get();
        
        foreach($dtl as $dd){
            
            $this->updStock($dd->product_id, ($dd->qty * $dd->isi), $dt->gudang_id);
            
            $pp = DTOut::find($dd->id);
            $pp->is_posted = 1;
            $pp->update();
            
        }                
        
        $dt->is_posted=1;
        $dt->update();

        // insert logs
		$usrnm	= Auth::user()->username;
		
		$userlog = New User_logs;
		$userlog->title		= 'Posting DO Keluar Barang';
		$userlog->content	= 'DO '.$dt->out_no.' berhasil diposting oleh '.$usrnm;
		$userlog->user_id	= Auth::user()->id;
		$userlog->save();
        
        echo json_encode(['msg'=>'success']);        
    }

    public function updStock($id, $qty, $gdg ){
        /* sisa stock = current stock - qty */
        
        $prd = Product::find($id);
        if($prd->is_stock==0){ return true; }
        
        $stk = Stock::where('product_id', $id)
                        ->where('gudang_id', $gdg)
                        ->first();
        
        if(empty($stk)){
            $dt = New Stock;
            $dt->gudang_id  = $gdg;
            $dt->product_id = $id;
            $dt->stock_out  = $qty;
            $dt->tgl_out    = date('Y-m-d');
            $dt->stock_akhir -= $qty;
            $dt->save();
        }else{
            
            $stk->stock_out     += $qty;
            $stk->stock_akhir   -= $qty;
            $stk->tgl_out        = date('Y-m-d');
            $stk->update();
        }
        
        return true;
    }    


    public function unposting(){
        return view('sales.unposting');
    }
    
     public function unpost_faktur(){

        $sl = MSSale::with('get_customer','get_sales', 'get_gudang')
                        ->where('is_posted',1)
                        ->where('is_batal',0)
                        ->where('is_lunas',0)
                        ->orderBy('sale_no', 'DESC')
                        ->get();
                        
        $data=[];
        foreach($sl as $dt){
            
            $row=[];
            $row[] = $dt->sale_no;
            $row[] = $dt->get_gudang->kode;
            $row[] = tanggal_indonesia($dt->sale_tgl, false);
            $row[] = tanggal_indonesia($dt->sale_jt, false);
            $row[] = $dt->get_customer->cus_name;
            $row[] = $dt->get_sales->sales_name;
            $row[] = $dt->sale_disc;
            $row[] = $dt->sale_ppn;
            $row[] = '<div style="text-align:right">'.format_uang($dt->sale_netto).'</div>';
            
            $row[]='<a onclick="unpost('.$dt->id.')" class="btn btn-info btn-sm"><i class="fa fa-recycle"></i></a>';
                        
            $data[]=$row;
        }
        
        return response()->json(["data"=>$data]);
        
    }
     
    public function unposted($id){
        
        $dt = MSSale::find($id);
        
        $dtl = DTSale::where('sale_id', $id)
                        ->where('is_posted',1)
                        ->get();
        
        foreach($dtl as $dd){
            
            $this->updStock($dd->product_id, ($dd->qty * $dd->isi)*-1, $dt->gudang_id);
            
            $mode=2;
            StockController::OutstandingStock($dt->gudang_id, $dd->product_id, ($dd->qty * $dd->isi), $mode);
            
            $pp = DTSale::find($dd->id);
            $pp->is_posted = 0;
            $pp->update();
            
        }                
        
        $dt->is_posted=0;
        $dt->update();
        
        // insert logs
		$usrnm	= Auth::user()->username;
		
		$userlog = New User_logs;
		$userlog->title		= 'Unposting Faktur Penjualan';
		$userlog->content	= 'Faktur '.$dt->sale_no.' berhasil diunposting oleh '.$usrnm;
		$userlog->user_id	= Auth::user()->id;
		$userlog->save();
        
        
        echo json_encode(['msg'=>'success']);        
    }

    
/* history */    
    public function history_sale(){
	    $hari_ini = date("Y-m-d");
        $tgl_pertama = date('Y-m-01', strtotime($hari_ini));
        
	    $tglawal =date('Y-m-d', strtotime('-1 month', strtotime( $tgl_pertama )));
	    $tglakhir=date('Y-m-t', strtotime('+1 month', strtotime( $tglawal )));
	    
        return view('sales.history', compact('tglawal','tglakhir'));
    }    
    
    public function datahistory($tg1, $tg2){

        $sl = MSSale::with('get_customer','get_sales', 'get_gudang')
                        ->whereBetween('sale_tgl', [$tg1, $tg2])
                        ->where('is_posted',1)
                        ->orderBy('sale_no', 'DESC')
                        ->get();
                        
        $data=[];
        foreach($sl as $dt){
            
            if($dt->is_lunas==1){ $sts='<label class="label-success">&nbsp; Ya &nbsp;</label>';}else{ $sts='<label class="label-info">&nbsp; No &nbsp;</label>'; }
            if($dt->is_batal==1){ $sts='<label class="label-danger">&nbsp; BTL &nbsp;</label>'; }
            
            $row=[];
            $row[] = $dt->sale_no;
            $row[] = $dt->get_gudang->kode;
            $row[] = tanggal_indonesia($dt->sale_tgl, false);
            $row[] = tanggal_indonesia($dt->sale_jt, false);
            $row[] = $dt->get_customer->cus_name;
            $row[] = $dt->get_sales->sales_name;
            $row[] = $dt->sale_disc;
            $row[] = $dt->sale_ppn;
            $row[] = '<div style="text-align:right">'.format_uang($dt->sale_netto).'&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            $row[] = $sts;
            $row[]='<a onclick="showDetail('.$dt->id.')" class="btn btn-info btn-sm"><i class="fa fa-eye"></i></a>';
                        
            $data[]=$row;
        }
        
        return response()->json(["data"=>$data]);
        
    }
 
 
    public function index_tagihan(){
        $sls = Salesman::all();
        
        return view('sales.index_tagihan', compact('sls'));
    }

    public function report_tagihan(Request $request){
        
        $sls = Salesman::find($request['sls']);
        $area= Area::find($sls->sales_area);
        $dt = MSSale::with('get_customer')
                        ->where('sales_id', $sls->id)
                        ->where('is_posted', 1)
                        ->where('is_lunas', 0)
                        ->orderBy('sale_cust', 'ASC')
                        ->get();
                        
        return view('sales.tagihan', compact('sls', 'dt', 'area'));
    }



/* print faktur printer dotmatrix */
    public function printFaktur_matrix($id){
        
        $msl = MSSale::find($id);
        $bns = Bonus::where('sale_id', $id)
                        ->get();
        
        $dt  = DTSale::with('get_product')
                            ->where('sale_id', $id)
                            ->where('qty','>',0)
                            ->get();  
                            
        $cus = Customer::find($msl->sale_cust);                    
        $sls = Salesman::find($msl->sales_id);
        $area= Area::find($cus->cus_area);

        $pin    = 0;
        $on_ms  = 120;
        $off_ms = 240;
        $feed   = "\x0c";
        
        $lebarkolom = 80;
        $bold1      = Chr(27) . Chr(69);
        $bold0      = Chr(27) . Chr(70);
        $initialized= chr(27) . chr(64);
        $condensed1 = chr(15);
        $condensed0 = chr(18);

        $setLeft    = chr(27) . "a" . chr(0);
        $setCenter  = chr(27) . "a" . chr(1);
        $setRight   = chr(27) . "a" . chr(2); 
    
        $fontNormal	= chr(27) . "!" . chr(0);
        $fontKecil	= chr(27) . "!" . chr(1);
        $fontTebal	= chr(27) . "!" . chr(8);
        $fontBesar	= chr(27) . "!" . chr(16);
        $fontLebar	= chr(27) . "!" . chr(32);
        $fontUline	= chr(27) . "!" . chr(128);
        $fontSans   = chr(27) . "k" . chr(1);

        $grs=PrinterController::replicate('-',$lebarkolom);

        $Data  = $initialized;
        $Data .= $condensed0;

        $Data .= $fontTebal.PrinterController::center("FAKTUR PENJUALAN", $lebarkolom)."\n";
        $Data .= PrinterController::strKarakter(COMPANY,40).PrinterController::rataKanan("Faktur: ".$msl->sale_no,40)."\n";
        $Data .= PrinterController::rataKanan(tanggal_indonesia($msl->sale_tgl, false),80)."\n";
        $Data .= PrinterController::strKarakter("Salesman: ".$sls->sales_name,35)."Outlet: ".$cus->cus_name."\n";
        $Data .= PrinterController::strKarakter("J.Tempo : ".tanggal_indonesia($msl->sale_jt, false),35).substr($cus->cus_address,0,42)."\n";
        $Data .= PrinterController::space(35)."Area :".$area->area_name."\n";
        $Data .= PrinterController::strKarakter($msl->notes,70)."\n";

        $Data .= $condensed0;        
        $Data .= $grs."\n";
        //$Data .= $fontKecil.$fontTebal;
        
        /*        0        1         2         3         4         5         6         7         8         9*/
        /*        123456789.123456789.123456789.123456789.123456789.123456789.123456789.123456789.   */
        /*        1234 123456789.123456789.123456789.123456789. 9999XXX 9,999,999  999 99,999,999*/
        $Data .= "KODE  Nama Barang                             --QTY--     Harga Disc     Jumlah\n";
        $Data .= $grs."\n";
        
        $no = 0;
        $ttl = 0;
        
        foreach($dt as $dtl){
            $no++;
            $jlh = ($dtl->qty * $dtl->harga)-($dtl->qty*$dtl->harga*$dtl->disc_1/100) - $dtl->potongan; 
            $ttl += $jlh;
            
            $kd = $condensed1.PrinterController::strKarakter($dtl->get_product->kode_brg,8).$condensed0;
            $nm = PrinterController::strKarakter(substr($dtl->product_name,0,39),39);
            $qq = PrinterController::rataKanan(format_uang($dtl->qty),4)." ".substr($dtl->kemasan,0,3);
            $hg = PrinterController::strAngka($dtl->harga,9);
            
            
            if($dtl->disc_1>0){
                $ds = PrinterController::strAngka($dtl->disc_1,3)."%";
            }else{
                $ds = "  --";
            }
            
            //$ds = PrinterController::strAngka(($dtl->qty*$dtl->harga*$dtl->disc_1/100) +$dtl->potongan,7);
            
            $jl = PrinterController::strAngka($jlh,10);
            
            $Data .=$kd." ".$nm." ".$qq." ".$hg." ".$ds." ".$jl."\n";
        }
        
        if(count($bns)>0){
            foreach($bns as $bb){
                $no++;
                $jlh = 0;
                $ttl += $jlh;
                
                $kd = $condensed1.PrinterController::strKarakter('BONUS',8).$condensed0;
                $nm = PrinterController::strKarakter(substr($bb->bonus_ket,0,39),39);
                $qq = PrinterController::rataKanan(format_uang($bb->bonus_qty),4)." ".substr($bb->bonus_stn,0,3);
                $hg = PrinterController::strAngka($jlh,9);
                
                $ds = "  --";
      
                $jl = PrinterController::strAngka($jlh,10);
                
                $Data .=$kd." ".$nm." ".$qq." ".$hg." ".$ds." ".$jl."\n";                
            }
        }
        
        $Data .= $grs."\n";
        $Data .= PrinterController::space(55)."Sub Total   ".PrinterController::strAngka($ttl,13)."\n";
        
        $dis =0;
        $ppn =0;
        
        //if($msl->sale_disc>0){
            $dis = round($ttl * $msl->sale_disc/100);
            $Data .= PrinterController::strKarakter("PENAGIHAN HARUS DISERTAI FAKTUR ASLI !",55)."Disc ".PrinterController::strAngka($msl->sale_disc,3)."%   ".PrinterController::strAngka($dis,13)."\n";
        //}
        
        $ttl -= $dis;

        if($msl->sale_ppn>0){
            $ppn = round($ttl * $msl->sale_ppn/100);
            $Data .= PrinterController::space(55)."PPN         ".PrinterController::strAngka($ppn,13)."\n";
        }     
        
        $Data .= PrinterController::space(55)."# TOTAL #   ".PrinterController::strAngka($ppn+$ttl,13)."\n";
        $Data .= $condensed1.terbilang(round($ttl+$ppn))." rupiah# \n\n";
        //$Data .= $fontNormal.$fontTebal."PENAGIHAN HARUS DISERTAI FAKTUR ASLI !\n\n";
        $Data .= $condensed0.PrinterController::space(10).PrinterController::strKarakter('Penerima', 40).'Hormat Kami'."\n\n\n";
        $Data .= PrinterController::space(10).PrinterController::strKarakter('Cap & Nama Jelas',40).'Admin'."\n";
        
        $Data .= $feed;

        $dt = "intent:base64," . base64_encode($Data) . "#Intent;scheme=rawbt;package=ru.a402d.rawbtprinter;end;";
        $output = ["data"=>$dt];

        return response()->json($output);

    }
    







/*----------------------------------------------------fungsi string bisa dipanggil dari controller lain*/  

    public static function initPrinter(){
        
    /*initial font/printer */
        $pin = 0;
        $on_ms = 120;
        $off_ms = 240;
        
        $bold1      = Chr(27) . Chr(69);
        $bold0      = Chr(27) . Chr(70);
        $initialized= chr(27) . chr(64);
        $condensed1 = chr(15);
        $condensed0 = chr(18);
        $cut        = Chr(27) . Chr(109);   
        $pulse      = Chr(27) . "p" . chr($pin + 48) . chr($on_ms / 2) . chr($off_ms / 2);
        //chr(27)+'p'+chr(0)+chr(20)+chr(20))
        
        $fontNormal	= chr(27) . "!" . chr(0);
        $fontKecil	= chr(27) . "!" . chr(1);
        $fontSedang	= chr(27) . "!" . chr(8);
        $fontBesar	= chr(27) . "!" . chr(16);
        $fontLebar	= chr(27) . "!" . chr(32);
        $fontUline	= chr(27) . "!" . chr(128);
        
        return true;
    }

    public static function strAngka($hg, $len){
        $strangka = format_uang($hg);
        $langka = strlen($strangka);
        $lspc = $len - $langka;
        
        $strHg=self::space($lspc).$strangka;
        return $strHg;
    }
    
    public static function space($len){
        $strSpc="";
        $i=1;
        while($i<=$len){ $strSpc=$strSpc." "; $i++; }
        return $strSpc;
    }
    
    public function space_android($len){
        $strSpc="";
        $i=1;
        while($i<=$len){ $strSpc=$strSpc."%20"; $i++; }
        return $strSpc;
    }
    
    public static function center($strCenter,$lbrkolom){
        $lspc=($lbrkolom-strlen($strCenter))/2;

        return self::space($lspc).$strCenter;
    }
/*---------------------------------------------------------------------------------*/    


    public function tesCetak(){

        $cmp = Setting::first();
        $lebarkolom = $cmp->printer_col;     /*40;*/
        
        $img = EscposImage::load("logo_print.png", false);    
    
        $rasterData = $img -> toRasterFormat();
        $header = Printer::imgHeader([$img -> getWidthBytes(), $img -> getHeight()], true);

        $logoimg = chr(29) . "v0" . chr(0) . $header. $rasterData;
        
        
        $profile = CapabilityProfile::load("POS-5890");
        //$connector = new RawbtPrintConnector();        
        //$printer = new Printer($connector, $profile);
        $connector = new FilePrintConnector("php://stdout");
        $printer = new Printer($connector);

    $pin    = 0;
    $on_ms  = 120;
    $off_ms = 240;
    
    $bold1      = Chr(27) . Chr(69);
    $bold0      = Chr(27) . Chr(70);
    $initialized= chr(27) . chr(64);
    $condensed1 = chr(15);
    $condensed0 = chr(18);
    $cut        = Chr(27) . Chr(109);   
    $pulse      = Chr(27) . "p" . chr($pin + 48) . chr($on_ms / 2) . chr($off_ms / 2);
    //chr(27)+'p'+chr(0)+chr(20)+chr(20))
    
    $setLeft    = chr(27) . "a" . chr(0);
    $setCenter  = chr(27) . "a" . chr(1);
    $setRight   = chr(27) . "a" . chr(2); 

    //$EmphasisOn = chr(27) . "E" . chr(1);
    //$EmphasisOff= chr(27) . "E" . chr(0);
    $fontNormal	= chr(27) . "!" . chr(0);
    $fontKecil	= chr(27) . "!" . chr(1);
    $fontSedang	= chr(27) . "!" . chr(8);
    $fontBesar	= chr(27) . "!" . chr(16);
    $fontLebar	= chr(27) . "!" . chr(32);
    $fontUline	= chr(27) . "!" . chr(128);

    /*initial barcode */
    $barcode_h = Chr(29) . 'h' . Chr(70);                          //tinggi barcode 100
    $barcode_M = Chr(29) . "L" . Chr(10) . Chr(0);                  //margin Left 10
    $barcode_H = Chr(29) . 'H' . Chr(2);			                //posisi data dibawah barcode
    $barcode_f = Chr(29) . 'f' . Chr(0);                            //type font
    $barcode_39= chr(29) . 'k' . chr(4);
    $barcode_93= chr(29) . 'k' . chr(7);
    $barcode_128=chr(29) . 'k' . chr(8);
    $barcode_bar=chr(29) . 'k' . chr(6);
    $barcode_k = Chr(29) . 'k' . Chr(2) . '123456789012' . Chr(0);	//data dan type barocde 2=EAN13
    $barcode_L = Chr(29) . "L" . Chr(0) . Chr(0);                   //set margin ke posisi awal
    
    $cn     = '1'; // Code type for QR code
    $model  = 2;  // Select model: 1, 2 or micro.
    $size   = 8;
    $ec     = 1;
    $content = "--- Tes Print ---\n";
    $content .= "ABCDEF abcdef 0123456789.\n";
    $textbarcode = '1234567';
    $textBar128='abcdefg';
    
    // A21C1E11P0 <content> 1Q0
    $qrcode_model   = chr(65) . $cn . chr(48 + $model) . chr(0);        //A12
    $qrcode_size    = chr(67) . $cn . chr($size);                       //C1
    $qrcode_level   = chr(69) . $cn . chr(48 + $ec);                    //E11
    $qrcode_content = chr(80) . $cn . $content . '1';                   //P1 content 0
    $qrcode_print   = chr(81) . $cn . '' . '0';                         //.... A12C1E11P1 content  0Q1
    
        
        $Data  = $initialized;
        $Data .= $condensed0;
        $Data .= $content."\n";
        //$Data .= $fontNormal."Barcode Code39 \n";
        //$Data .= $barcode_h. $barcode_M.$barcode_H.$barcode_f.$barcode_39.$textbarcode.chr(0).$barcode_L."\n";
        $Data .= $fontNormal."Barcode Codebar \n";
        $Data .= $barcode_h. $barcode_M.$barcode_H.$barcode_f.$barcode_bar.$textbarcode.chr(0).$barcode_L."\n";        
        $Data .= $logoimg;      
        $Data .= "\n \n ";
        $Data .= $cut;
        
        $dt = "intent:base64," . base64_encode($Data) . "#Intent;scheme=rawbt;package=ru.a402d.rawbtprinter;end;";
        $output = ["data"=>$dt];

        return response()->json($output);
       
    }

	

        
    
    
    
}
