<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    protected $table      = 'tbl_authors';
    protected $primaryKey = 'author_id';
    public    $timestamps = true;

    protected $guarded = [];

    protected $casts = [
        'social' => 'array',
    ];

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

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

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

    public function getPhotoUrlAttribute(): string
    {
        if (!empty($this->image)) {
            // Primary location: assets/upload/authors/
           if (file_exists(base_path('assets/upload/authors/' . $this->image))) {
                return asset('assets/upload/authors/' . $this->image);
            }
            // Fallback: img/ folder
            if (file_exists(public_path('img/' . $this->image))) {
                return asset('img/' . $this->image);
            }
        }

        // Generic author placeholder — use news1.jpg since no dedicated author placeholder exists
        return asset('img/news1.jpg');
    }

    public function getUrlAttribute(): string
    {
        return url('/author/' . $this->slug);
    }

    public function getTwitterUrlAttribute(): ?string
    {
        return $this->social['twitter'] ?? null;
    }

    public function getFacebookUrlAttribute(): ?string
    {
        return $this->social['facebook'] ?? null;
    }

    public function getLinkedinUrlAttribute(): ?string
    {
        return $this->social['linkedin'] ?? null;
    }
}
