<?php

namespace Filanco\Cms\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Filanco\Cms\Facades\Cms;
use Filanco\Cms\Traits\Translatable;

class Post extends Model
{
    use Translatable;

    protected $translatable = ['title', 'seo_title', 'excerpt', 'body', 'slug', 'meta_description', 'meta_keywords'];

    const PUBLISHED = 'PUBLISHED';

    protected $guarded = [];

    public function save(array $options = [])
    {


        // If no author has been assigned, assign the current user's id as the author of the post
        if (!$this->author_id && Auth::user()) {
            $this->author_id = Auth::user()->id;
        }

        parent::save();
    }

    public function authorId()
    {
        return $this->belongsTo(Cms::modelClass('User'));
    }

    /**
     * Scope a query to only published scopes.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePublished(Builder $query)
    {
        return $query->where('status', '=', static::PUBLISHED);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function category()
    {
        return $this->hasOne(Cms::modelClass('Category'), 'id', 'category_id');
    }

    public function category3()
    {
        return $this->hasOne(Cms::modelClass('Category'));
    }


    /**
     * Display menu.
     *
     * @param string $menuName
     * @param string|null $type
     * @param array $options
     *
     * @return string
     */
    public static function display($category_id, array $options = [])
    {

        // GET THE MENU - sort collection in blade
        $post = static::where('category_id', '=', $category_id)->join('categories', 'posts.category_id', '=', 'categories.id')->orderBy('posts.created_at', 'desc')->select('posts.*', 'categories.slug as c_slug');

          if(isset($options['limit']))
        $post->take($options['limit']);

        $post=$post->get()->toArray();

        // Check for Menu Existence
        if (!isset($post)) {
            return false;
        }


        return new \Illuminate\Support\HtmlString(
            \Illuminate\Support\Facades\View::make('post.list', ['posts' => $post,'option'=>$options])->render()
        );
    }


}
