<?php

namespace App\Http\Controllers\Admin;

use App\Facade\Theme;
use App\Facade\UserConfig;
use App\Group;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreGroupRequest;
use App\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\View;

class GroupController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        View::share('is_admin', true);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->authorizeAccessToAdminPanel('admin:manage-groups');

        return Theme::render('admin.create_group');
    }

    public function delete($id)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-groups');

        $group = Group::where('id', intval($id))->first();
        if (is_null($group))
        {
            App::abort(404);
        }

        return Theme::render('admin.delete_group', ['group' => $group]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-groups');

        /** @var Group $group */
        $group = Group::where('id', intval($id))->first();
        if (is_null($group))
        {
            App::abort(404);
        }

        try
        {
            $group->delete();
            $request->session()->flash('success', trans('admin.group_deletion_successful', [
                'name' => $group->name
            ]));
        }
        catch (\Exception $ex)
        {
            $request->session()->flash('error', trans('admin.group_deletion_failed', [
                'error_message' => $ex->getMessage(),
                'name' => $group->name
            ]));
        }

        return redirect(route('groups.index'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-groups');

        $group = Group::where('id', intval($id))->first();
        if (is_null($group))
        {
            App::abort(404);
        }

        if (!$request->session()->has('_old_input'))
        {
            $request->session()->flash('_old_input', $group->toArray());
        }

        return Theme::render('admin.edit_group', [
            'all_permissions' => Permission::where('section', 'admin')->get(),
            'group' => $group
        ]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-groups');

        $groups = Group::orderBy('name')
            ->paginate(UserConfig::get('items_per_page'));

        return Theme::render('admin.list_groups', [
            'error' => $request->session()->get('error'),
            'groups' => $groups,
            'success' => $request->session()->get('success'),
            'warning' => $request->session()->get('warning')
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreGroupRequest $request)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-groups');

        $group = new Group();
        $group->fill($request->only(['name']));
        $group->save();

        return redirect(route('groups.index'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(StoreGroupRequest $request, $id)
    {
        $this->authorizeAccessToAdminPanel('admin:manage-groups');

        /** @var Group $group */
        $group = Group::where('id', intval($id))->first();
        if (is_null($group))
        {
            App::abort(404);
        }

        $group->fill($request->only(['name']));

        // Update the admin permissions
        $group->adminPermissions()->detach();
        $permissions = $request->get('permissions');
        if (is_array($permissions) && array_key_exists($id, $permissions))
        {
            foreach ($permissions[$id] as $permissionID)
            {
                $group->adminPermissions()->attach($permissionID, [
                    'created_at' => new \DateTime(),
                    'updated_at' => new \DateTime()
                ]);
            }
        }

        $group->save();

        return redirect(route('groups.index'));
    }
}