<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;
use App\Cabang;
use App\Stock;
use App\Transfer;
use App\TransferDetail;
use App\User_logs;
use Datatables;
use DB;
use Auth;
Use Redirect;

class TransferController extends Controller
{

	public function index()
	{		
		$cabang = Cabang::where('id_cbg', '<>', Auth::user()->store_id)->get();
		
		return view('transfer.index', compact('cabang'));
	}
	
    function getheader()
    {
		$tglnow = date("Y-m-d");

     	$transfer = Transfer::leftjoin('ms_cabang', 'ms_transfer.to_id','=','ms_cabang.id_cbg')
								->where('ms_transfer.from_id', '=', Auth::user()->store_id)
								->where('ms_transfer.trf_posted',0)
								->where('ms_transfer.trf_batal',0)
								->orderBy('ms_transfer.from_id','ASC')
								->orderby('ms_transfer.trf_no','ASC')->get();
		
		$no=1;
		$data = array();
		
		foreach($transfer as $list)
		{
			$row = array();
				   
			$row[] = $no++;
			$row[] = $list->trf_no;
			$row[] = tanggal_indonesia($list->trf_tgl, false);
			$row[] = $list->cbg_name;
			
			$sss = $list->trf_posted;
			$sts="";
				switch ($sss){
					case '0': $sts = 'Blm diterima'; break;
					case '1': $sts = 'Posted'; break;}

			$row[] = $sts;
		    $row[] = '<div class="btn-btn">
				   <a href="transfer/'.$list->id_transfer.'/input" class="btn btn-success btn-sm"><i class="fa fa-plus"> detail </i></a>
				   </div>';	

		   $data[] = $row;
		}

		$output = array("data" => $data);
		return response()->json($output);								
			
    }

///-- create new invoice
	public function store(Request $request)
	{
		$notrf  = "";
		$tahun	= date('Y');
		$bulan  = date('m');
		$nomor	= "TRF/".$tahun.$bulan."/";		
		$ada_no	= DB::table('ms_transfer')
					->select(DB::raw('SUBSTR(MAX(trf_no),12,4) as last_no'))
					->where('trf_no', 'LIKE', "$nomor%" )->get();
							
		$jml	= $ada_no->count();
			
		if ($jml >0)
		{
			foreach( $ada_no as $ada ){	$no	= $ada->last_no; }
			$no1	= $no + 1;
				
			$nomorbaru 	= sprintf("%04s", $no1);		//format: JMP/2019/00001
			$notrf = $nomor.$nomorbaru;
			
		} else {
			$nomorbaru = "0001";
			$notrf = $nomor.$nomorbaru;
		}
			
		$idcbg		= $request['cbg'];
		$tgltrf		= $request['tgltrf'];
		
		$cabang	= Cabang::find($idcbg);
	
		$transfer	= New Transfer;
		$transfer->trf_no	= $notrf;
		$transfer->from_id	= Auth::user()->store_id;
		$transfer->to_id	= $idcbg;
		$transfer->trf_tgl	= $tgltrf;
		$transfer->user_id	= Auth::user()->id;
		
		$transfer->save();

	// insert logs
			$usrnm	= Auth::user()->username;
			
			$userlog = New User_logs;
			$userlog->title		= 'Transfer ke Cabang';
			$userlog->content	= 'Transfer ke '.$cabang->cbg_name.' berhasil dicreate oleh '.$usrnm;
			$userlog->user_id	= Auth::user()->id;
			$userlog->save();

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

//-------------------------------
	function input($id)
	{
		session(['idtrf'=>$id]);
		
		$idtrf	    = $id;
		$transfer	= Transfer::where('id_transfer',$id)->get();
		
		foreach($transfer as $list)
		{
			$idfrom	= $list->from_id;
			$idto	= $list->to_id;
			$notrf	= $list->trf_no;
			$posted	= $list->trf_posted;
		}
		
		if($posted==1)
		{
			//return Redirect::route('invoice.index');	
			$cabang = Cabang::where('id_cbg', '<>', Auth::user()->store_id)->get();
			return view('transfer.index', compact('cabang'));
		}else{
		
    		$no=1;
    		$m_trf		= Transfer::find($idtrf);
    		$cabang		= Cabang::find($idto);
 			$dtstock	= Stock::leftJoin('ms_product', 'dt_stock.product_id', 'ms_product.id')
									->where('dt_stock.cabang_id','=', Auth::user()->store_id)
									->where('dt_stock.stock_akhir', '>', 0)
									->get();
    
    		return view('transfer_detail.index', compact('m_trf','cabang','dtstock','idtrf','no'));
		}
	
	} 

/*-----------------------------------------------------*/
	function tampil($id)
	{
		session(['idinv'=>$id]);
		
		$idinv	    = $id;
		$invoice	= Invoice::where('id_invoice',$id)->get();
		
		foreach($invoice as $list)
		{
			$idsupp	= $list->supp_id;
			$noinv	= $list->inv_no;
			$ppn	= $list->inv_ppn;
			$disc1	= $list->inv_disc;
			$posted	= $list->inv_posted;
		}
		
		$no=1;
		$m_inv		= Invoice::find($id);
		$supplier	= Supplier::find($idsupp);
		$product	= Product::where('supplier',$idsupp)
    								->orderBy('nama_brg','ASC')->get();
    	
    
		return view('invoice_detail.index_history', compact('m_inv','supplier','product','idinv','no'));

	} 
/*-----------------------------------------------------*/
    public function edit($id)
    {
      $produk = Product::find($id);
      echo json_encode($produk);
    }
    
/* 
    public function show($id)
    {
        
    }
*/

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

	/* posting invoice ke stock & cetak invoice */
	
    public function update($id)
    {

		$invoice 	= Invoice::find($id);
		$spc		= $invoice->inv_disc;
		$ppn		= $invoice->inv_ppn;
		$noinv      = $invoice->inv_no;
		
		$dtinv  	= InvoiceDetail::where('invoice_id', $id )->get();

		$totalinv1	= 0;
		$totalinv2	= 0;
		$totalinv	= 0;
		$disc1	 	= 0;
		$disc2		= 0;
		$disc3		= 0;
		$total_net	= 0;
		$pokok      = 0;
		
		foreach($dtinv as $list){
            
            $id_detail  = $list->id_inv;
            $idbrg  = $list->id_brg;
            $noseri = $list->no_seri;
            $tglinv = $list->inv_tgl;
            $qty    = $list->inv_qty;
            $posted = $list->inv_posted;
            
			$pokok1  = jumlahINV($list->inv_gross, $list->inv_disc1, $list->inv_qty) ;
			$pokok2  = $pokok1 - ($pokok1 * $spc/100);
			$pokok3  = $pokok2 + ( $pokok2 * $ppn/100);
			$pokok   = $pokok3 / $qty;         
			
			$totalinv1 += $list->inv_gross * $list->inv_qty;
			
			$disc1	= $totalinv1 * $list->inv_disc1 /100;
		//	$disc2	= ($totalinv1 - $disc1) * $list->inv_disc2 /100;
		//	$disc3	= ($totalinv1 - $disc1 - $disc2) * $list->inv_disc3 /100;
			
			$totalinv = $totalinv1 - $disc1 - $disc2 - $disc3;
			

			
			/* posting stock */
			$data_stock  = Stock::where('cabang_id',0)
			                    ->where('product_id', $idbrg)
			                    ->where('no_seri', $noseri)
			                    ->get();
			                    
			$ada_stock   = $data_stock->count();
			 
			 if ($ada_stock==0)
			 {
			     if ($posted==0){
    			     /* insert stock */
    			     $stock = New Stock;
    			     $stock->cabang_id      = 0;    //default gudang pusat
    			     $stock->product_id     = $idbrg;
    			     $stock->no_seri        = $noseri;
    			     $stock->barang_masuk   = $qty;
    			     $stock->tgl_masuk      = $tglinv;
    			     $stock->stock_akhir    = $qty;
    			     $stock->user_id        = Auth::user()->id;
			     
			         $stock->save();
			     }
			     
			 }else{
			     
			     if ($posted==0){			     
    			     /*update stock */
    			     foreach ($data_stock as $dtstock)
    			     { 
    			        $stkakhir   = $dtstock->stock_akhir;
    			        $idstock    = $dtstock->id_stock; 
    			        $masuk      = $dtstock->barang_masuk;
    			     }
    			     
    			     $data_stock->barang_masuk  = $masuk + $qty;
    			     $data_stock->tgl_masuk     = $tglinv;
    			     $data_stock->stock_akhir   = $stkakhir + $qty;
    			     
			        $data_stock->update();
			     } 
			 }

            /*update status posted inv detail */
            $det_inv = InvoiceDetail::find($id_detail);
            $det_inv->inv_posted = 1;
            $det_inv->inv_pokok  = $pokok;
            $det_inv->update();
            
 		 }
		 
		 $disc_spc 	= $totalinv * $spc/ 100;
		 $totalinv2	= $totalinv - $disc_spc;
		 $total_net	= $totalinv2 + ($totalinv2 * $ppn /100);
		 
		 /* update ms_transfer */
		 
		 $invoice->inv_total	= $total_net;
		 $invoice->inv_posted   = 1;
		 $invoice->update();

// insert logs
		$usrnm	= Auth::user()->username;
		$userlog = New User_logs;
		$userlog->title		= 'Posting Invoice';
		$userlog->content	= 'Inovice No. '.$noinv.' berhasil diposting oleh '.$usrnm;
		$userlog->user_id	= Auth::user()->id;
		$userlog->save();		

 		return Redirect::route('invoicedetail.cetak');					//cetak invoice
    }

/* reprint inv */
    public function printform($id)
    {
		$mtrf	= Transfer::find($id);
		$dtrf	= TransferDetail::leftjoin('ms_product', 'dt_transfer.product_id', 'ms_product.id')
									->where('dt_transfer.transfer_id', $id)->get();
					
		$cabang	= Cabang::find($mtrf->to_id);
		$no=1;
		$totalqty=10;
		//return Redirect::route('transferdetail.print');				//cetak po
		return view('transfer_detail.cetak', compact('mtrf', 'dtrf', 'cabang', 'no', 'totalqty'));
    }
	
/*=====================================================*/
/* untuk terima barang */

	function index_terima(){
		return view('terimadata.index');
	}
	
    function dataterima()
    {
		$tglnow = date("Y-m-d");

     	$terima = Transfer::where('ms_transfer.to_id', '=', Auth::user()->store_id)
								->where('ms_transfer.trf_posted',0)
								->where('ms_transfer.trf_batal',0)
								->orderby('ms_transfer.trf_no','ASC')->get();
		
		$no=1;
		$data = array();
		
		foreach($terima as $list)
		{
			$row = array();
				   
			$row[] = $no++;
			$row[] = $list->trf_no;
			$row[] = tanggal_indonesia($list->trf_tgl, false);
			$row[] = self::namaCabang($list->from_id)->cbg_name;
		    $row[] = '<div class="btn-btn">
				   <a href="/sbo/transfer/'.$list->id_transfer.'/terima" class="btn btn-success btn-md"><i class="fa fa-check"> detail </i></a>
				   </div>';	

		   $data[] = $row;
		}

		$output = array("data" => $data);
		return response()->json($output);								
    }
	
	function terima($id)
	{
		session(['idtrf'=>$id]);
		
		$idtrf	    = $id;
		$transfer	= Transfer::where('id_transfer',$id)->get();
		
		foreach($transfer as $list)
		{
			$idfrom	= $list->from_id;
			$idto	= $list->to_id;
			$notrf	= $list->trf_no;
			$posted	= $list->trf_posted;
		}
		
    	$no=1;
    	$m_trf		= Transfer::find($idtrf);
    	$cabang		= Cabang::find($idfrom);
 		$dttrf		= TransferDetail::leftJoin('ms_product', 'dt_transfer.product_id', 'ms_product.id')
									->where('dt_transfer.transfer_id','=', $idtrf)
									->get();
    
    	return view('terimadata.terima_detail', compact('m_trf','cabang','dttrf','idtrf','no'));
		
	
	} 

/* posting stock */
	/* posting opname ke stock & cetak opname */
	
    public function updatestock($id)
    {

		$mtrf    	= Transfer::find($id);
        $tgltrf     = $mtrf->trf_tgl;
        $idfrom     = $mtrf->from_id;
		$idto		= $mtrf->to_id;
        $cabang     = Cabang::find($idto);
        
		$dtrf 	 	= TransferDetail::where('transfer_id', $id )
		                                ->where('trf_posted', 0)
		                                ->get();

    /* proses posting stock  kurangi stock asal(from_id) dan tambah stock tujuan(to_id) */
		foreach($dtrf as $list) 
        {
            $id_detail  = $list->id_trf;
            $qty        = $list->trf_qty;
            $idbrg      = $list->product_id;
            $noseri     = $list->no_seri;
            
			$data_stock  = Stock::where('cabang_id', $idfrom)
			                    ->where('product_id', $idbrg)
			                    ->where('no_seri', $noseri)
			                    ->get();

			/* update stock asal (dikurangi) */			
			foreach ($data_stock as $dtstock)
			{  $idstock    = $dtstock->id_stock; }
			   			     
  			    $datastock  = Stock::find($idstock);
				$stk_old	= $datastock->stock_akhir;
				$out_old	= $datastock->trf_out;
				    			     
    			$datastock->trf_out       = $out_old + $qty;
    			$datastock->tgl_trout     = $tgltrf;
    			$datastock->stock_akhir   = $stk_old - $qty;
    			$datastock->user_id       = Auth::user()->id;
			    
		        $datastock->update();

			/* update stock tujuan */
			$stock_tuju  = Stock::where('cabang_id', $idto)
			                   ->where('product_id', $idbrg)
			                   ->where('no_seri', $noseri)
			                   ->get();
				
		
			$ada_stock   = $stock_tuju->count();

			if ($ada_stock==0)
			{
				/* insert stock */
				 $stock = New Stock;
				 $stock->cabang_id      = $idto;    
				 $stock->product_id     = $idbrg;
				 $stock->no_seri        = $noseri;
				 $stock->trf_in     	= $qty;
				 $stock->tgl_trin       = $tgltrf;
				 $stock->stock_akhir    = $qty;
				 $stock->user_id        = Auth::user()->id;
				 
				 $stock->save();

			 }else{
			     
				foreach ($stock_tuju as $stk_tuju)
				{ $idstock   = $stk_tuju->id_stock; }
			        
   			    $dtstock  	= Stock::find($idstock);
				$stk_old	= $dtstock->stock_akhir;
				$in_old		= $dtstock->trf_in;
				    			     
    			$dtstock->trf_in        = $in_old + $qty;
    			$dtstock->tgl_trin	    = $tgltrf;
    			$dtstock->stock_akhir   = $stk_old + $qty;
    			$dtstock->user_id       = Auth::user()->id;
			    
		        $dtstock->update();
			         
		     } 

            /*update status posted opn detail */
            $det_trf = TransferDetail::find($id_detail);
            $det_trf->trf_posted = 1;
            
            $det_trf->update();
            
		 }
		 
		 /* update ms_transfer */
		 
		 $mtrf->trf_posted   = 1;
		 $mtrf->update();

// insert logs
		$usrnm	= Auth::user()->username;
		$userlog = New User_logs;
		$userlog->title		= 'Posting Transfer Barang';
		$userlog->content	= 'Posting Transfer '.$mtrf->trf_no.' berhasil diposting oleh '.$usrnm;
		$userlog->user_id	= Auth::user()->id;
		$userlog->save();		

 		//return Redirect::route('stockopnamedetail.cetak');					//cetak invoice
 		return Redirect::route('home');
    }
	
/*------------------------------------------------------*/
	static function namaCabang($id){
		return Cabang::find($id);
	}
	
	
/* history */
//-------------------------------
	public function history()
	{		
		$cabang = Cabang::all();
		
		return view('transfer.history', compact('cabang'));
	}	

/*------------------------------------------------------*/
    function history_header()
    {

      	$transfer = Transfer::leftjoin('ms_cabang', 'ms_transfer.to_id','=','ms_cabang.id_cbg')
								->where('ms_transfer.from_id', '=', Auth::user()->store_id)
								->where('ms_transfer.trf_posted',1)
								->orderby('ms_transfer.trf_no','ASC')->get();
		
		$no=1;
		$data = array();
		
		foreach($transfer as $list)
		{
			$row = array();
				   
			$row[] = $no++;
			$row[] = $list->trf_no;
			$row[] = tanggal_indonesia($list->trf_tgl, false);
			$row[] = $list->cbg_name;
			
			$sss = $list->trf_posted;
			$sts="";
				switch ($sss){
					case '0': $sts = 'Blm diterima'; break;
					case '1': $sts = 'Posted'; break;}

			$row[] = $sts;
		    $row[] = '<div class="btn-btn">
				   <a href="/sbo/transfer/'.$list->id_transfer.'/detail_history" class="btn btn-success btn-sm"><i class="fa fa-check"> detail </i></a>
				   </div>';	

		   $data[] = $row;
		}

		$output = array("data" => $data);
		return response()->json($output);								
			
    }


//------------------------------history detail

	function detail_history($id)
	{
		session(['idtrf'=>$id]);
		
		$idtrf	    = $id;
		$transfer	= Transfer::where('id_transfer',$id)->get();
		
		foreach($transfer as $list)
		{
			$idfrom	= $list->from_id;
			$idto	= $list->to_id;
			$notrf	= $list->trf_no;
			$posted	= $list->trf_posted;
		}
		
	
    		$no=1;
    		$m_trf		= Transfer::find($idtrf);
    		$cabang		= Cabang::find($idto);
 
    		return view('transfer_detail.history', compact('m_trf','cabang','idtrf','no'));
		
	
	} 
	
}
