<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Carbon\Carbon;

class Post extends Model
{
    protected $fillable = [
      'title',
      'slug',
      'thumbnail',
      'body',
      'active',
      'published_at',
      'user_id',
      'meta_title',
      'meta_description',
    ];
    public function user(): BelongsTo
    {
      return $this->belongsTo(User::class);
    }
    public function categories(): BelongsToMany
    {
      return $this->belongsToMany(Category::class, 'category_posts', 'post_id', 'category_id');
    }
    public function tags(): BelongsToMany
    {
      return $this->belongsToMany(Tag::class, 'tag_posts', 'post_id', 'tag_id');
    }
    public function comments()
    {
      return $this->hasMany(Comment::class, 'post_id')->whereNull('parent_id')->with('replies');
    }
    public function ShortBody()
    {
      return Str::limit(strip_tags($this->body), 100, '...');
    }
    public function getFormattedDate()
    {
      return Carbon::parse($this->published_at)->format('F jS, Y');
    }
    public function getThumbnail()
    {
      if (str_starts_with($this->thumbnail, 'http')) {
          return $this->thumbnail;
      }
      return '/storage/' . $this->thumbnail;
    }
    public function ShortTitle()
    {
      return Str::limit(strip_tags($this->body), 30, '...');
    }
}
