<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;
use App\ProductSub;
use App\Category;
use App\Supplier;
use App\Customer;
use App\Stock;
use App\InvoiceDetail;
use App\DTSale;
use App\Gudang;
use App\Outstanding;
use App\DTAdjust;
use App\MSOut;
use App\DTOut;

use App\User;
use App\User_logs;
use DataTables;
use DB;
use Closure;
use Auth;


class StockController extends Controller
{
	
    public function index()
    {
        $gdg = Gudang::all();
        $sup = Supplier::all();
        
		return view('stock.index', compact('gdg','sup'));
    }	
    
    
    function tampilProduk($id){
        $stk = Stock::find($id);
        
        $prd = Product::find($stk->product_id);
        echo json_encode($prd);
    }


    function listdata($id)
    {

        $stk = Stock::with('get_product','get_gudang')
                            //->leftjoin('ms_product', function($join){
                            //        $join->on('ms_product.id', '=', 'ms_stock.product_id');
                            //    })
                            ->where('ms_stock.gudang_id', $id)
                            ->get();
                            

                        
        $data = [];

        foreach($stk as $list){
            
            $stn=Product::find($list->product_id);

            $row = [];
            $row[] = $list->get_gudang->kode;
            $row[] = $list->get_product->nama_brg;
            $row[] = Category::get_category($list->get_product->cat_id)->cat_name;
            $row[] = $list->get_product->satuan.'/'.$list->get_product->isi;
            $row[] = '<div style="text-align:right">'.format_uang($list->stock_akhir).' '.$stn->satuan.'&nbsp;&nbsp;&nbsp;</div>';

            if(Auth::user()->group=="MANAGER"){
                $row[] = '<div class="btn-btn">
                            <a onclick="showDetail('.$list->id.')" class="btn btn-primary btn-sm"><i class="fa fa-list"></i></a>
                            <a onclick="adjust('.$list->id.')" class="btn btn-danger btn-sm"><i class="fa fa-pencil"></i></a>
                        </div>';
            }else{
                $row[] = '<div class="btn-btn">
                            <a onclick="showDetail('.$list->id.')" class="btn btn-primary btn-sm"><i class="fa fa-list"></i></a>
                        </div>';               
            }
           
           $data[] = $row;
        }

        return response()->json(["data"=>$data]);
    }
    

    public function show($id){
        $stk = Stock::find($id);
        echo json_encode($stk);
    }

    public function tampilStock($id){
        $stk = Stock::find($id);
        
        $dt = $stk->stock_akhir;
        echo json_encode(["stock"=>$dt]);
    }
    

    public function stockRekap($id){
        $st = Stock::find($id);
        
        $data=[];
        
        if($st->tgl_awal !=null){
        $row=[];
        $row[]="Stock Awal";
        $row[]= $st->stock_awal;
        $row[]= tanggal_indonesia($st->tgl_awal, false);
        $data[]=$row;
        }
        
        if($st->tgl_in !=null){
        $row=[];
        $row[]="Pembelian";
        $row[]= $st->stock_in;
        $row[]= tanggal_indonesia($st->tgl_in, false);
        $data[]=$row;
        }
        
        if($st->tgl_out !=null){
        $row=[];        
        $row[]="Stock Keluar";
        $row[]=  $st->stock_out;
        $row[]= tanggal_indonesia($st->tgl_out, false);
        $data[]=$row;
        }
        
        if($st->tgl_retur !=null){
        $row=[];        
        $row[]="Retur";
        $row[]= $st->stock_retur;
        $row[]= tanggal_indonesia($st->tgl_retur, false);
        $data[]=$row;
        }
        
        if($st->tgl_mts_out !=null){
        $row=[];     
        $row[]="Mutasi Out";
        $row[]= $st->stock_mts_out;
        $row[]= tanggal_indonesia($st->tgl_mts_out, false);
        $data[]=$row;
        }
        
        if($st->tgl_mts_in !=null){
        $row=[];        
        $row[]="Mutasi In";
        $row[]= $st->stock_mts_in;
        $row[]= tanggal_indonesia($st->tgl_mts_in, false);
        $data[]=$row;
        }
        
        if($st->tgl_adjust !=null){
        $row=[];        
        $row[]="Koreksi";
        $row[]= $st->stock_adjust;        /*format_uang($st->stock_adjust).' PCS';*/
        $row[]= tanggal_indonesia($st->tgl_adjust, false);
        $data[]=$row;
        }
        
        $row=[];       
        $row[]="Stock Akhir";
        $row[]= $st->stock_akhir;
        $row[]= "";
        $data[]=$row;

        echo json_encode(["data"=>$data]);
    }        
    
    public function stockMasuk($id){

        $st = Stock::find($id);
        $tglawal = $st->tgl_awal;
        $data=[];
        if(is_null($tglawal)){ return json_encode(["data"=>$data]);}

        $dt = DB::table('dt_invoice as A')
                    ->select('A.product_id','A.satuan','A.isi','A.qty','A.is_posted','B.inv_tgl', 'B.inv_no')
                    ->leftjoin('ms_invoice as B', function($join) {
                            $join->on('A.inv_id', '=', 'B.id');
                        })
                    ->where('A.product_id','=', $st->product_id)
                    ->where('A.is_posted', 1)
                    ->where('B.inv_tgl', '>=', $tglawal)
                    ->where('B.gudang_id','=', $st->gudang_id)
                    ->get();

                            
      
        foreach($dt as $stk){
            $row=[];

            $row[]= tanggal_indonesia($stk->inv_tgl, false);
            $row[]= $stk->inv_no;
            $row[]= '<div class="text-right">'.format_uang($stk->qty).'</div>';
            //$row[]= $stk->satuan.'/'.$stk->isi;
            
            
            $data[]=$row;
        }
        
        echo json_encode(["data"=>$data]);
    }

