<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class News extends Model
{
    use HasFactory;

    protected $fillable = [
        'campus_id',
        'excerpt', // Kolom title dihapus
        'content',
        'image_url',
        'category',
        'color',
        'published_at',
        'user_id',
    ];

    protected $with = ['campus']; 
    
    protected $casts = [
        'published_at' => 'datetime',
    ];

    protected $appends = ['url'];

    /**
     * Definisikan relasi ke Campus.
     */
    public function campus()
    {
        return $this->belongsTo(Campus::class); 
    }

    /**
     * Definisikan relasi ke User (admin/editor).
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Accessor untuk properti 'url'.
     * Menggunakan campus->slug untuk membuat URL frontend.
     */
    public function getUrlAttribute()
    {
        // Pastikan relasi campus telah dimuat
        if (!$this->relationLoaded('campus') || !$this->campus) {
             return null;
        }

        $slug = $this->campus->slug; // Asumsi model Campus memiliki kolom 'slug'
        
        try {
            return route('campus.berita.detail', ['slug' => $slug, 'id' => $this->id]);
        } catch (\Exception $e) {
            return "/{$slug}/berita/{$this->id}";
        }
    }
}