<?php

namespace App\Repositories;

use App\Models\Auth\Biodata;
use Auth;
use Illuminate\Support\Str;

class UserdetailRepository
{
    public function __construct(Biodata $model)
    {
        $this->model = $model;
    }

    public function findbyid($id = null, $with = null)
    {
        return $this->model
            ->when($with, function ($query) use ($with) {
                return $query->with($with);
            })
            ->when($id, function ($query) use ($id) {
                return $query->where('id', $id);
            })
            ->first();
    }

    public function findbyuser($userid = null, $with = null, $nim = null)
    {
        return $this->model
            ->when($with, function ($query) use ($with) {
                return $query->with($with);
            })
            ->when($userid, function ($query) use ($userid) {
                return $query->where('user_id', $userid);
            })
            ->when($nim, function ($query) use ($nim) {
                return $query->where('noidentitas', $nim);
            })
            ->first();
    }

    public function get($id = null, $with = null, $fakultas = null, $limit = 3000)
    {
        return $this->model
            ->when($id, function ($query) use ($id) {
                return $query->where('id', $id);
            })
            ->when($with, function ($query) use ($with) {
                return $query->with($with);
            })
            ->when($fakultas, function ($query) use ($fakultas) {
                return $query->where('fakultas', $fakultas);
            })
            ->orderBy('prodi', 'asc')
            ->limit($limit)
            ->get();
    }

    public function store($request)
    {
        $data = $request->except('_token');
        $data['id'] = (string) Str::uuid();
        $data['user_id'] = Auth::user()->id;
        $data['userid_created'] = Auth::user()->id;
        $data['userid_updated'] = Auth::user()->id;
        $biodata = $this->model->create($data);

        return $biodata;
    }

    public function storeSso($id, $data)
    {

        $data['id'] = $id;
        $data['noidentitas'] = $data['noid'];
        $data['type'] = $data['role'];
        $data['origin'] = 'Universitas Negeri Surabaya';

        return $this->model->create($data);
    }
}
