<?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\Salesman;
use App\MSSale;
use App\DTSale;
use App\MSRetur;
use App\DTRetur;
use App\Product;
use App\ProductSub;
use App\Stock;
use App\Gudang;


class ReturController extends Controller
{
    
    public function index(){
        
        $cus = Customer::with('get_city')
                        ->orderBy('cus_name', "DESC")
                        ->get();
        
        $sls = Salesman::orderBy('sales_name', 'ASC')
                        ->get();
                        
        $prd = Product::orderBy('nama_brg', 'ASC')
                        ->get();
                        
        $kms = ProductSub::all();
        $gdg = Gudang::all();
        
        return view('retur.index', compact('cus','sls', 'prd', 'kms','gdg'));
    }
    
    public function dataretur(){
    
        $tgl = date('Y-m-d');
        
        $rtr = MSRetur::with('get_customer','get_sales')
                        ->where('is_posted',0)
                        ->get();
                        
        $data=[];
        foreach($rtr as $dt){
            
            $row=[];
            $row[] = $dt->rtr_no;
            $row[] = tanggal_indonesia($dt->rtr_tgl, false);
            $row[] = $dt->get_customer->cus_name;
            $row[] = $dt->get_sales->sales_name;
            $row[] = '<div style="text-align:right">'.format_uang($dt->rtr_netto).'</div>';
            
            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="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){

        $cust = Customer::find($request['cus']);
        $tgl = date('Y-m-d');

        $noinv = $this->cekNoRetur();
        
        $dt = new MSRetur;
        $dt->rtr_tgl   = date('Y-m-d');
        $dt->rtr_no    = $noinv;
        $dt->rtr_cust  = $request['cus'];
        $dt->sales_id   = $request['sls'];
        $dt->user_id    = Auth::user()->id;
        
        $dt->save();
        
	// insert logs
		$usrnm	= Auth::user()->username;
		
		$userlog = New User_logs;
		$userlog->title		= 'Retur Penjualan Baru';
		$userlog->content	= 'NO.Retur '.$noinv.' berhasil dibuat oleh '.$usrnm;
		$userlog->user_id	= Auth::user()->id;
		$userlog->save();

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

    public static function cekNoRetur(){
    	/* cek no terakhir */
		$noftr	= '';
		$tahun	= date('y');
		$bulan  = date('m');
		$nomor	="RTR/".$tahun.$bulan."/";		/* FTR/2205/0001*/
			
		$ada_no	= DB::table('ms_retur')
						->select(DB::raw('SUBSTR(MAX(rtr_no),10,4) as last_no'))
						->where('rtr_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 = MSRetur::find($id);
        $cus = Customer::find($dt->rtr_cust);
        
        echo json_encode(array_merge(json_decode($cus, true),json_decode($dt, true)));

    }

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

        $dt = MSRetur::find($id);
        $dt->sales_id   = $request['sls'];
        $dt->sale_ppn   = $ppn;
        $dt->sale_disc  = $request['dis'];
        $dt->user_id    = Auth::user()->id;
        
        $dt->update();
        

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

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

    public function dataDetail($id){
        
        $msl = MSRetur::find($id);
        $dsl = DTRetur::with('get_product', 'get_gudang')
                        ->where('rtr_id', $id)
                        ->get();
                        
        $data=[];
        $ttl=0;
        foreach($dsl as $dt){
            
            $jlh=($dt->qty * $dt->harga);
            $ttl+= $jlh;
            
            $row=[];
            $row[]=$dt->get_product->kode_brg;
            $row[]=$dt->get_product->nama_brg;
            $row[]=$dt->kemasan.'/'.$dt->isi;
            $row[]='<div style="text-align:right">'.format_uang($dt->harga).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            $row[]='<div style="text-align:right">'.$dt->qty.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            $row[]='<div style="text-align:right">'.format_uang($jlh).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            $row[]=$dt->get_gudang->nama;
            
            if($msl->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;
        }
        
        $row=[];
        $row[]="";
        $row[]="";
        $row[]="";
        $row[]="Sub Total";
        $row[]="";        
        $row[]='<div style="text-align:right">'.format_uang($ttl).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
        $row[]="";
        $row[]="";
            
        $data[]=$row;     
        
        return response()->json(["data"=>$data]);
    }
    
    public function listKemasan($id, $cus){
        $set = Setting::first();
        $kms = ProductSub::where('product_id', $id)
                            ->get();
        
        $cust = Customer::find($cus);
        
		$data = [];
		
		foreach($kms as $list){
		    
		    $hg=$list->harga;
		    if($cust->is_ppn==0){ $hg = $list->harga + ($list->harga*$set->ppn_value/100); }
		    
			$row = [];
			$row[] = $list->satuan ;
            $row[] = $list->volume ;
            $row[] = '<div style="text-align:right">'.format_uang($hg).'</div>' ;
			
  		    $row[] = '<div class="btn-btn">
						<a onclick="selectKemasan('.$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 tampilKemasan($id, $cus){
        $set = Setting::first();
        $cust = Customer::find($cus);
        $kms = ProductSub::find($id);

        $dt= $kms->satuan." / ".$kms->volume;
        $hg= $kms->harga;
        if($cust->is_ppn==0){ $hg = $kms->harga + ($kms->harga*$set->ppn_value/100); }
        
        echo json_encode(["kemasan"=>$dt, "harga"=>format_uang($hg)]);
    }

    public function loadSummary($id){
        
        $msl = MSRetur::find($id);
        $dt = DTRetur::where('rtr_id', $id)
                            ->get();
        $sub=0;
        foreach($dt as $list){
            $sub += ($list->qty * $list->harga);
        }
        
        $ttl = $sub;

        /* update total pada saat print faktur
        $msl->rtr_netto    = $ttl;
        $msl->update();
        */
        
        echo json_encode(["totalftr"=>format_uang($ttl)]);
    }	
    
    public function addDetail(Request $request){
        
        $idrtr = $request['idretur2'];       /* pada form add_detail */
        $idprd = $request['prd2'];
        $qty   = $request['qty'];
        $hg    = $request['harga'];
        
        $set = Setting::first();
        
        $mrtr= MSRetur::find($idrtr);
        $cust= Customer::find($mrtr->rtr_cust);
        $prd = Product::find($idprd);
        $sub = ProductSub::find($request['kms']);
        
        //$hg = $sub->harga;
        //if($cust->is_ppn==0){ $hg = $sub->harga + ($sub->harga*$set->ppn_value/100); }
        
        try{  
            $dt = new DTRetur;
            
            $dt->rtr_id         = $mrtr->id;
            $dt->product_id     = $prd->id;
            $dt->product_name   = $prd->nama_brg;
            $dt->sub_id         = $request['kms'];
            $dt->kemasan        = $sub->satuan;
            $dt->isi            = $sub->volume;
            $dt->harga          = $hg;
            $dt->gudang_id      = $request['gdg'];
            $dt->qty            = $qty;
            //$dt->notes          = $request['ket'];
            $dt->save();
            
            /*$this->updStock($prd->id, $qty * $sub->volume, $request['gdg']);*/
            $mode=1;
            StockController::OutstandingStock($request['gdg'], $prd->id, $qty*$sub->volume, $mode);
            
            echo json_encode(['msg'=>'success']);
        }
        catch (Exeption $e){
            return response (['status' => false,'errors' => $e->getMessage()]);
        }            
    }
    
    public function updStock($id, $qty, $gdg ){

        $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_retur    = $qty;
            $dt->tgl_retur      = date('Y-m-d');
            $dt->stock_akhir    = $qty;
            $dt->save();
        }else{
            
            $stk->stock_retur   += $qty;
            $stk->stock_akhir   += $qty;
            $stk->tgl_retur      = date('Y-m-d');
            $stk->update();
        }
        
        return true;
    }
    
    public function editDetail($id){
        
        $dt = DTRetur::find($id);
        echo json_encode($dt);
        
    }
    
    public function simpanEdit(Request $request, $id){
        
        $dt = DTRetur::find($id);
        $mrtr = MSRetur::find($dt->rtr_id);
        
        $dt->qty        = $request['qty'];
        $dt->harga      = $request['harga'];
        $dt->update();
        
        /*$this->updStock($dt->product_id, ($newqty-$oldqty), $msl->gudang_id);*/
        
        echo json_encode(['msg'=>'success']);
        
    }
    
    public function printFaktur($id){
        
        $mdt = MSRetur::find($id);
        $dt  = DTRetur::with('get_product')
                            ->where('rtr_id', $id)
                            ->get();  
                            
        $cus = Customer::find($mdt->rtr_cust);                    
        $sls = Salesman::find($mdt->sales_id);
        $area= Area::find($cus->cus_area);
                            
        $sub=0;
        foreach($dt as $list){
            $sub += ($list->qty * $list->harga);
        }
        
        $ppn = $sub * $mdt->rtr_ppn/100;
        $ttl = round($sub + $ppn);
        $mdt->rtr_netto = $ttl;
        $mdt->update();
        
        return view('retur.faktur', compact('mdt','dt','sub', 'ppn','ttl','sls','cus','area'));
    }
    
    public function posting(Request $request){
        
        $mdt = MSRetur::find($request['idretur']);
        
        if($mdt->rtr_netto==0){ return json_encode(["msg"=>"error1"]); }
        
        $dtl = DTRetur::where('rtr_id', $mdt->id)
                            ->where('is_posted', 0)
                            ->get();
                            
        foreach($dtl as $dt){
            $this->updStock($dt->product_id, ($dt->qty*$dt->isi), $dt->gudang_id);
            
            $mode=1;
            StockController::OutstandingStock($dt->gudang_id, $dt->product_id, ($dt->qty * $dt->isi)*-1, $mode);
            
            $dd = DTRetur::find($dt->id);
            $dd->is_posted = 1;
            $dd->update();
        }
        
        $mdt->is_posted=1;
        $mdt->update();
        
        echo json_encode(['msg'=>'success']);        
    }
    

/* print faktur printer dotmatrix */
    public function printFaktur_matrix($id){
        
        $mdt = MSRetur::find($id);
        $dt  = DTRetur::with('get_product')
                            ->where('rtr_id', $id)
                            ->get();  
                            
        $cus = Customer::find($mdt->rtr_cust);                    
        $sls = Salesman::find($mdt->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("RETUR PENJUALAN", $lebarkolom)."\n";
        $Data .= PrinterController::strKarakter(COMPANY,40).PrinterController::rataKanan("NO.Rektur: ".$mdt->rtr_no,40)."\n";
        $Data .= PrinterController::rataKanan(tanggal_indonesia($mdt->rtr_tgl, false),80)."\n";
        $Data .= PrinterController::strKarakter("Salesman: ".$sls->sales_name,35)."Outlet: ".$cus->cus_name."\n";
        $Data .= PrinterController::space(35).substr($cus->cus_address,0,45)."\n";
        $Data .= PrinterController::space(35)."Area :".$area->area_name."\n";

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

        /*        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  99,999,999*/
        $Data .= "KODE  Nama Barang                              --QTY--     Harga      Jumlah\n";
        $Data .= $grs."\n";
        
        $no = 0;
        $ttl = 0;
        
        foreach($dt as $dtl){
            $no++;
            $jlh = ($dtl->qty * $dtl->harga); 
            $ttl += $jlh;
            
            $kd = $condensed1.PrinterController::strKarakter($dtl->get_product->kode_brg,8).$condensed0;
            $nm = PrinterController::strKarakter(substr($dtl->product_name,0,40),40);
            $qq = PrinterController::rataKanan(format_uang($dtl->qty),4).substr($dtl->kemasan,0,3);
            $hg = PrinterController::strAngka($dtl->harga,9);
            

            $jl = PrinterController::strAngka($jlh,10);
            
            $Data .=$kd." ".$nm." ".$qq." ".$hg." ".$jl."\n";
        }
        
        $Data .= $grs."\n";

        $Data .= PrinterController::space(55)."# TOTAL # ".PrinterController::strAngka($ttl,10)."\n";
        $Data .= $condensed1.terbilang(round($ttl))." rupiah# \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);

    }
    
    
/* history */
    function index_history(){
        return view('retur.history');
    }
    
    public function history(){

        
        $rtr = MSRetur::with('get_customer','get_sales')
                        ->where('is_posted',1)
                        ->orderby('rtr_no', 'DESC')
                        ->get();
                        
        $data=[];
        foreach($rtr as $dt){
            
            $row=[];
            $row[] = $dt->rtr_no;
            $row[] = tanggal_indonesia($dt->rtr_tgl, false);
            $row[] = $dt->get_customer->cus_name;
            $row[] = $dt->get_sales->sales_name;
            $row[] = '<div style="text-align:right">'.format_uang($dt->rtr_netto).'</div>';
	        $row[] = '<div class="btn-btn">
			                <a onclick="showDetail('.$dt->id.')" class="btn btn-success btn-sm"><i class="fa fa-list"></i></a>
				        </div>';

            $data[]=$row;
        }
        
        return response()->json(["data"=>$data]);
        
    }
    
        public function historyDetail($id){
        
        $msl = MSRetur::find($id);
        $dsl = DTRetur::with('get_product', 'get_gudang')
                        ->where('rtr_id', $id)
                        ->get();
                        
        $data=[];
        $ttl=0;
        foreach($dsl as $dt){
            
            $jlh=($dt->qty * $dt->harga);
            $ttl+= $jlh;
            
            $row=[];
            $row[]=$dt->get_product->kode_brg;
            $row[]=$dt->get_product->nama_brg;
            $row[]=$dt->kemasan.'/'.$dt->isi;
            $row[]='<div style="text-align:right">'.format_uang($dt->harga).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            $row[]='<div style="text-align:right">'.$dt->qty.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            $row[]='<div style="text-align:right">'.format_uang($jlh).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            $row[]=$dt->get_gudang->nama;
            $row[]="";
            
            $data[]=$row;
        }
        
        $row=[];
        $row[]="";
        $row[]="";
        $row[]="";
        $row[]="Sub Total";
        $row[]="";        
        $row[]='<div style="text-align:right">'.format_uang($ttl).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
        $row[]="";
        $row[]="";
            
        $data[]=$row;     
        
        return response()->json(["data"=>$data]);
    }
    
    
}
