<?php

class RolesPermissionsController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /rolespermissions
	 *
	 * @return Response
	 */
	public function index()
	{
		if(!UserRole::has('list_role')) return Redirect::route('dashboard');
		$roles = Role::where('role_name', "<>", "Master")->get();
		return View::make('Roles.index')->with('roles',$roles);
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /rolespermissions/create
	 *
	 * @return Response
	 */
	public function create()
	{
		if(!UserRole::has('create_role')) return Redirect::route('dashboard');
		return View::make('Roles.create')
						->with('groups',$this->permissionGroup());
	}
	/**
	 * Store a newly created resource in storage.
	 * POST /rolespermissions
	 *
	 * @return Response
	 */
	public function store()
	{
		// assume it won't work
      $success = false;

      DB::beginTransaction();

      try {
					$role = Role::whereRoleName(Input::get('role_name'))->first();
					if(!empty($role))
					return Redirect::back()
						->withInput()
						->with('message','messages.duplicated_name')
						->with('messageType','danger');
          $role = new Role;
					$role->role_name = Input::get('role_name');
          $role->description = Input::get('description');
					if ($role->save()) {
              $perms = Input::get('perm');
              if (count($perms) > 0) {
              		foreach ($perms as $key => $value) {
              			$perm_list[] = ['permission_id' => $value, 'role_id' => $role->id];
              		}
									//return $perm_list;
								DB::table('Permission_Role')->insert($perm_list);	
              }
              $success = true;
          }

      } catch (Exception $e) {
      }
      if (!$success) {
          DB::rollback();
          return Redirect::back()
						->withInput()
						->with('message','messages.fail-to-create')
						->with('messageType','danger');
      } else {
      	DB::commit();
        return Redirect::back()
					->withInput()
					->with('message','messages.success-to-create')
					->with('messageType','success');
      }
	}

	/**
	 * Display the specified resource.
	 * GET /rolespermissions/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 * GET /rolespermissions/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		if(!UserRole::has('edit_role')) return Redirect::route('dashboard');
		$role = Role::find($id);
		if(empty($role)) return Redirect::route('roles.index');
		return View::make('Roles.edit')
						->with('role',$role)
						->with('groups',$this->permissionGroup());
	}

	/**
	 * Update the specified resource in storage.
	 * PUT /rolespermissions/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		// assume it won't work
      $success = false;

      DB::beginTransaction();

      try {
          $role = Role::find($id);
          $role->role_name = Input::get('role_name');
          $role->description = Input::get('description');
          if ($role->save()) {
          	$removePermissions = UserRole::removePermissionByRoleId($id);
          	if($removePermissions):
              $perms = Input::get('perm');
              foreach ($perms as $perm => $value) {
              	if(!is_null($perms)):
              		$perm_list[] = ['permission_id' => $value, 'role_id' => $role->id];
              	endif;
              }
              $insertPerms = DB::table('Permission_Role')->insert($perm_list);
            endif;
            $success = true;
          }
      } catch (Exception $e) {

      }
    	DB::commit();
      return Redirect::back()->withInput()->with('message','messages.success-to-update')->with('messageType','success');

	}

	/**
	 * Remove the specified resource from storage.
	 * DELETE /rolespermissions/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$role = Role::find($id);
		if(empty($role)) return Redirect::back()
										->with('message','messages.fail-to-delete')
										->with('messageType','danger');
		$role->delete();
		return Redirect::back()
						->with('message','messages.success-to-delete')
						->with('messageType','success');
	}
	/**
	 * Permission Group
	 * @return array permission group
	 */
	private function permissionGroup()
	{
		$groups = [];
		$permissions = Permission::orderBy('permission_group')->get();
		// loop and add permission_group in to arry
		foreach($permissions as $permission) {
			if ($permission->permission_group == $permission->permission_group) {
				$groups[$permission->permission_group][$permission->id]['id'] = $permission->id;
				$groups[$permission->permission_group][$permission->id]['name'] = (App::getLocale() == "kh" ? $permission->display_name_khmer : $permission->display_name);
			}
		}
		return $groups;
	}

}
