<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Page extends Model
{
    protected $fillable = [
        'parent_id',
        'target',
        'position_id',
        'template'
    ];

    protected $casts = [
        'position_id' => 'array',
    ];

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

    public function getPaddedTitleAttribute()
    {
        $str = $this->parent_id ? '&mdash; ' : null;

        return $str.$this->post->title;
    }

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

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

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

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

    public function getPosition()
    {
        return config('cms.positions')[$this->attributes['position']];
    }

    public function getTarget()
    {
        return config('cms.targets')[$this->attributes['target']];
    }

    public function getParentName()
    {
        return $this->parent->post->title ?? null;
    }

    public function getTemplateNameAttribute()
    {
        return config('cms.templates')[$this->template] ?? null;
    }

    public function getSection($selector)
    {
        return $this->sections->where('selector', $selector)->first();
    }

    public function getSections($selector)
    {
        return $this->sections->where('selector', $selector)->sortBy('post.order');
    }

    public function isExternal()
    {
        return $this->attributes['target'] == 1;
    }

    public function isInline()
    {
        return $this->attributes['target'] == 2;
    }

    public function isActive()
    {
        return request()->is($this->post->slug);
    }
}
