<?php

namespace App;

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

class Post extends Model
{
    protected $fillable = [
        'title',
        'excerpt',
        'content',
        'image',
        'featured',
        'parent_id',
        'active',
        'slug',
        'order'
    ];

    public function parent()
    {
        return $this->belongsTo(self::class);
    }

    public function child()
    {
        return $this->hasMany(self::class, 'id');
    }

    public function hits()
    {
        return $this->hasMany('App\Hit');
    }

    public function postable()
    {
        return $this->morphTo();
    }

    public function getFeaturedImageAttribute()
    {
        return Medium::where('post_id', $this->attributes['id'])->whereHas('post', function($q) {
            $q->where('featured', 1);
        })->first();
    }

    public function setSlugAttribute($value)
    {
        $this->attributes['slug'] = $value ?? slug('hola');
    }

    public function setFeaturedAttribute($value)
    {
        $this->attributes['featured'] = $value ? 1 : 0;
    }

    public function categories()
    {
        return $this->belongsToMany('App\Category');
    }

    public function getCategoryAttribute()
    {
        return $this->categories->first();
    }

    public function getCategoryNames()
    {
        return implode(', ', $this->categories->pluck('title')->toArray());
    }

    public function getThumbnailAttribute()
    {
        return $this->featured_image->thumbnail ?? null;
    }

    public function getFullImageAttribute()
    {
        return url($this->image);
    }

    public function media()
    {
        return $this->hasMany('App\Medium');
    }

    public function blocks()
    {
        return $this->hasMany('App\Block', 'post_id', 'id');
    }
}
