<?php

namespace App\Http\Controllers\master;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Yajra\Datatables\Datatables;
use Illuminate\Support\Facades\Session;

class SatuanController extends Controller
{
    //
    public function __construct(){    	
    	$this->middleware(function ($request, $next) {
    	$url = request()->segment(1);
    	$kode_group = Session::get('kode_group');
    	$d_menu = DB::table("tb_menu as a")->join("tb_role as b","a.kode_menu","b.kode_menu")->where([['a.link_menu',$url],['b.kode_group',$kode_group],['b.status_role','1'],['a.active','1']])->orderBy('a.sort_menu','asc')->count();
    	if(Session::get('decode') <> 1)
         {
         	Session::flash('message', 'Silahkan login dengan username dan password anda.!!');
             return redirect()->to('login');
         }
         if($d_menu == 0){
         	Session::flush();
         	Session::flash('message', 'Anda Tidak Punya Akses ke Halaman ini.!!');
             return redirect()->to('login');
         }
        return $next($request);	
        });
    }

	public function index(){
		
		return view('master.SatuanList');
	}

	function get_data(){
		DB::statement(DB::raw('set @rownum=0'));
		$d_data = DB::table('ms_satuan')->select(DB::raw('*, @rownum  := @rownum  + 1 AS rownum'));

		return Datatables::of($d_data)
				->addColumn('aksi', function($d_data){
					$btnAction = '<button class="btn bg-warning-400" onclick="edit('.$d_data->id_satuan.')"><i class="icon-pencil"></i> </button>
						<button class="btn bg-danger-800" type="button" onclick="hapus('.$d_data->id_satuan.')"><i class="icon-eraser"></i></button>'.
						'<input type="hidden" id="table_id'.$d_data->id_satuan.'" value="'.$d_data->id_satuan.'">'.
						'<input type="hidden" id="table_nama'.$d_data->id_satuan.'" value="'.$d_data->nama_satuan.'">'.
						'<input type="hidden" id="table_satuan'.$d_data->id_satuan.'" value="'.$d_data->satuan.'">'
						;
					return $btnAction;
				})
				->make(true);

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

	function simpan(Request $request){
		$id = $request->get('id');
		$data['nama_satuan'] = $request->get('nama');
		$data['satuan'] = $request->get('kode');

		if($id == ''){
			DB::table('ms_satuan')->insert($data);
		}else{
			DB::table('ms_satuan')->where(array('id_satuan' => $id))->update($data);
		}
	}

	function hapus(Request $request){
		$data['id_satuan'] = $request->get('id');

		DB::table('ms_satuan')->where($data)->delete();
	}

}
