<?php

namespace App\Repositries;

use App\Models\User;

class AdminRepository
{
    public $mainRepositry;
    public $roleRepository;
    public $model;
    public function __construct(MainRepository $mainRepositry, RoleRepository $roleRepository, User $model)
    {
        $this->mainRepositry = $mainRepositry;
        $this->roleRepository = $roleRepository;
        $this->model = $model->admin();
    }
    public function index()
    {
        $admins = $this->model->with('roles');
        return $this->mainRepositry->index($admins);
    }

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

        return $admin->load('roles');
    }

    public function store($data)
    {
        $admin = $this->mainRepositry->create($this->model, $data);
        $this->syncRoles($admin, $data['role_id']);
        return $admin;
    }


    public function update($id, $data)
    {
        $this->checkAvailability($id);
        $admin = $this->mainRepositry->update($this->model, $id, $data);
        $this->syncRoles($admin, $data['role_id']);
        return $admin;
    }

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

    private function checkAvailability($id)
    {
        $this->model->findOrFail($id);
    }

    private function syncRoles($admin, $role_id)
    {
        $admin->syncRoles($this->roleRepository->show($role_id)->name);
    }
}