    public function stockKeluar($id){
        
        $data=[];        
        $st = Stock::find($id);
        $tglawal = $st->tgl_awal;
        if(is_null($tglawal)){ return json_encode(["data"=>$data]);}
        
        $dt = DB::table('dt_out as A')
                    ->select('A.product_id','A.qty','A.satuan','A.isi','B.out_tgl', 'B.out_no', 'B.tujuan')
                    ->leftjoin('ms_out as B', function($join) {
                        $join->on('A.out_id', '=', 'B.id');
                    })
                    ->where('A.product_id', $st->product_id)
                    ->where('B.out_tgl', '>=', $tglawal)
                    ->where('A.qty','>',0)
                    ->where('A.is_posted',1)
                    ->where('B.gudang_id', $st->gudang_id)
                    ->get();

        foreach($dt as $stk){
            $row=[];
            $row[]= tanggal_indonesia($stk->out_tgl, false);
            $row[]= $stk->out_no;
            $row[]= $stk->tujuan;
            $row[]= '<div class="text-right">'.format_uang($stk->qty).'&nbsp;&nbsp;</div>';
            //$row[]= $stk->satuan.'/'.$stk->isi;
            
            
            $data[]=$row;
        }
        
        echo json_encode(["data"=>$data]);
    }
    
    public function stockRetur($id){
        
        $data=[];        
        return response()->json(["data"=>$data]);
        
        $st = Stock::find($id);
        $tglawal = $st->tgl_awal;
        
        if($tglawal==null){ return json_encode(["data"=>$data]);}
        
        $dt = DB::table('dt_retur as A')
                    ->select('A.*','B.rtr_tgl', 'B.rtr_no', 'B.rtr_cust')
                    ->leftjoin('ms_retur as B', function($join) {
                        $join->on('A.rtr_id', '=', 'B.id');
                    })
                    ->where('A.product_id', $st->product_id)
                    ->where('B.rtr_tgl', '>=', $tglawal)
                    ->where('A.is_posted',1)
                    ->where('A.gudang_id', $st->gudang_id)
                    ->get();

        foreach($dt as $stk){
            $row=[];
            $row[]= tanggal_indonesia($stk->rtr_tgl, false);
            $row[]= $stk->rtr_no;
            $row[]= Customer::cekCustomer($stk->rtr_cust)->cus_name;
            $row[]= $stk->kemasan.'/'.$stk->isi;
            $row[]= '<div class="text-right">'.format_uang($stk->qty).'&nbsp;&nbsp;</div>';
            
            $data[]=$row;
        }
        
        echo json_encode(["data"=>$data]);
    }    
    
