<?php

namespace App\Modules\User\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;
use Yajra\Datatables\Datatables;
use App\User;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Storage;
use DB;
class RolesController extends Controller
{
    protected $table;
    protected $permission;
    protected $table_pivot = 'role_has_permissions';
    function __construct(){
        $this->middleware('auth');
        $this->table = new Role();
        $this->permission = new Permission();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {       
        $roles = $this->permission::all();
        return view('User.views.role',['permisos'=>$roles]);
    }
    /**
     * Display a listing of the datatables list.
     *
     */
    public function permission_role(){

    }
    public function getTable()
    {   
        $table = Datatables::of($this->table::all());
        $table->addColumn('action', function($row){
            return view('layouts.buttons.buttons-admin')->with('url',url('user/config/roles'))->with('id',$row['id'])->with('modal','1');;
        })->rawColumns(['action']);
        return $table->make(true);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       if ($request->has('action')) {
           $data = $request->all();
           switch ($data['action']) {
                case 'showtable':
                    return $this->getTable();    
                break;
                case 'add':
                    $validator = Validator::make($request->all(),[
                        'name' => 'required',
                        'permisos' => 'required',
                    ]);
                    if ($validator->fails()) {
                        return response()->json(['error'=>$validator->errors()->all()]);
                    }else{
                        if ($this->table::where('name', '=', $data['name'])->count() > 0) {
                            return response()->json(['error'=>array('El rol '.$data['name'].' ya existe')]);
                        }else{
                            $rol = $this->table::create([
                                'name' => $data['name'],
                                'guard_name' => 'web',
                            ]);
                            if ($request->has('permisos')) {
                                for ($i=0; $i <count($data['permisos']) ; $i++) { 
                                    $rol->givePermissionTo($data['permisos'][$i]);
                                }
                            }
                           return response()->json(['success'=>'Registro agregado con exito','tablereload'=>'1']);
                        }
                    }

                break;
                default:
                   # code...
                break;
           }
       }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function get_permission_by_role($id){
        $get = DB::table($this->table_pivot)->where('role_id',$id)->get();
        $data = array();
        foreach ($get as $g) {
            $permi = Permission::find($g->permission_id);
            $data[] = (Object)array('name'=>$permi->name,'id'=>$permi->id);
        }
        return $data;
    }
    public function show($id)
    {
        $data = $this->table::find($id);
        $permisos = $this->permission::all();
        $get_by_permi = $this->get_permission_by_role($id);
        if (!empty($data)) {
            return view('User.views.edit.role',['data'=>$data,'permisos'=>$permisos,'get_by_per'=>$get_by_permi]);
        }else{

        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
 
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $this->table::find($id);
        if (!empty($data)) {
            $datos = $request->all();
            if ($request->has('permisos')) {
                $get = DB::table($this->table_pivot)->where('role_id',$id)->delete();
                for ($i=0; $i <count($datos['permisos']) ; $i++) { 
                    $data->givePermissionTo($datos['permisos'][$i]);
                }
            }
            unset($datos['permisos']);
            $data->fill($datos)->save();
            return response()->json(['success'=>'Registro actualizado con exito','tablereload'=>'1']);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = $this->table::find($id);
        if (!empty($data)) {
            $get = DB::table($this->table_pivot)->where('role_id',$id)->delete();
            $data->delete();
            return response()->json(['success'=>'Registro eliminado con exito']);
        }
    }
}
