<?php

namespace Modules\Post\Models;

use Modules\Main\Models\City;
use Modules\Post\Models\PostCity;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\HasMany;

use Te7aHoudini\LaravelTrix\Traits\HasTrixRichText;
use Modules\Main\Models\Scopes\CityScope;

class Post extends Model
{
    use HasFactory;
    use HasTrixRichText;
    protected $guarded = [];
    protected $fillable = [
        'name',
        'short_text',
        'text',
        'category',
        'image',
        'post-trixFields'
    ];

    protected static function booted(): void
    {
        static::addGlobalScope(new CityScope);
        
        static::deleted(function ($post) {
            $post->trixRichText->each->delete();
            $post->trixAttachments->each->purge();
        });
    }

    public function cities(): HasManyThrough
    {
        return $this->hasManyThrough(
            City::class,
            PostCity::class,
            'post_id',
            'id',
            'id',
            'city_id'
        );
    }

    public function scopeVisibleForUser(Builder $query)
    {
        auth()->user()->can('view', $this) ? $query : $query->whereRaw('0 = 1');
    }
}
