<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Role;
use App\Permission;
use App\User;

class RoleController extends Controller
{
  /**
   * Enforce middleware
   */
  public function __construct(){
    $this->middleware(['auth']);
    $this->middleware(['permissions:CreateRole'], ['only' => ['create','store']]);
    $this->middleware(['permissions:CreateRole.EditRole.DeleteRole'], ['only' => ['index','show']]);
    $this->middleware(['permissions:EditRole'], ['only' => ['edit','update']]);
    $this->middleware(['permissions:DeleteRole'], ['only' => ['destroy']]);
  }
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //Pass all roles
    $roles=Role::get();
    return view('roles.index')->with('roles', $roles);
  }

  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    $categories=Permission::select('category')->groupBy('category')->get();
    foreach ($categories as $value){
      $permissions[$value->category]=Permission::where('category',$value->category)->get();
    }
    return view('roles.create')->with('permissions',$permissions);
  }

  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    //Validate name and description
    $this->validate($request, [
      'name'=>'required|max:120',
      'description'=>'required|max:3000'
    ]);

    $perms = array();
    foreach($request->all() as $element => $value){
        if(preg_match('/p_.*/', $element)){
            array_push($perms, (int)$value);
        }
    }

    $role = Role::create($request->only('name', 'description'));

    $role->permissions()->sync($perms);

    //Redirect to the roles.index view and display message
    return redirect()->route('roles.index')->with('message','Role successfully added.');
  }

  /**
   * Display the specified resource.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function show($id)
  {
    //Redirect requests to view specific role to roles index
    return redirect('roles');
  }

  /**
   * Show the form for editing the specified resource.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function edit($id)
  {
    $role = Role::with('permissions')->findOrFail($id);
    $categories=Permission::select('category')->groupBy('category')->get();
    foreach ($categories as $value){
      $permissions[$value->category]=Permission::where('category',$value->category)->get();
    }
    $active_perms=array();
    $active_cats=array();
    foreach($role->permissions as $perm){
      array_push($active_perms,$perm->id);
      array_push($active_cats,$perm->category);
    }
    return view('roles.edit')->with('role',$role)->with('permissions',$permissions)->with('active_perms',$active_perms)->with('active_cats',$active_cats);
  }

  /**
   * Update the specified resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function update(Request $request, $id)
  {
    //Find and update user after validating
    $role = Role::findOrFail($id);

    $this->validate($request, [
      'name'=>'required|max:120',
      'description'=>'required|max:3000'
    ]);

    $perms = array();
    foreach($request->all() as $element => $value){
        if(preg_match('/p_.*/', $element)){
            array_push($perms, (int)$value);
        }
    }

    $update = $request->only(['name','description']);
    $role->fill($update)->save();

    $role->permissions()->sync($perms);

    return redirect()->route('roles.index')->with('message','Role successfully edited.');
  }

  /**
   * Remove the specified resource from storage.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function destroy($id)
  {
    //Find and remove user
    $role = Role::findOrFail($id);
    $role->permissions()->sync([]);
    $role->users()->sync([]);
    $role->delete();

    return redirect()->route('roles.index')->with('message','Role successfully deleted.');
  }
}
