<?php

namespace App\Modules\Admin;

use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Response;
use App\Models\Group;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;

class GroupsController extends BaseController
{
    /**
     *	The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

    /**
     * Render the main page listing all the groups.
     *
     * @return null
     */
    public function index()
    {
        $this->layout->content = View::make('admin::settings.groups.index');
    }

    /**
     * Display the create a new group page.
     *
     * @return null
     */
    public function create()
    {
        $this->layout->content = View::make('admin::settings.groups.create');
    }

    /**
     * Store a new group.
     *
     * @return \Group | Illuminate\Support\Response
     */
    public function store(Request $request)
    {
        $group = Group::create($request->all());

        if (! $group->exists) {
            return Response::json(['errors' => $group->errors->all()], 400);
        }

        //Link group and permissions
        if ($request->has('permissions')) {
            $permissions = $request->get('permissions');
            foreach ($permissions as $permission) {
                $group->permissions()->attach($permission);
            }
        }

        // Link group and users
        if ($request->has('users')) {
            $group->users()->sync($request->get('users', []));
        }

        return $group;
    }

    /**
     * Display the page to edit the group.
     *
     * @return null
     */
    public function edit($id)
    {
        $group = Group::findOrFail($id);

        $this->layout->content = View::make('admin::settings.groups.edit', compact('group'));
    }

    /**
     * Save changes made to a group.
     *
     * @return null
     */
    public function update($id, Request $request)
    {
        $group = Group::findOrFail($id);

        $group->fill($request->all());

        if (! $group->save()) {
            return Response::json(['errors' => $group->errors->all()], 400);
        }

        //Delete all the permissions
        $group->permissions()->detach();

        //Link group and permissions
        if ($request->has('permissions')) {
            $group->permissions()->sync($request->get('permissions', []));
        }

        if ($request->has('users')) {
            $group->users()->sync($request->get('users', []));
        }

        return $group;
    }
}
