<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class Block extends Model
{
    protected $fillable = [
        'post_id',
        'selector',
        'url'
    ];

    public function post()
    {
        return $this->morphOne('App\Post', 'postable');
    }

    public function getImageAttribute()
    {
        return $this->post->featured_image->post->image ?? null;
    }

    public function getImagesAttribute()
    {
        return $this->post->media()->notFeatured()->get()->sortBy('post.order');
    }

    public function parent_post()
    {
        return $this->belongsTo('App\Post', 'post_id', 'id');
    }

    public function selectors()
    {
        return config('cms.templates.'.$this->parent_post->slug.'.blocks') ?? [];
    }

    public function getSelectorNameAttribute()
    {
        return config('cms.templates.'.$this->parent_post->slug.'.blocks.'.$this->attributes['selector']) ?? null;
    }

    public function getImagesJSONAttribute()
    {
        $media = $this->post->media()->notFeatured()->get()->sortBy('post.order');
        $output = [];
        foreach($media as $medium) {
            $output[] = [
                'thumbnail' => $medium->thumbnail ? url($medium->thumbnail) : null,
                'image' => $medium->post->image ? url($medium->post->image) : null,
            ];
        }
        return json_encode($output);
    }
}