    public function printform($id){
        
        $gdg = Gudang::find($id);
        
        $dt = DB::table('ms_stock as A')
                    ->select('B.nama_brg')
                    ->leftjoin('ms_product as B', function($join){
                        $join->on('A.product_id','=', 'B.id');
                    })
                    ->where('A.gudang_id', $id)
                    ->orderBy('B.nama_brg', 'ASC')
                    ->get();

        $no=1;                    
                    
        return view('stock.form_opn', compact('dt','gdg','no'));
    }
    
    
    
/* print faktur printer dotmatrix */
    public function print_form($id){
        
        $gdg = Gudang::find($id);
        
        $opn = DB::table('ms_stock as A')
                    ->select('B.kode_brg', 'B.nama_brg')
                    ->leftjoin('ms_product as B', function($join){
                        $join->on('A.product_id','=', 'B.id');
                    })
                    ->where('A.gudang_id', $id)
                    ->orderBy('B.kode_brg', 'ASC')
                    ->get();
                            
        $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("FORM STOCK OPNAME", $lebarkolom)."\n\n";
        $Data .= PrinterController::strKarakter($gdg->nama,48)."Tgl.Opname: __________________\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                              --SATUAN--     QTY    Notes     \n";
        $Data .= $grs."\n";
        
        $no = 0;
        $ttl = 0;
        
        foreach($opn as $dtl){
            $no++;
            if($no>25){
                $no=0;
                $Data .= "\n\n\n\n".$feed."\n\n";
                $Data .= $grs."\n";
                $Data .= "KODE Nama Barang                              --SATUAN--     QTY    Notes     \n";
                $Data .= $grs."\n";
            }
            
            $kd = PrinterController::strKarakter($dtl->kode_brg,4);
            $nm = PrinterController::strKarakter(substr($dtl->nama_brg,0,40),40);

            $Data .=$kd." ".$nm."\n".$grs."\n";
        }
        
        //$Data .= $grs."\n";
        $Data .= PrinterController::space(10).PrinterController::strKarakter('Checker', 40).'Mengetahui'."\n\n\n";
        $Data .= PrinterController::space(10).PrinterController::strKarakter('________________',40).'______________'."\n";
        
        $Data .= $feed;

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

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

    }
    
    
    public static function OutstandingStock($gdg, $prd, $qty, $mode){
        
        return true;
        
        /* tidak dipake lagi */
        
        $ada = Outstanding::where('gudang_id', $gdg)
                            ->where('product_id', $prd)
                            ->first();
                            
        if(empty($ada)){
            
            $out = new Outstanding;
            $out->gudang_id     = $gdg;
            $out->product_id    = $prd;
            
            if($mode==1){ $out->stock_in = $qty; }else{ $out->stock_out = $qty; }
            $out->save();
            
        }else{
            
            if($mode==1){
                $ada->stock_in  += $qty;
            }else{
                $ada->stock_out += $qty;
            }
            
            $ada->update();
        }                    
        
        /* insert logs
		$usrnm	= Auth::user()->username;
		
		$userlog = New User_logs;
		$userlog->title		= 'Update Outstanding Stock';
		$userlog->content	= 'Outstanding Stock -> product id:'.$prd.' QTY:'.$qty;
		$userlog->user_id	= Auth::user()->id;
		$userlog->save();        
        */
        
        return true;
    }
    

/* cek sisa stock berdasarkan data yg blm posting */    
    public static function cekStock($gdg, $prd){
        
        $sisa=0; $masuk=0; $sale=0; $mts_in=0; $mts_out=0; $retur=0;
    
    /* sisa stock */    
        $stk = Stock::where('gudang_id', $gdg)
                        ->where('product_id', $prd)
                        ->first();
        if(!empty($stk)){ $sisa=$stk->stock_akhir; }
    
    /* barang masuk TIDAK DIHITUNG  */
    /*
        $inv = DB::table('dt_invoice as A')
                    ->select('A.product_id')
                    ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                    ->leftjoin('ms_invoice as B', function($join){
                        $join->on('A.inv_id', '=', 'B.id');
                    })
                    ->where('B.gudang_id', $gdg)
                    ->where('A.product_id', $prd)
                    ->where('A.qty','>',0)
                    ->where('A.is_posted',0)
                    ->groupBy('A.product_id')
                    ->get();
                    
        foreach($inv as $in){ $masuk += $in->qty; }
    */
    
    /* penjualan */
        $sl = DB::table('dt_sale as A')
                    ->select('A.product_id')
                    ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                    ->leftjoin('ms_sale as B', function($join){
                        $join->on('A.sale_id', '=', 'B.id');
                    })
                    ->where('B.gudang_id', $gdg)
                    ->where('A.product_id', $prd)
                    ->where('A.qty','>',0)
                    ->where('A.is_posted',0)
                    ->groupBy('A.product_id')
                    ->get();
                    
        foreach($sl as $ss){ $sale += $ss->qty; }    
        
    /* retur    */
        $rtr = DB::table('dt_retur')
                    ->select('product_id')
                    ->addSelect(DB::raw('SUM(qty * isi) as qty'))
                    ->where('gudang_id', $gdg)
                    ->where('product_id', $prd)
                    ->where('qty','>',0)
                    ->where('is_posted', 0)
                    ->groupBy('product_id')
                    ->get();
                    
        foreach($rtr as $rr){ $retur += $rr->qty; }
        
    /* mutasi out ms_mutasi.mts_from  */
        $out = DB::table('dt_mutasi as A')
                    ->select('A.product_id')
                    ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                    ->leftjoin('ms_mutasi as B', function($join){
                        $join->on('A.mts_id', '=', 'B.id');
                    })
                    ->where('B.mts_from', $gdg)
                    ->where('A.product_id', $prd)
                    ->where('A.qty','>',0)
                    ->where('A.is_posted', 0)
                    ->groupBy('A.product_id')
                    ->get();
        
        foreach($out as $oo){ $mts_out += $oo->qty; }
        
     /* mutasi in ms_mutasi.mts_to  */
        $in = DB::table('dt_mutasi as A')
                    ->select('A.product_id')
                    ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                    ->leftjoin('ms_mutasi as B', function($join){
                        $join->on('A.mts_id', '=', 'B.id');
                    })
                    ->where('B.mts_to', $gdg)
                    ->where('A.product_id', $prd)
                    ->where('A.qty','>',0)
                    ->where('A.is_posted', 0)
                    ->groupBy('A.product_id')
                    ->get();
        
        foreach($in as $ii){ $mts_in += $ii->qty; }   
    
        //$sisa; +$masuk; -$sale; +$mts_in; -$mts_out; +$retur;
        $rekap = $sisa + $masuk + $mts_in + $retur - $sale - $mts_out;
        
        //return response()->json(["sisa"=>$sisa, "masuk"=>$masuk, "out"=>$mts_out, "in"=>$mts_in, "sale"=>$sale, "retur"=>$retur]);
        
        return $rekap;
    }
    
    
/* cek sisa stock berdasarkan data yg blm posting */    
    public static function cekOutStanding($idstock){
        
        $sisa=0; $masuk=0; $sale=0; $mts_in=0; $mts_out=0; $retur=0;
        $data=[];
        
        $stk = Stock::find($idstock);
 
    /* barang masuk*/
        $inv = DB::table('dt_invoice as A')
                    ->select('A.product_id')
                    ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                    ->leftjoin('ms_invoice as B', function($join){
                        $join->on('A.inv_id', '=', 'B.id');
                    })
                    ->where('B.gudang_id', $stk->gudang_id)
                    ->where('A.product_id', $stk->product_id)
                    ->where('A.qty','>',0)
                    ->where('A.is_posted',0)
                    ->groupBy('A.product_id')
                    ->get();
                    
        foreach($inv as $in){ $masuk += $in->qty; }
        $row=[];
        $row[]="Pembelian";
        $row[]= self::KonversiStock($stk->product_id, $masuk);
        $data[]=$row;
        
    /* penjualan */
        $sl = DB::table('dt_sale as A')
                    ->select('A.product_id')
                    ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                    ->leftjoin('ms_sale as B', function($join){
                        $join->on('A.sale_id', '=', 'B.id');
                    })
                    ->where('B.gudang_id', $stk->gudang_id)
                    ->where('A.product_id', $stk->product_id)
                    ->where('A.qty','>',0)
                    ->where('A.is_posted',0)
                    ->groupBy('A.product_id')
                    ->get();
                    
        foreach($sl as $ss){ $sale += $ss->qty; }  
        $row=[];
        $row[]="Penjualan";
        $row[]= self::KonversiStock($stk->product_id, $sale);
        $data[]=$row;
        
    /* retur    */
        $rtr = DB::table('dt_retur')
                    ->select('product_id')
                    ->addSelect(DB::raw('SUM(qty * isi) as qty'))
                    ->where('gudang_id', $stk->gudang_id)
                    ->where('product_id', $stk->product_id)
                    ->where('qty','>',0)
                    ->where('is_posted', 0)
                    ->groupBy('product_id')
                    ->get();
                    
        foreach($rtr as $rr){ $retur += $rr->qty; }
        $row=[];
        $row[]="Retur ";
        $row[]= self::KonversiStock($stk->product_id, $retur);
        $data[]=$row;
        
    /* mutasi out ms_mutasi.mts_from  */
        $out = DB::table('dt_mutasi as A')
                    ->select('A.product_id')
                    ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                    ->leftjoin('ms_mutasi as B', function($join){
                        $join->on('A.mts_id', '=', 'B.id');
                    })
                    ->where('B.mts_from', $stk->gudang_id)
                    ->where('A.product_id', $stk->product_id)
                    ->where('A.qty','>',0)
                    ->where('A.is_posted', 0)
                    ->groupBy('A.product_id')
                    ->get();
        
        foreach($out as $oo){ $mts_out += $oo->qty; }
        $row=[];
        $row[]="Mutasi Out";
        $row[]=self::KonversiStock($stk->product_id, $mts_out);
        $data[]=$row;
        
     /* mutasi in ms_mutasi.mts_to  */
        $in = DB::table('dt_mutasi as A')
                    ->select('A.product_id')
                    ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                    ->leftjoin('ms_mutasi as B', function($join){
                        $join->on('A.mts_id', '=', 'B.id');
                    })
                    ->where('B.mts_to', $stk->gudang_id)
                    ->where('A.product_id', $stk->product_id)
                    ->where('A.qty','>',0)
                    ->where('A.is_posted', 0)
                    ->groupBy('A.product_id')
                    ->get();
        
        foreach($in as $ii){ $mts_in += $ii->qty; }   
        $row=[];
        $row[]="Mutasi In";
        $row[]=self::KonversiStock($stk->product_id, $mts_in);
        $data[]=$row;        
    
        return response()->json(["data"=>$data]);

    }    
    
