<?php

namespace Modules\Lpj\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Modules\Lpj\Database\Factories\PenilaianFactory;
use Modules\Lpj\Models\JenisPenilaian;
use Modules\Lpj\Models\Teams;
use Modules\Lpj\Models\Permohonan;
use Modules\Usermanagement\Models\User;

class Penilaian extends Base
{
    /**
     * The attributes that are mass assignable.
     */
    protected $table = 'penilaian';
    protected $fillable = [
        'jenis_penilaian_id', 'penilaian_id', 'tanggal_kunjungan', 'keterangan','nomor_registrasi',
        'status', 'authorized_status', 'authorized_at', 'authorized_by', 'created_at',
        'created_by', 'updated_at', 'updated_by', 'deleted_at', 'deleted_by','waktu_penilaian', 'deskripsi_penilaian', 'reschedule_date','reschedule_note','rejected_note'
    ];

    public function jenis_penilaian()
    {
        return $this->belongsTo(JenisPenilaian::class, 'jenis_penilaian_id', 'id');
    }

    public function teams()
    {
        return $this->belongsTo(Teams::class, 'teams_id', 'id');
    }

    public function teamLeader(){
        return $this->belongsTo(Teams::class, 'teams_id', 'id')
                    ->with(['teamsUsers' => function($query) {
                        $query->whereHas('user', function($q) {
                            $q->whereHas('roles', function($r) {
                                $r->where('name', 'senior-officer');
                            });
                        })->with('user');
                    }]);
    }

    public function userPenilai()
    {
        return $this->hasMany(PenilaianTeam::class, 'penilaian_id', 'id');
    }

    public function _user_penilai()
    {
        return $this->hasOne(PenilaianTeam::class, 'penilaian_id', 'id')
                    ->where('role', 'penilai')
                    ->with('userPenilaiTeam');
    }

    public function permohonan()
    {
        return $this->belongsTo(Permohonan::class, 'nomor_registrasi', 'nomor_registrasi');
    }
}
