<?php

namespace App\Services;

use App\Models\Group;
use App\Models\ModulePermission;
use App\Models\ResourcePermission;

class GroupService
{
    public function store($data)
    {
        $group = Group::create([
            'name' => $data->get('name')
        ]);

        $can_create_modules   = $data->input('permissions.create');
        $can_access_resources = $data->input('permissions.access');

        $this->attachResourcePermission($can_access_resources, $group->group_ID);

        $this->attachModulePermission($can_create_modules, $group->group_ID);
    }

    public function update($data, $group)
    {
        $group->update([
            'name' => $data['name']
        ]);

        $can_create_modules   = $data->input('permissions.create');
        $can_access_resources = $data->input('permissions.access');

        $this->deattachModulePermission($group->group_ID);
        $this->attachModulePermission($can_create_modules, $group->group_ID);

        $this->deattachResourcePermission($group->group_ID);
        $this->attachResourcePermission($can_access_resources, $group->group_ID);
    }

    public function destroy($group)
    {

        if (!auth()->user()->isAdminOrOwner()) {
            return;
        }

        $users = $group->users()->exists();

        if ($users) {

            abort(400, trans('users.delete_users_before', [
                'group' => $group->name
            ]));
        } else {

            $group->delete();
        }

    }

    public function getAllGroups()
    {
        return Group::orderBy('created_at', 'desc')->get();
    }

    public function getGroupsCount()
    {
        return Group::all()->count();
    }

    private function attachResourcePermission($resources, $group_id)
    {

        if ($resources) {

            foreach ($resources as $resource) {
                ResourcePermission::create([
                    'group_id'    => $group_id,
                    'resource_id' => $resource,
                    'can_view'    => true

                ]);
            }

        }

    }

    private function attachModulePermission($modules, $group_id)
    {

        if ($modules) {

            foreach ($modules as $module) {
                ModulePermission::create([
                    'group_id'    => $group_id,
                    'module_id'   => $module,
                    'can_add_new' => true
                ]);
            }

        }

    }

    private function deattachModulePermission($group_id)
    {
        ModulePermission::where(['group_id' => $group_id])->delete();
    }

    private function deattachResourcePermission($group_id)
    {
        ResourcePermission::where(['group_id' => $group_id])->delete();
    }

}
