<?php namespace App\Http\Controllers;

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


class PermissionsController extends Controller {

    private $menu='acces';
    private $submenu='permissions';
    private $menu_home='acces';


    public function __construct()
    {
        //$this->beforeFilter('auth');
    }


    public function index()
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );

        $permissions = Permission2::where('id', '<>', 'null')->orderBy('name')->get();
        return View::make('acces.permissions.index', [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            'permissions' => $permissions
        ]);
    }


    public function create($mode="create",$id="")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );

        $permission ="";
        if($id){
            $permission = Permission2::find($id);
        }
        return View::make('acces.permissions.'.$mode,[
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,'mode' => $mode,
            'permission' => $permission,
        ]);
    }


    public function store(PermissionRequest $request)
    {
        $permission = $this->setData($request);
        return Redirect::to('/permissions');
    }


    public function edit($id)
    {
        return $this->create("edit",$id);
    }


    public function update($id,PermissionRequest $request)
    {
        $permission = $this->setData($request,$id);
        return Redirect::to('/permissions');
    }

    public function show($id)
    {
        return $this->create("show",$id);
    }


    public function setData($request,$id="")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );

        if($id) $permission = Permission2::find($id);
        else $permission = new Permission2;

        $permission->name = $request->name;
        $permission->display_name = $request->display_name;
        $permission->save();

        return $permission;
    }

    public function destroy($id)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );

        $permission = Permission2::find($id);
        if(!$permission->IsSupprimable) {
            $msg="Suppression interdite";
            Session::flash('message', $msg);
            return Redirect::back()->with('msg', $msg);
        }
        Permission2::destroy($id);
        Session::flash('message', "Suppression effectuée");
        return Redirect::to('/permissions');
    }



}



