<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;
use App\ProductSub;
use App\Stock;
use App\Gudang;
use App\MSMutasi;
use App\DTMutasi;
use App\User_logs;
use DataTables;
use DB;
use Auth;
Use Redirect;

class MutasiController extends Controller
{

	public function index()
	{		
		$gdg = Gudang::all();
        $prd = Product::all();
        
		return view('mutasi.index', compact('gdg','prd'));
	}
	

    function getheader()
    {
		$tglnow = date("Y-m-d");

		$mts = MSMutasi::with('get_gudangasal', 'get_gudangtuju')
		                   	->where('is_posted',0)
							->orderby('mts_no','ASC')
							->get();
		
		$data = [];
		
		foreach($mts as $list)
		{
			$row = [];

			$row[] = $list->mts_no;
			$row[] = tanggal_indonesia($list->mts_tgl, false);
			$row[] = $list->get_gudangasal->nama;
			$row[] = $list->get_gudangtuju->nama;			
            $row[] = $list->deskripsi;
			if($list->is_posted==1){
			    $row[]="";
			}else{
		        $row[] = '<div class="btn-btn">
				                <a onclick="addDetail('.$list->id.')" class="btn btn-success btn-sm"><i class="fa fa-plus"></i></a>
				                
				            </div>';	
			}

		   $data[] = $row;
		}

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

///-- create new invoice
	public function store(Request $request)
	{

        $asal =$request['asal'];
        $tuju =$request['tuju'];
        
        if($asal==$tuju){ return json_encode(['msg'=>'error']); }
        
        $nomts = $this->cekNoMutasi();
        
        $dt= new MSMutasi;
        $dt->mts_tgl    = date('Y-m-d');
        $dt->mts_no     = $nomts;
        $dt->mts_from   = $asal;
        $dt->mts_to     = $tuju;
        $dt->deskripsi  = $request['ket'];
        $dt->user_id    = Auth::user()->id;
        $dt->save();
        
	// insert logs
			$usrnm	= Auth::user()->username;
			
			$userlog = New User_logs;
			$userlog->title		= 'Mutasi Stock';
			$userlog->content	= 'No.'.$nomts.'  berhasil dicreate oleh '.$usrnm;
			$userlog->user_id	= Auth::user()->id;
			$userlog->save();

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

    public static function cekNoMutasi(){
    	/* cek no terakhir */
		$noftr	= '';
		$tahun	= date('y');
		$bulan  = date('m');
		$nomor	="MTS/".$tahun.$bulan."/";		/* FTR/2205/0001*/
			
		$ada_no	= DB::table('ms_mutasi')
						->select(DB::raw('SUBSTR(MAX(mts_no),10,4) as last_no'))
						->where('mts_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 update(Request $request, $id){
	    
	    $dis    = $request['dis'];
	    $ppn    = $request['ppn'];
	    
	    $inv = Invoice::find($id);	 
	    
        $dtl = InvoiceDetail::where('inv_id', $id)
                            ->get();
        $sub=0;
        foreach($dtl as $list){
            $sub += ($list->qty * $list->harga)-($list->qty * $list->harga * $list->disc_1/100);
        }
        
        $disc = $sub * $dis /100;
        $ppn2 = ($sub - $disc) * $ppn/100;
        $ttl = $sub - $disc + $ppn2;
        
	    $inv->inv_no        = $request['inv'];
	    $inv->inv_tgl       = $request['tglinv'];
	    $inv->inv_jt        = $request['tgljt'];
	    $inv->inv_disc      = $dis;
	    $inv->inv_ppn       = $ppn;
        $inv->inv_brutto    = $sub;
        $inv->inv_netto     = $ttl;	    
	    $inv->update();	            
	    
	    echo json_encode(['msg'=>'success']);
	    
	}
	
    public function edit($id)
    {
      $dt = MSMutasi::find($id);
      $asal = Gudang::find($dt->mts_from);
      $tuju = Gudang::find($dt->mts_to);
      
      echo json_encode(["id"=>$dt->id,"nomutasi"=>$dt->mts_no, "asal"=>$asal->nama, "tuju"=>$tuju->nama]);
      
      //echo json_encode(array_merge(json_decode($asal, true), json_decode($tuju, true), json_decode($dt, true)));
    }
    
    public function show($id){
        $dt = MSMutasi::find($id);
        echo json_encode($dt);
    }

    public function dataDetail($id){
        
        $mts = MSMutasi::find($id);
        $dtl = DTMutasi::with('get_product')
                        ->where('mts_id', $id)
                        ->get();
                        
        $data=[];
        $ttl=0;
        foreach($dtl as $dt){
            
            $jlh=($dt->qty * $dt->harga)-($dt->qty * $dt->harga * $dt->disc_1/100);
            $ttl+= $jlh;
            
            $row=[];
            $row[]=$dt->get_product->kode_brg;
            $row[]=$dt->get_product->nama_brg;
            $row[]=$dt->satuan.'/'.$dt->isi;
            $row[]='<div style="text-align:right">'.$dt->qty.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';            
            $row[]='<div style="text-align:right">'.format_uang($dt->harga).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            $row[]='<div style="text-align:right">'.format_uang($jlh).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            
            if($mts->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[]="";
            
        $data[]=$row;     
        
        return response()->json(["data"=>$data]);
    }	
    
    public function loadSummary($id){
        
        $inv = Invoice::find($id);
        $dtl = InvoiceDetail::where('inv_id', $id)
                            ->get();
        $sub=0;
        foreach($dtl as $list){
            $sub += ($list->qty * $list->harga)-($list->qty * $list->harga * $list->disc_1/100);
        }
        
        $dis = $sub * $inv->inv_disc /100;
        $ppn = ($sub - $dis) * $inv->inv_ppn/100;
        $ttl = $sub - $dis + $ppn;
        
        $inv->inv_brutto   = $sub;
        $inv->inv_netto    = $ttl;
        $inv->update();
        
        echo json_encode(["totalftr"=>format_uang($ttl)]);
    }	

    public function listProduk($id){
        
        $prd = DB::table('ms_product as A')
                    ->select('B.id','A.kode_brg', 'A.nama_brg', 'B.satuan', 'B.volume', 'B.hpp')
                    ->leftjoin('product_sub as B', function($join){
                            $join->on('A.id', '=', 'B.product_id');  
                        })
                    ->where('A.supp_id', $id)
                    ->where('B.is_invoice','=',1)
                    ->get();


		$data = [];
		
		foreach($prd as $list){
			$row = [];
			$row[] = $list->kode_brg;
			$row[] = $list->nama_brg;
			$row[] = $list->satuan.'/'.$list->volume ;
            $row[] = '<div style="text-align:right">'.format_uang($list->hpp).'</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 tampilKemasan($id){
        
        $kms = ProductSub::find($id);
        $prd = Product::find($kms->product_id);
        $dt = $kms->satuan." / ".$kms->volume;
        $brg= $prd->kode_brg.' - '.$prd->nama_brg;
        
        echo json_encode(["kemasan"=>$dt, "harga"=>format_uang($kms->hpp), "namaprd"=>$brg]);
    }
    
    public function listKemasan($id){

        $kms = ProductSub::where('product_id', $id)
                            ->get();

		$data = [];
		
		foreach($kms as $list){
		    
		    $hg=$list->harga;

			$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 addDetail(Request $request){

        $idmts = $request['idmts2'];       /* pada form add_detail */
        $qty   = $request['qty'];
        
        $mts = MSMutasi::find($idmts);
        $sub = ProductSub::find($request['kms']);
        $prd = Product::find($sub->product_id);
        
        $qmutasi = $qty * $sub->volume;
        $sisastock = StockController::cekStock($mts->mts_from, $prd->id);
        if($sisastock < $qmutasi){ return json_encode(["msg"=>"error1"]); }        
        
        try{    
            $dt = new DTMutasi;
            $dt->mts_id         = $mts->id;
            $dt->product_id     = $prd->id;
            $dt->sub_id         = $sub->id;
            $dt->product_name   = $prd->nama_brg;
            $dt->satuan         = $sub->satuan;
            $dt->isi            = $sub->volume;
            $dt->harga          = $sub->hpp;
            $dt->qty            = $qty;
            $dt->save();
            
            /* update stock pada saat posting */
            //$this->updStock($mts->mts_from, $mts->mts_to, $prd->id, $qty * $sub->volume);
            
            $mode=2;
            StockController::OutstandingStock($mts->mts_from, $prd->id, $qty* $sub->volume, $mode);

            $mode=1;
            StockController::OutstandingStock($mts->mts_to, $prd->id, $qty* $sub->volume, $mode);            

            
            echo json_encode(['msg'=>'success']);
        }
        catch (Exeption $e){
            return response (['status' => false,'errors' => $e->getMessage()]);
        }
    }
    
    public function updStock($from, $to, $id, $qty ){
   
    /* update stock asal, dikurangi */     
        $stk = Stock::where('product_id', $id)
                        ->where('gudang_id', $from)
                        ->first();
                        
        
        if(empty($stk)){
            /* jika tidak ada stock, ditolak */
            return json_encode(['msg'=>'error1']);
        }else{
            
            $stk->stock_mts_out  += $qty;
            $stk->stock_akhir    -= $qty;
            $stk->tgl_mts_out     = date('Y-m-d');
            $stk->update();
            
            /*update stock tujuan */
            $stk1 = Stock::where('product_id', $id)
                        ->where('gudang_id', $to)
                        ->first();
            
            if(empty($stk1)){
                $dt = new Stock;
                $dt->gudang_id      = $to;
                $dt->product_id     = $id;
                $dt->stock_mts_in   = $qty;
                $dt->stock_akhir    = $qty;
                $dt->tgl_mts_in     = date('Y-m-d');
                $dt->save();
            }else{
                
                $stk1->stock_mts_in  += $qty;
                $stk1->stock_akhir   += $qty;
                $stk1->tgl_mts_in    = date('Y-m-d');
                $stk1->update();
            }
        }
        
        return true;
    }
    
    public function editDetail($id){
        
        $dt = DTMutasi::find($id);
        echo json_encode($dt);
        
    }
    
    public function simpanEdit(Request $request, $id){
        
        $sub = ProductSub::find($request['kms']);
        
        $dt = DTMutasi::find($id);
        $mts= MSMutasi::find($dt->mts_id);
        
        $qty    = $request['qty'];
        $oldqty = $dt->qty * $dt->isi;
        $newqty = $qty * $sub->volume;

        $dt->sub_id         = $sub->id;
        $dt->satuan         = $sub->satuan;
        $dt->isi            = $sub->volume;
        $dt->harga          = $sub->hpp;
        $dt->qty            = $qty;        
        $dt->update();
        
        /*update stock pada saat posting */
        //$this->updStock($mts->mts_from, $mts->mts_to, $prd->id, $newqty - $oldqty);
        
        $mode=2;
        StockController::OutstandingStock($mts->mts_from, $dt->product_id, ($newqty-$oldqty), $mode);

        $mode=1;
        StockController::OutstandingStock($mts->mts_to, $dt->product_id, ($newqty-$oldqty), $mode);            
        
        
        echo json_encode(['msg'=>'success']);
        
    }
    
    public function posting(Request $request){
        
        $mts = MSMutasi::find($request['idmts']);        
        $dt = DTMutasi::where('mts_id', $mts->id)
                            ->where('is_posted', 0)
                            ->get();
        
        foreach($dt as $list){
            
            $this->updStock($mts->mts_from, $mts->mts_to, $list->product_id, $list->qty * $list->isi);
            
            $mode=2;
            StockController::OutstandingStock($mts->mts_from, $list->product_id, ($list->qty* $list->isi)*-1, $mode);

            $mode=1;
            StockController::OutstandingStock($mts->mts_to, $list->product_id, ($list->qty* $list->isi)*-1, $mode);            
            
            
            /* update status posting */
            $pp = DTMutasi::find($list->id);
            $pp->is_posted = 1;
            $pp->update();
            
        }
        

        $mts->is_posted=1;
        $mts->update();
        
        echo json_encode(['msg'=>'success']);
    }
    
    public function printFaktur($id){
        
        $mts = MSMutasi::find($id);
        $dt  = DTMutasi::with('get_product')
                                ->where('mts_id', $id)
                                ->get();  
                            
        $asal = Gudang::find($mts->mts_from);
        $tuju = Gudang::find($mts->mts_to);                    

        $sub=0;
        foreach($dt as $list){
            $sub += ($list->qty * $list->harga);
        }
        
        $ttl = $sub;
        
        return view('mutasi.faktur', compact('mts','dt','ttl', 'asal','tuju'));
    }
    
/*------------------------------------------------------*/

    function index_history(){
        return view('mutasi.history');
    }
    
    function history(){
        
		$mts = MSMutasi::with('get_gudangasal', 'get_gudangtuju')
		                   	->where('is_posted',1)
							->orderby('mts_no','ASC')
							->get();
		
		$data = [];
		
		foreach($mts as $list)
		{
			$row = [];

			$row[] = $list->mts_no;
			$row[] = tanggal_indonesia($list->mts_tgl, false);
			$row[] = $list->get_gudangasal->nama;
			$row[] = $list->get_gudangtuju->nama;			
            $row[] = $list->deskripsi;
	        $row[] = '<div class="btn-btn">
			                <a onclick="showDetail('.$list->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){
        
        $mts = MSMutasi::find($id);
        $dtl = DTMutasi::with('get_product')
                        ->where('mts_id', $id)
                        ->get();
                        
        $data=[];
        $ttl=0;
        foreach($dtl as $dt){
            
            $jlh=($dt->qty * $dt->harga)-($dt->qty * $dt->harga * $dt->disc_1/100);
            $ttl+= $jlh;
            
            $row=[];
            $row[]=$dt->get_product->kode_brg;
            $row[]=$dt->get_product->nama_brg;
            $row[]=$dt->satuan.'/'.$dt->isi;
            $row[]='<div style="text-align:right">'.$dt->qty.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';            
            $row[]='<div style="text-align:right">'.format_uang($dt->harga).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            $row[]='<div style="text-align:right">'.format_uang($jlh).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
            $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[]="";
            
        $data[]=$row;     
        
        return response()->json(["data"=>$data]);
    }	


/////////////////////////////////////////////////////////////////////////


/* reprint inv */
    public function reprint($id)
    {
		session(['idinv'=>$id]);
		return Redirect::route('invoicedetail.reprint');				//cetak po
    }

	
}
