<?php

/**
 * Created by Reliese Model.
 */

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Kalnoy\Nestedset\NodeTrait;

/**
 * Class Category
 *
 * @property int $id
 * @property string $name
 * @property string $short_name
 * @property string|null $slug
 * @property bool $enabled
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property int $_lft
 * @property int $_rgt
 * @property int|null $parent_id
 */
class Category extends Model
{
    use NodeTrait;

    protected $table = 'categories';

    protected $casts = [
        'enabled' => 'bool',
        '_lft' => 'int',
        '_rgt' => 'int',
        'parent_id' => 'int',
        'serp_at' => 'datetime',
    ];

    protected $fillable = [
        'name',
        'short_name',
        'slug',
        'enabled',
        '_lft',
        '_rgt',
        'parent_id',
        'serp_at',
    ];

    protected static function boot()
    {
        parent::boot();

        static::saved(function ($category) {
            if (empty($category->slug)) {
                $category->slug = Str::slug($category->name);
                $category->saveQuietly();
            }
        });
    }

    public function saveQuietly(array $options = [])
    {
        return static::withoutEvents(function () use ($options) {
            return $this->save($options);
        });
    }

    public function posts()
    {
        return $this->hasManyThrough(
            Post::class,
            PostCategory::class,
            'category_id',     // Foreign key on PostCategory table
            'id',              // Local key on Post table
            'id',              // Local key on Category table
            'post_id'          // Foreign key on PostCategory table
        );
    }
}
