<?php

namespace App\Http\Controllers\user;

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

class GroupController 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('user.GroupList');
    	/*return view('BarangkeluarList');*/
    }

    function tampil(){
    	DB::statement(DB::raw('set @rownum=0'));
		$d_data = DB::table('tb_group as tg')->select([DB::raw('tg.*')]);

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

    function simpan(Request $request){
    	$id = $request->get('popup_id');
    	$data['nama_group'] = $request->get('popup_nama');

    	if($id == ''){
    		DB::table('tb_group')->insert($data);
    	}else{
    		DB::table('tb_group')->where('kode_group',$id)->update($data);
    	}

    	return response()->json(array('status'=> '1'));
    }

    function hapus(Request $request){
    	$data['kode_group'] = $request->get('id');
    	DB::table('tb_group')->where($data)->delete();
    }
}
