<?php namespace App\Http\Controllers;

use Auth\AuthController;
use App\User;
use App\Role2;
use App\Permission2;
//use App\Permission;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
use View;
use DB;
use App\Http\Requests\PermissionRequest;
use App\Http\Requests\RoleChangeRequest;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class PermissionsController extends Controller {
 
    private $menu='permissions';

    public function __construct()
    {
        //$this->beforeFilter('auth');
    }
 
    public function index()
    {
        $user = Auth::user();
        if(!$user) return Redirect::route( 'login' );

        $permissions = Permission2::where('id', '<>', 'null')->orderBy('name')->get();

        return View::make('acces.permissions.index', [
            'permissions' => $permissions, 
            'user'=>$user,
            'menu' => $this->menu
        ]);
    }
 
    public function create()
    {
        $user = Auth::user();
        if(!$user) return Redirect::route( 'login' );

        return View::make('acces.permissions.create',
            [
                'user' => $user,
                'menu' => $this->menu,
            ]);

    }
 
    public function store(PermissionRequest $request)
    {
        $permission = new Permission;
 
        $permission->name = $request->name;
        $permission->save();

        return Redirect::to('/permissions');
    }
 
    public function edit($id)
    {
        $user = Auth::user();
        if(!$user) return Redirect::route( 'login' );

        $permission = Permission::find($id);
        return View::make('acces.permissions.edit', 
            [ 
                'user' => $user,
                'menu' => $this->menu,
                'permission' => $permission 
            ]);
    }
 

    public function update($id,PermissionRequest $request)
    {
        $permission = Permission::find($id);
        $permission->name = $request->name;
        $permission->save();
 
        return Redirect::to('/permissions');
    }
 
    public function show($id)
    {
        $user = Auth::user();
        if(!$user) return Redirect::route( 'login' );

        $permission = Permission::find($id);
        return View::make('acces.permissions.show', 
            [ 
                'user' => $user,
                'menu' => $this->menu,
                'permission' => $permission 
            ]);
    }

    public function destroy($id)
    {

        DB::table('role_has_permissions')->where('permission_id', '=', $id)->delete();
        DB::table('model_has_permissions')->where('permission_id', '=', $id)->delete();
        DB::table('permissions')->where('id', '=', $id)->delete();
        //Permission::destroy($id);
 
        return Redirect::to('/permissions');
    }
 

}



