<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Journal extends Model
{
    // PENTING: Agar semua kolom bisa diisi via Controller
    protected $guarded = ['id'];

    // Agar data array otomatis jadi JSON, dan tanggal jadi format Date
    protected $casts = [
        'topics' => 'array',
        'date' => 'date',
    ];

    // --- RELASI ---

    // TAMBAHAN: Relasi ke User (Guru)
    // Ini memperbaiki error "Call to undefined relationship [user]"
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function subject()
    {
        return $this->belongsTo(Subject::class);
    }

    // Relasi ke Siswa lewat tabel pivot jurnal_student
    public function students()
    {
        return $this->belongsToMany(Student::class, 'jurnal_student', 'jurnal_id', 'student_id')
                    ->withPivot('status')
                    ->withTimestamps();
    }

    // --- FITUR TAMBAHAN (ACCESSOR) ---
    // Ini agar di Javascript/View bisa terbaca jumlah kehadiran
    protected $appends = ['student_attendance'];

    public function getStudentAttendanceAttribute()
    {
        // Mengembalikan Array ID siswa yang statusnya 'hadir'
        // Jika jurnal baru dibuat, kembalikan array kosong
        if (!$this->exists) {
            return [];
        }

        return $this->students()
                    ->wherePivot('status', 'hadir')
                    ->pluck('students.id')
                    ->toArray();
    }
}