    public function kartuStock($id, $tgl1, $tgl2){
        
        $tglnow = date('Y-m-d');
        $t_awal=date('Y-m-d', strtotime('-1 day', strtotime( $tgl1 )));
        $t_akhir=date('Y-m-d', strtotime('+1 day', strtotime( $tgl2 )));
        
        if(strtotime($tgl2) > strtotime($tglnow)){ $tgl2 = $tglnow; }
        
        $rkp = Stock::find($id);
        $prd = Product::find($rkp->product_id);
        $gdg = Gudang::find($rkp->gudang_id);
        
        $beli = DB::table('dt_invoice as A')
                        ->select('A.product_id')
                        ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                        ->leftjoin('ms_invoice as B', function($join){
                                $join->on('A.inv_id','=','B.id');
                            })
                        ->where('B.gudang_id', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->where('B.inv_tgl','>=', $rkp->tgl_awal)
                        ->where('A.is_posted', 1)
                        ->groupBy('A.product_id')
                        ->get();

        /* akumulasi sale dari awal - $t_awal */
        $sale1 = DB::table('dt_sale as A')
                        ->select('A.product_id')
                        ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                        ->leftjoin('ms_sale as B', function($join){
                                $join->on('A.sale_id','=','B.id');
                            })
                        ->where('B.gudang_id', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->whereBetween('B.sale_tgl',[$rkp->tgl_awal, $t_awal])
                        ->where('A.is_posted', 1)
                        ->groupBy('A.product_id')
                        ->get();   
        
        if($tgl2=$tglnow){
            $sale2=[];
        }else{
        /* akumulasi sale dari $t_akhir - now*/
                $sale2 = DB::table('dt_sale as A')
                        ->select('A.product_id')
                        ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                        ->leftjoin('ms_sale as B', function($join){
                                $join->on('A.sale_id','=','B.id');
                            })
                        ->where('B.gudang_id', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->whereBetween('B.sale_tgl',[$t_akhir, $tglnow])
                        ->where('A.is_posted', 1)
                        ->groupBy('A.product_id')
                        ->get();   
        }
        
        $sale3 = DB::table('dt_sale as A')
                        ->select('B.sale_tgl','A.product_id')
                        ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                        ->leftjoin('ms_sale as B', function($join){
                                $join->on('A.sale_id','=','B.id');
                            })
                        ->where('B.gudang_id', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->whereBetween('B.sale_tgl',[$tgl1, $tgl2])
                        ->where('A.is_posted', 1)
                        ->groupBy('B.sale_tgl')
                        ->groupBy('A.product_id')
                        ->get();        

        $retur = DB::table('dt_retur as A')
                        ->select('A.product_id')
                        ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                        ->leftjoin('ms_retur as B', function($join){
                                $join->on('A.rtr_id','=','B.id');
                            })
                        ->where('A.gudang_id', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->where('B.rtr_tgl','>=', $rkp->tgl_awal)
                        ->where('A.is_posted', 1)
                        ->groupBy('A.product_id')
                        ->get();
                        
        $mts_in = DB::table('dt_mutasi as A')
                        ->select('A.product_id')
                        ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                        ->leftjoin('ms_mutasi as B', function($join){
                                $join->on('A.mts_id','=','B.id');
                            })
                        ->where('B.mts_to', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->where('B.mts_tgl','>=', $rkp->tgl_awal)
                        ->where('A.is_posted', 1)
                        ->groupBy('A.product_id')
                        ->get();          

        $mts_out = DB::table('dt_mutasi as A')
                        ->select('A.product_id')
                        ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                        ->leftjoin('ms_mutasi as B', function($join){
                                $join->on('A.mts_id','=','B.id');
                            })
                        ->where('B.mts_from', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->where('B.mts_tgl','>=', $rkp->tgl_awal)
                        ->where('A.is_posted', 1)
                        ->groupBy('A.product_id')
                        ->get();   
                        
        $adj    = DB::table('dt_adjust')
                        ->select('A.produt_id')
                        ->addSelect(DB::raw('SUM(adj_qty) as qty'))
                        ->where('gudang_id', $rkp->gudang_id)
                        ->where('product_id', $prd->id)
                        ->where('A.aj_tgl','>=', $rkp->tgl_awal)
                        ->groupBy('A.product_id')
                        ->get();


        $pin    = 0;
        $on_ms  = 120;
        $off_ms = 240;
        $feed   = "\x0c";
        
        $lebarkolom = 75;
        $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;

        $produk = $prd->kode_brg." - ".$prd->nama_brg;

        $Data .= $fontTebal.PrinterController::strKarakter("KARTU STOCK", 50)."\n\n";
        $Data .= PrinterController::strKarakter($gdg->nama,50)."\n";
        $Data .= PrinterController::strKarakter($produk,60)."\n";

        $Data .= $condensed1;        
        $Data .= $grs."\n";

        $no = 0; $tlbeli=0; $tlsale=0; $tlretur=0; $tlout=0; $tlin=0; $tladj=0;
        
        $Data .=PrinterController::strKarakter("Stock Awal",20).PrinterController::strKarakter(tanggal_indonesia($rkp->tgl_awal, false),15 ).
                PrinterController::rataKanan($this->KonversiStock($prd->id, $rkp->stock_awal),29)."\n";
                //$this->KonversiStock($out->product_id, $out->stock_in)
        
        if($beli->count()>0){        
            $Data .="(+) Pembelian : \n";
            foreach($beli as $bl){
                //$Data .=PrinterController::space(25).
                //        PrinterController::strKarakter($this->KonversiStock($prd->id, $bl->qty),25)."\n";
                        $tlbeli += $bl->qty ;
            }
            if($tlbeli>0){
                $Data .=PrinterController::space(5).PrinterController::strKarakter("Total --->",20).
                        PrinterController::rataKanan($this->KonversiStock($prd->id, $tlbeli),39)."\n\n";
            }
        }
        
        $Data .="(-) Penjualan : \n";
        if($sale1->count()>0){
            
            $periode = tanggal_indonesia($rkp->tgl_awal, false).' - '.tanggal_indonesia($t_awal, false);
            
            foreach($sale1 as $sl1){
                $Data .=PrinterController::space(5).PrinterController::strKarakter($periode,25).
                        PrinterController::rataKanan($this->KonversiStock($prd->id, $sl1->qty),34)."\n";
                        $tlsale += $sl1->qty;
            }    
        }
        
        if($sale3->count()>0){
            foreach($sale3 as $sl3){
                $Data .=PrinterController::space(5).PrinterController::strKarakter(tanggal_indonesia($sl3->sale_tgl, false),34).
                        PrinterController::rataKanan($this->KonversiStock($prd->id, $sl3->qty),25)."\n";
                        $tlsale += $sl3->qty;
            }          
        }
        
        if(!empty($sale2)){
            foreach($sale2 as $sl2){
                $Data .=PrinterController::space(5).PrinterController::strKarakter(tanggal_indonesia($t_akhir, false),12).' - '.
                        PrinterController::strKarakter(tanggal_indonesia($tglnow, false),22).
                        PrinterController::rataKanan($this->KonversiStock($prd->id, $sl3->qty),25)."\n";
                        $tlsale += $sl3->qty;
            }    
        }
        
        if($tlsale>0){
            $Data .=PrinterController::space(5).PrinterController::strKarakter("Total --->",20).
                    PrinterController::rataKanan($this->KonversiStock($prd->id, $tlsale),39)."\n\n";
        }        
        
        
        if($mts_in->count()>0){
            $Data .="(+) Mutasi In : \n";
            foreach($mts_in as $m_in){
                //$Data .=PrinterController::space(25).
                //        PrinterController::rataKanan($this->KonversiStock($prd->id, $m_in->qty),25)."\n";
                        $tlin += $m_in->qty ;
            }    
            if($tlin>0){
                $Data .=PrinterController::space(5).PrinterController::strKarakter("Total --->",20).
                        PrinterController::rataKanan($this->KonversiStock($prd->id, $tlin),39)."\n\n";
            }        
        }        

        if($mts_out->count()>0){
            $Data .="(-) Mutasi Out : \n";
            foreach($mts_out as $m_out){
                //$Data .=PrinterController::space(25).
                //        PrinterController::rataKanan($this->KonversiStock($prd->id, $m_out->qty),25)."\n";
                        $tlout += $m_out->qty ;
            }    
            if($tlout>0){
                $Data .=PrinterController::space(5).PrinterController::strKarakter("Total --->",20).
                        PrinterController::rataKanan($this->KonversiStock($prd->id, $tlout),39)."\n\n";
            }        
        }     
        
        if($retur->count()>0){
            $Data .="(+) Retur Penjualan : \n";
            foreach($retur as $rtr){
                //$Data .=PrinterController::space(25).
                //        PrinterController::rataKanan($this->KonversiStock($prd->id, $rtr->qty),25)."\n";
                        $tlretur += $rtr->qty ;
            }    
            if($tlretur>0){
                $Data .=PrinterController::space(5).PrinterController::strKarakter("Total --->",20).
                        PrinterController::rataKanan($this->KonversiStock($prd->id, $tlretur),39)."\n\n";
            }        
        }                
        
        if($adj->count()>0){
            $Data .="(+) Adjustment Stock : \n";
            foreach($adj as $ad){
                $tladj += $ad->qty ;
            }    
            if($tladj>0){
                $Data .=PrinterController::space(5).PrinterController::strKarakter("Total --->",20).
                        PrinterController::rataKanan($this->KonversiStock($prd->id, $tladj),39)."\n\n";
            }        
        }                




        $Data .=PrinterController::space(5).PrinterController::strKarakter("-- Stock Akhir --->",20).
                        PrinterController::rataKanan($this->KonversiStock($prd->id, $rkp->stock_akhir),39)."\n\n";
                        
        $Data .= $grs."\n";
        
        $c_now = date('Y-m-d H:i:s', time());
        
        $Data .= $c_now." eof report \n";
        $Data .= $feed;

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

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

    public function kartu___Stock($id, $tgl1, $tgl2){
        
        $t_awal=date('Y-m-d', strtotime('-1 day', strtotime( $tgl1 )));
        $t_akhir=date('Y-m-d', strtotime('+1 day', strtotime( $tgl2 )));
        
        $rkp = Stock::find($id);
        $prd = Product::find($rkp->product_id);
        $gdg = Gudang::find($rkp->gudang_id);
        
        $beli = DB::table('dt_invoice as A')
                        ->select('B.inv_tgl','A.product_id','A.satuan','A.isi')
                        ->addSelect(DB::raw('SUM(A.qty) as qty'))
                        ->leftjoin('ms_invoice as B', function($join){
                                $join->on('A.inv_id','=','B.id');
                            })
                        ->where('B.gudang_id', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->where('B.inv_tgl','>=', $rkp->tgl_awal)
                        ->where('A.is_posted', 1)
                        ->groupBy('B.inv_tgl')
                        ->groupBy('A.product_id')
                        ->groupBy('A.satuan')
                        ->groupBy('A.isi')
                        ->get();

        $sale = DB::table('dt_sale as A')
                        ->select('B.sale_tgl','A.product_id','A.kemasan','A.isi')
                        ->addSelect(DB::raw('SUM(A.qty) as qty'))
                        ->leftjoin('ms_sale as B', function($join){
                                $join->on('A.sale_id','=','B.id');
                            })
                        ->where('B.gudang_id', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->where('B.sale_tgl','>=', $rkp->tgl_awal)
                        ->where('A.is_posted', 1)
                        ->groupBy('B.sale_tgl')
                        ->groupBy('A.product_id')
                        ->groupBy('A.kemasan')
                        ->groupBy('A.isi')                        
                        ->get();        

        $retur = DB::table('dt_retur as A')
                        ->select('B.rtr_no','B.rtr_tgl','A.product_id','A.qty','A.kemasan','A.isi')
                        ->leftjoin('ms_retur as B', function($join){
                                $join->on('A.rtr_id','=','B.id');
                            })
                        ->where('A.gudang_id', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->where('B.rtr_tgl','>=', $rkp->tgl_awal)
                        ->where('A.is_posted', 1)
                        ->get();
                        
        $mts_in = DB::table('dt_mutasi as A')
                        ->select('B.mts_no','B.mts_tgl','A.product_id','A.qty','A.satuan','A.isi')
                        ->leftjoin('ms_mutasi as B', function($join){
                                $join->on('A.mts_id','=','B.id');
                            })
                        ->where('B.mts_to', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->where('B.mts_tgl','>=', $rkp->tgl_awal)
                        ->where('A.is_posted', 1)
                        ->get();          

        $mts_out = DB::table('dt_mutasi as A')
                        ->select('B.mts_no','B.mts_tgl','A.product_id','A.qty','A.satuan','A.isi')
                        ->leftjoin('ms_mutasi as B', function($join){
                                $join->on('A.mts_id','=','B.id');
                            })
                        ->where('B.mts_from', $rkp->gudang_id)
                        ->where('A.product_id', $prd->id)
                        ->where('B.mts_tgl','>=', $rkp->tgl_awal)
                        ->where('A.is_posted', 1)
                        ->get();   


        $pin    = 0;
        $on_ms  = 120;
        $off_ms = 240;
        $feed   = "\x0c";
        
        $lebarkolom = 75;
        $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;

        $produk = $prd->kode_brg." - ".$prd->nama_brg;

        $Data .= $fontTebal.PrinterController::strKarakter("KARTU STOCK", 50)."\n\n";
        $Data .= PrinterController::strKarakter($gdg->nama,50)."\n";
        $Data .= PrinterController::strKarakter($produk,60)."\n";

        $Data .= $condensed1;        
        $Data .= $grs."\n";

        $no = 0; $tlbeli=0; $tlsale=0; $tlretur=0; $tlout=0; $tlin=0;
        
        $Data .=PrinterController::strKarakter("Stock Awal",25).PrinterController::strKarakter(tanggal_indonesia($rkp->tgl_awal, false),15 ).
                PrinterController::strKarakter($this->KonversiStock($prd->id, $rkp->stock_awal),25)."\n";
                //$this->KonversiStock($out->product_id, $out->stock_in)
        
        if($beli->count()>0){        
            $Data .="(+) Pembelian : \n";
            foreach($beli as $bl){
                $Data .=PrinterController::space(5).PrinterController::strKarakter(tanggal_indonesia($bl->inv_tgl, false),20).
                        PrinterController::strKarakter($this->KonversiStock($prd->id, $bl->qty*$bl->isi),25)."\n";
                        $tlbeli += $bl->qty * $bl->isi;
            }
            if($tlbeli>0){
                $Data .=PrinterController::space(15).PrinterController::strKarakter("Total --->",20).
                        PrinterController::strKarakter($this->KonversiStock($prd->id, $tlbeli),35)."\n\n";
            }
        }
        
        if($sale->count()>0){
            $Data .="(-) Penjualan : \n";
            foreach($sale as $sl){
                $Data .=PrinterController::space(5).PrinterController::strKarakter(tanggal_indonesia($sl->sale_tgl, false),20).
                        PrinterController::strKarakter($this->KonversiStock($prd->id, $sl->qty*$sl->isi),25)."\n";
                        $tlsale += $sl->qty * $sl->isi;
            }    
            if($tlsale>0){
                $Data .=PrinterController::space(15).PrinterController::strKarakter("Total --->",20).
                        PrinterController::strKarakter($this->KonversiStock($prd->id, $tlsale),35)."\n\n";
            }        
        }
        
        if($mts_in->count()>0){
            $Data .="(+) Mutasi In : \n";
            foreach($mts_in as $m_in){
                $Data .=PrinterController::space(5).PrinterController::strKarakter(tanggal_indonesia($m_in->mts_tgl, false),20).
                        PrinterController::strKarakter($this->KonversiStock($prd->id, $m_in->qty * $m_in->isi),25)."\n";
                        $tlin += $m_in->qty * $m_in->isi;
            }    
            if($tlin>0){
                $Data .=PrinterController::space(15).PrinterController::strKarakter("Total --->",20).
                        PrinterController::strKarakter($this->KonversiStock($prd->id, $tlin),35)."\n\n";
            }        
        }        

        if($mts_out->count()>0){
            $Data .="(-) Mutasi Out : \n";
            foreach($mts_out as $m_out){
                $Data .=PrinterController::space(5).PrinterController::strKarakter(tanggal_indonesia($m_out->mts_tgl, false),20).
                        PrinterController::strKarakter($this->KonversiStock($prd->id, $m_out->qty * $m_out->isi),25)."\n";
                        $tlout += $m_out->qty * $m_out->isi;
            }    
            if($tlout>0){
                $Data .=PrinterController::space(5).PrinterController::strKarakter("Total --->",20).
                        PrinterController::strKarakter($this->KonversiStock($prd->id, $tlout),35)."\n\n";
            }        
        }     
        
        if($retur->count()>0){
            $Data .="(+) Retur Penjualan : \n";
            foreach($retur as $rtr){
                $Data .=PrinterController::space(5).PrinterController::strKarakter(tanggal_indonesia($rtr->rtr_tgl, false),20).
                        PrinterController::strKarakter($this->KonversiStock($prd->id, $rtr->qty * $rtr->isi),25)."\n";
                        $tlretur += $rtr->qty * $rtr->isi;
            }    
            if($tlretur>0){
                $Data .=PrinterController::space(5).PrinterController::strKarakter("Total --->",20).
                        PrinterController::strKarakter($this->KonversiStock($prd->id, $retur),35)."\n\n";
            }        
        }                
        
        $Data .=PrinterController::space(15).PrinterController::strKarakter("-- Stock Akhir --->",20).
                        PrinterController::strKarakter($this->KonversiStock($prd->id, $rkp->stock_akhir),35)."\n\n";
                        
        $Data .= $grs."\n";
        
        $c_now = date('Y-m-d H:i:s', time());
        
        $Data .= $c_now." eof report \n";
        $Data .= $feed;

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

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

    public function reconsile($gdg){
        
        $stk = Stock::where('gudang_id', $gdg)->get();
        
        $tbeli=0; $tsale=0; $tretur=0; $mts_in=0; $mts_out=0; 
        
        
        foreach($stk as $st){
            /* pembelian   */
            $bl = DB::table('dt_invoice as A')
                            ->select('A.product')
                            ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                            ->leftjoin('ms_invocie as B', function($join){
                                    $join->on('A.inv_id', '=', 'B.id');
                                })
                            ->where('B.gudang_id', $gdg)
                            ->where('A.product_id', $st->product_id)
                            ->where('A.is_posted',1)                            
                            ->whereBetween('B.inv_tgl', [$st->tgl_awal, date('Y-m-d')])
                            ->groupBy('A.product_id')
                            ->get();
                            
            foreach($bl as $bb){ $tbeli += $bb->qty; }
            
            /* penjualan   */
            $sl = DB::table('dt_sale as A')
                            ->select('A.product')
                            ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                            ->leftjoin('ms_sale as B', function($join){
                                    $join->on('A.sale_id', '=', 'B.id');
                                })
                            ->where('B.gudang_id', $gdg)
                            ->where('A.product_id', $st->product_id)
                            ->where('A.is_posted',1)                            
                            ->whereBetween('B.sale_tgl', [$st->tgl_awal, date('Y-m-d')])
                            ->groupBy('A.product_id')
                            ->get();
                            
            foreach($sl as $ss){ $tsale += $ss->qty; }          
            
            /* retur   */
            $rt = DB::table('dt_retur as A')
                            ->select('A.product')
                            ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                            ->leftjoin('ms_retur as B', function($join){
                                    $join->on('A.rtr_id', '=', 'B.id');
                                })
                            ->where('A.gudang_id', $gdg)
                            ->where('A.product_id', $st->product_id)
                            ->where('A.is_posted',1)                            
                            ->whereBetween('B.rtr_tgl', [$st->tgl_awal, date('Y-m-d')])
                            ->groupBy('A.product_id')
                            ->get();
                            
            foreach($rt as $rr){ $tretur += $rr->qty; }            
            
            /* mutasi in   */
            $in = DB::table('dt_mutasi as A')
                            ->select('A.product')
                            ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                            ->leftjoin('ms_mutasi as B', function($join){
                                    $join->on('A.mts_id', '=', 'B.id');
                                })
                            ->where('B.mts_to', $gdg)
                            ->where('A.product_id', $st->product_id)
                            ->where('A.is_posted',1)                            
                            ->whereBetween('B.mts_tgl', [$st->tgl_awal, date('Y-m-d')])
                            ->groupBy('A.product_id')
                            ->get();
                            
            foreach($in as $ii){ $mts_in += $ii->qty; }            
            
            /* mutasi out   */
            $out = DB::table('dt_mutasi as A')
                            ->select('A.product')
                            ->addSelect(DB::raw('SUM(A.qty * A.isi) as qty'))
                            ->leftjoin('ms_mutasi as B', function($join){
                                    $join->on('A.mts_id', '=', 'B.id');
                                })
                            ->where('B.mts_from', $gdg)
                            ->where('A.product_id', $st->product_id)
                            ->where('A.is_posted',1)                            
                            ->whereBetween('B.mts_tgl', [$st->tgl_awal, date('Y-m-d')])
                            ->groupBy('A.product_id')
                            ->get();
                            
            foreach($out as $oo){ $mts_out += $oo->qty; }      
            
            /* rekap stock */
            $sisa = Stock::find($st->id);
            $sisa->stock_in     = $tbeli;
            $sisa->stock_sale   = $tsale;
            $sisa->stock_retur  = $tretur;
            $sisa->stock_mts_in = $mts_in;
            $sisa->stock_mts_out= $mts_out;
            $sisa->stock_akhir = $sisa->stock_awal + $tbeli - $tsale + $tretur + $mts_in - $mts_out;
            $sisa->update();
            
        }
        
        return json_encode(["msg"=>"success"]);
    }
    
    public function reportStock($gdg){
    
        $gudang = Gudang::find($gdg);
        
        $stk  = Stock::with('get_product', 'get_gudang')            
                        ->where('gudang_id', $gdg)
                        ->get();

     
        return view('stock.reportstock', compact('gudang', 'stk'));
        
    }
    
/***** adjustment stock -------------------*/

    public function simpanAdjust(Request $request){
        
        $stk = Stock::find($request['idadj']);
        $prd = Product::find($stk->product_id);
        
        //return json_encode(["msg"=>"success"]);
        
        $dt = new DTAdjust;
        $dt->adj_tgl    = date('Y-m-d');
        $dt->gudang_id  = $stk->gudang_id;
        $dt->product_id = $stk->product_id;
        $dt->nama_brg   = $prd->nama_brg;
        $dt->adj_qty    = $request['koreksi'];
        $dt->deskripsi  = $request['ket'];
        $dt->user_id    = Auth::user()->id;
        $dt->save();
        
        $stk->stock_adjust += $request['koreksi'];
        $stk->tgl_adjust    = date('Y-m-d');
        $stk->stock_akhir  += $request['koreksi'];
        $stk->update();

		$usrnm	= Auth::user()->username;
	
		$userlog = New User_logs;
		$userlog->title		= 'Ajustment Stock';
		$userlog->content	= 'Adjustment Stock '.$prd->kode_brg.'-'.$prd->nama_brg.' '.$request['koreksi'];
		$userlog->user_id	= Auth::user()->id;
		$userlog->save();         
        
        echo json_encode(["msg"=>"success"]);
    }

    
    public function historyAdjust(){
        return view('stock.historyadjust');
    }    
    
    public function dataAdjust(){
        
        $ad = DTAdjust::with('get_gudang','get_product')
                            ->get();
        
        $data=[];
        foreach($ad as $adj){
            
            $row=[];
            $row[]=$adj->get_gudang->kode;
            $row[]=tanggal_indonesia($adj->adj_tgl, false);
            $row[]=$adj->get_product->kode_brg;
            $row[]=$adj->get_product->nama_brg;
            $row[]='<div class="text-right">'.format_uang($adj->adj_qty).' PCS&nbsp;&nbsp;&nbsp;'.'</div>';
            $row[]=$adj->deskripsi;
            
            $data[]=$row;
        }
        
        return response()->json(["data"=>$data]);
    }
    
    
}
