<?php

namespace App\Models;

use App\Traits\HasSlug;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use HasFactory, HasSlug;

    protected $fillable = [
        'user_id', 'type', 'title', 'article_image_path', 'excerpt', 
        'content', 'html_content', 'html_file_path', 'is_published'
    ];

    protected $casts = [
        'is_published' => 'boolean',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function categories(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Category::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function tags(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Tag::class);
    }

    public function isHtmlType(): bool
    {
        return $this->type === 'html';
    }

    public function getContentAttribute()
    {
        if ($this->isHtmlType() && $this->html_file_path && file_exists(public_path($this->html_file_path))) {
            return file_get_contents(public_path($this->html_file_path));
        }
        
        return $this->isHtmlType() ? $this->html_content : $this->attributes['content'];
    }
}
