<?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)) {
            // If it's already a full URL
            if (filter_var($this->image, FILTER_VALIDATE_URL)) {
                return $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: public/images/
            if (file_exists(public_path('images/' . $this->image))) {
                return asset('images/' . $this->image);
            }
        }

        return asset('images/img.webp');
    }

    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;
    }
}
