<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;
use Auth;

//Importing laravel-permission models
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Support\Facades\Hash;

//Enables us to output flash messaging
use Session;

class UserController extends Controller {

    public function __construct() {
        $this->middleware(['role:admin']);
    }

    /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function index() {
    //Get all users and pass it to the view
        $users = User::orderBy('created_at','DESC')->get()->except(Auth::id());
        return view('users.index')->with('users', $users);
    }

    /**
    * Show the form for creating a new resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function create() {
    //Get all roles and pass it to the view
        $roles = Role::get();
        return view('users.create', ['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 fields
        $this->validate($request, [
            'name'=>'required|max:120',
            'email'=>'required|email|unique:users',
            'balance'=>'required|min:0',
            'password'=>'required|min:6|confirmed',
            'phone_no'=>'required|min:1000|max:99999999999999|numeric',
            'address'=>'required|min:5|max:1000'
        ],
        [
            'phone_no.min'=>'The phone number must be at least 4 digits',
            'phone_no.max'=>'The phone number may not be greater than 14',
        ]);

        $request['password'] =  Hash::make($request->password);
        $user = User::create($request->only('email', 'name', 'password', 'balance', 'phone_no', 'address')); //Retrieving only the email and password data

        $roles = $request['roles']; //Retrieving the roles field
    //Checking if a role was selected
        if (isset($roles)) {

            foreach ($roles as $role) {
            $role_r = Role::where('id', '=', $role)->firstOrFail();
            $user->assignRole($role_r); //Assigning role to user
            }
        }

        $user->givePermissionTo('send');

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

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

    /**
    * Show the form for editing the specified resource.
    *
    * @param  int  $id
    * @return \Illuminate\Http\Response
    */
    public function edit($id) {
        $user = User::findOrFail($id); //Get user with specified id
        $roles = Role::get(); //Get all roles
        $permissions = Permission::get(); //Get all permissions

        return view('users.edit', compact('user', 'roles', 'permissions')); //pass user and roles data to view

    }

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

        //Validate name, email and password fields
        $this->validate($request, [
            'name'=>'required|max:120',
            'email'=>'required|email',
            'balance'=>'required|min:0',
            'password'=>'confirmed',
            'phone_no'=>'required|min:1000|max:99999999999999|numeric',
            'address'=>'required|min:5|max:1000'
        ],
        [
            'phone_no.min'=>'The phone number must be at least 4 digits',
            'phone_no.max'=>'The phone number may not be greater than 14',
        ]);

        if ($request->filled('password')) {
            $request['password'] =  Hash::make($request->password);
            $input = $request->only(['name', 'email', 'password', 'balance', 'phone_no', 'address']);//Retreive the name, email and password fields
        } else {
            $input = $request->only(['name', 'email', 'balance', 'phone_no', 'address']); //Retreive the name and email fields
        }

        $roles = $request['roles']; //Retreive all roles
        $permissions = $request['permissions']; //Retreive all permissions
        $user->fill($input)->save();

        if (isset($roles)) {
            $user->roles()->sync($roles);  //If one or more role is selected associate user to roles
        }
        else {
            $user->roles()->detach(); //If no role is selected remove exisiting role associated to a user
        }

        if (isset($permissions)) {
            $user->permissions()->sync($permissions);  //If one or more role is selected associate user to permissions
        }
        else {
            $user->permissions()->detach(); //If no permission is selected remove exisiting permission associated to a user
        }

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

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

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