<?php

namespace App\Repositories\Auth;

use App\Models\User;

class UserRepository
{
    private $model;

    public function __construct(User $model)
    {
        $this->model = $model;
    }

    public function find($with = null, $nip = null, $email = null, $id = null)
    {
        return $this->model
                ->when($with, function ($query) use ($with) {
                    return $query->with($with);
                })
                ->when($nip, function ($query) use ($nip) {
                    return $query->whereHas('rBiodata', function ($query) use ($nip) {
                        $query->where('noidentitas', $nip);
                    });
                })
                ->when($email, function ($query) use ($email) {
                    return $query->where('email', $email);
                })
                ->when($id, function ($query) use ($id) {
                    return $query->where('id', $id);
                })
                ->first();
    }

    public function paginate($with = null, $search = null, $is_active = null, $paginate = 10)
    {
        return $this->model
            ->when($with, function ($query) use ($with) {
                return $query->with($with);
            })
            ->when($is_active, function ($query) use ($is_active) {
                return $query->where('is_active', $is_active);
            })
            ->when(!$is_active, function ($query) {
                return $query->where('is_active', 0);
            })
            ->when($search, function ($query) use ($search) {
                return $query->where(function ($query) use ($search) {
                    return $query->where('nidn', 'ilike', '%'.$search.'%')
                        ->orWhere('nip', 'ilike', '%'.$search.'%')
                        ->orWhere('name', 'ilike', '%'.$search.'%');
                });
            })
            ->orderBy('name', 'asc')
            ->paginate($paginate);
    }

    public function storeSso($id, $data)
    {
        $data['id'] = $id;
        $data['password'] = bcrypt($data['noid'].'s3cr3t5');
        $data['is_active'] = 1;

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