<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
  /**
   * Enforce middleware
   */
  public function __construct(){
    $this->middleware(['auth']);
    $this->middleware(['permissions:CreateUser'], ['only' => ['create','store']]);
    $this->middleware(['permissions:CreateUser.EditUser.DeleteUser.AssignRole'], ['only' => ['index','show']]);
    $this->middleware(['permissions:DeleteUser'], ['only' => ['destroy']]);
  }
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //Pass all users
    $users = User::get();
    return view('users.index')->with('users', $users);
  }

  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    $roles = Role::get();
    return view('users.create')->with('roles',$roles);
  }

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

    $user = User::create($request->only('email', 'name', 'password')); //Retrieving only the email and password data

    if(auth()->user()->hasPerm('AssignRole')){
      $roles = array();
      foreach($request->all() as $element => $value){
          if(preg_match('/r_.*/', $element)){
              array_push($roles, (int)$value);
          }
      }
      $user->roles()->sync($roles);
    }

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

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

  /**
   * Show the form for editing the specified resource.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function edit($id)
  {
    //verify user has permission to edit record
    if(auth()->user()->hasPerm('EditUser') || auth()->user()->id == $id){
      //Find user and pass to edit
      $user = User::with('roles')->findOrFail($id);

      $roles=Role::get();
      $active_roles=array();
      $active_cats=array();
      foreach($user->roles as $role){
        array_push($active_roles,$role->id);
      }

      return view('users.edit')->with('user',$user)->with('roles',$roles)->with('active_roles',$active_roles);
    }else{
      return redirect('/')->with('message','You don\'t have permission to access this page');
    }
  }

  /**
   * Update the specified resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function update(Request $request, $id)
  {
    if(auth()->user()->hasPerm('EditUser') || auth()->user()->id == $id){
      //Find and update user after validating
      $user = User::findOrFail($id);

      if($request->password != null && (auth()->user()->hasPerm('ResetPassword') || auth()->user()->id == $id)){
        $this->validate($request, [
          'name'=>'required|max:120',
          'email'=>'required|email|unique:users,email,'.$id,
          'password'=>'required|min:6|confirmed'
        ]);
        $update = $request->only(['name','email','password']);
      }else{
        $this->validate($request, [
          'name'=>'required|max:120',
          'email'=>'required|email|unique:users,email,'.$id,
        ]);
        $update = $request->only(['name','email']);
      }
      $user->fill($update)->save();

      if(auth()->user()->hasPerm('AssignRole')){
        $roles = array();
        foreach($request->all() as $element => $value){
            if(preg_match('/r_.*/', $element)){
                array_push($roles, (int)$value);
            }
        }
        $user->roles()->sync($roles);
      }
      if (auth()->user()->hasPerm('EditUser')){
        return redirect()->route('users.index')->with('message','User successfully edited.');
      }else {
        return redirect(url()->previous())->with('message','User successfully edited.');
      }
    }else{
      return redirect('/')->with('message','You don\'t have permission to edit this user');
    }
  }

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

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