<?php

namespace App\Http\Controllers\master;

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

class ProsesController 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.ProsesList');
    }

    function get_data(){
        $d_data = DB::table('ms_proses')->where('parent', '!=', '0');

        if($d_data->count() > 0){
            foreach($d_data->get() as $d){
                $arr[] = array('id_proses' => $d->id_proses,
                                'nama_proses' => $d->nama_proses,
                                'jenis' => $d->jenis,
                                'aksi' => '<a class="btn  btn-xs bg-warning-400" type="button" onclick="edit('.$d->id_proses.')"><i class="icon-pencil"></i> </a> <button class="btn btn-xs bg-danger-800" type="button" onclick="hapus('.$d->id_proses.')"><i class="icon-eraser"></i></button>'.
                                '<input type="hidden" id="table_id'.$d->id_proses.'" value="'.$d->id_proses.'">'.
                                '<input type="hidden" id="table_nama'.$d->id_proses.'" value="'.$d->nama_proses.'">'.
                                '<input type="hidden" id="table_jenis'.$d->id_proses.'" value="'.$d->jenis.'">');
            }
        }else{
            $arr = array(); 
        }

        $data = new Collection($arr);
        return Datatables::of($data)
                ->make(true);
    }   

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

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

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

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


}
