<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Category extends Model
{
    protected $table      = 'tbl_category';
    protected $primaryKey = 'category_id';
    public    $timestamps = false;

    protected $guarded = [];

    // ─── Relationships ──────────────────────────────────────────────────────────

    public function news()
    {
        return $this->hasMany(News::class, 'category_id', 'category_id');
    }

    // ─── Accessors ───────────────────────────────────────────────────────────────

    /**
     * Use stored slug if present, otherwise auto-generate from name.
     */
    public function getSlugAttribute(): string
    {
        return $this->attributes['slug']
               ?? Str::slug($this->category_name ?? '');
    }

    /**
     * URL for the category listing page.
     */
    public function getUrlAttribute(): string
    {
        return url('/category/' . $this->slug);
    }

    /**
     * Banner image URL (optional).
     */
    public function getBannerUrlAttribute(): string
    {
        if (!empty($this->category_banner)
            && file_exists(public_path('assets/upload/categories/' . $this->category_banner))) {
            return asset('assets/upload/categories/' . $this->category_banner);
        }
        return asset('img/news1.jpg');
    }
}
