<?php

namespace App\Repositries;

use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RoleRepository
{
    public $mainRepositry;
    public $model;
    public function __construct(MainRepository $mainRepositry, Role $model)
    {
        $this->mainRepositry = $mainRepositry;
        $this->model = $model->whereNot('id', 1);
    }
    public function index()
    {
        $roles = $this->mainRepositry->index($this->model);

        return $roles;
    }

    public function show($id)
    {
        $role = $this->mainRepositry->show($this->model, $id);

        $role['permission_ids'] = $role->permissions->pluck('id')->toArray();

        unset($role->permissions);

        return $role;
    }

    public function create($data)
    {
        $role = $this->mainRepositry->create($this->model, $data);
        $this->syncPermissions($role, $data['permissions']);
        return $role;
    }


    public function update($id, $data)
    {
        $role = $this->mainRepositry->update($this->model, $id, $data);
        $this->syncPermissions($role, $data['permissions']);
        return $role;
    }

    public function destroy($id)
    {
        $this->mainRepositry->destroy($this->model, $id);
    }


    private function syncPermissions($role, $permissions)
    {
        $permissions = Permission::whereIn('id', $permissions)->get()->pluck('name')->toArray();
        $role->syncPermissions($permissions);
    }
}
