<?php

namespace Modules\Pengguna\Services;

use App\Libraries\Constants;
use App\Services\BaseService;
use Modules\Pengguna\Repositories\PenggunaRepository;

class PenggunaService extends BaseService implements PenggunaServiceInterface
{
    public function __construct(PenggunaRepository $penggunaRepository)
    {
        $this->mainRepository = $penggunaRepository;
    }

    public function datatable()
    {
        return $this->mainRepository->datatable();
    }

    public function deleteUserAndRemoveRole($id)
    {
        try {
            $user = $this->mainRepository->findById($id);

            if (!$user) {
                throw new \Exception(__('messages.id_not_found'));
            }

            // REMOVE ROLE
            $user->removeRole($user->role->name);

            if (!$user->delete()) {
                throw new \Exception(__('messages.delete_failed', ['action' => __('lang.users'),]));
            }

            return $user;
        } catch (\Exception $e) {
            writeAppLog($e->getMessage(), 'alert');

            return false;
        }
    }
}
