<?php

namespace App\Traits;
use Illuminate\Support\Str;
use App\Models\ModelHasRoles;
use App\Repositories\Auth\RoleRepository;
use App\Repositories\Auth\UserRepository;

use App\Repositories\UserdetailRepository;
use App\Repositories\Auth\BiodataRepository;

trait LoginTrait
{
    private $userRepo;
    private $roleRepo;
    private $biodataRepo;
    private $userDetailRepo;

    public function __construct(
        UserRepository $userRepo,
        RoleRepository $roleRepo,
        BiodataRepository $biodataRepo,
        UserdetailRepository $userDetailRepo
    ) {
        $this->userRepo = $userRepo;
        $this->roleRepo = $roleRepo;
        $this->biodataRepo = $biodataRepo;
        $this->userDetailRepo = $userDetailRepo;
    }

    public function login_reviewer($nip)
    {
        $user = $this->userRepo->find(null, $nip, null);

        if ($user) {
            $this->createRole($user->id);
            return 'sudah ada';
        } else {
            return $this->getAddReviewer($nip);
        }
    }

    private function getAddReviewer($nip)
    {
        $id = (string) Str::uuid();
        $data = collect([
            (object) [
                'jenis' => 'P',
                'userid' => $nip
            ]
        ]);
        $biodata = $this->biodataRepo->biodata($data->toArray());
        $user = $this->userRepo->storeSso($id, $biodata);
        $roles = $this->roleRepo->roles('reviewer');
        $this->userDetailRepo->storeSso($user->id, $biodata);
        $this->roleRepo->store($user, $roles);
        $this->createRole($user->id);

        return 'sukses';
    }

    private function createRole($reqId)
    {
        // CEK APAKAH ADA ROLE SEBAGAI REVIEWER
        $ada_data = ModelHasRoles::where([
            ['model_id', '=', $reqId?:''],
            ['role_id', '=', '2619bc99-0027-4997-9510-d4736bd26862']
        ])->count();

        if ($ada_data == 0)
        {
            $data_role['role_id'] = '2619bc99-0027-4997-9510-d4736bd26862';
            $data_role['model_type'] = 'App\Models\User';
            $data_role['model_id'] = $reqId;

            ModelHasRoles::create($data_role);
        }

        // CEK APAKAH ADA ROLE SEBAGAI DOSEN
        $ada_data_reviewer = ModelHasRoles::where([
            ['model_id', '=', $reqId],
            ['role_id', '=', 'a48826dd-ad41-406d-a1db-2a5e94a78bb8']
        ])->count();

        if ($ada_data_reviewer == 0)
        {
            $data_role['role_id'] = 'a48826dd-ad41-406d-a1db-2a5e94a78bb8';
            $data_role['model_type'] = 'App\Models\User';
            $data_role['model_id'] = $reqId;

            ModelHasRoles::create($data_role);
        }

        return 'sukses';

    }
}
