<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use App\Role;
use Illuminate\Support\Facades\Validator;
use DataTables;


class RoleController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware('administrator');
        $this->pageTitle = 'Role';
        $this->masterActive = 'active';
        $this->roleActive = 'active';
    }
    public function index()
    {
        $data = (array)$this;
        $data['form'] = [
            [ 'name' => 'name', 'label' => 'Nama', 'type' => 'text'],
            // ['name' => 'ket', 'label' => 'Keterangan', 'type'=>'select', 'value' => ['sa', 'tu', 'dua']]  
        ];
        $data['form_action'] = "role.store";
        $data['form_update'] = "role.update";
        // return json_encode($data);
        return View::make('dashboard.role.index', $data);
    }
    public function indexData(Request $request){
        $data = Role::all();
         return Datatables::of($data)
               ->editColumn('action', function($data){ return view('dashboard.role.index-action', compact('data'));})
               ->rawColumns(['action'])
               ->make(true); 

   }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
        ]);

        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $researche = Role::create([
            'name' => $request->name
            ]);

        session()->put('success','Berhasil Input.');   
        return redirect('/role');
        
        // return json_encode($request->all());
    }

    public function destroy($id)
    {
        $data = Role::find($id);
        if($data->count() < 1){
        session()->put('error','Gagal hapus.');
            return redirect('/role');
        };
        $data->delete();
        session()->put('success','Berhasil Hapus.');
            return redirect('/role');
    }
    public function look(Request $request)
    {
       
        $data = Role::findOrFail($request->data);
        return json_encode($data);

    }
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $data = Role::find($request->id);
        $data->name = $request->name;
        $data->save();
        session()->put('success','Berhasi edit!');
        return redirect('/role');  
    }

}