<?php

namespace App\Models\CMS\Media;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Image\Manipulations;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\Translatable\HasTranslations;

class Gallery extends Model implements HasMedia
{
    use HasFactory;
    use HasTranslations;
    use InteractsWithMedia;

    /**
     * Table
     */
    protected $table = 'galleries';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'title',
        'description',
        'is_visible',
    ];

    /**
     * @var array<string>
     */
    public $translatable = ['title', 'description'];

    /**
     * Media collections
     */
    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('main')
            ->singleFile();
    }

    /**
     * Media conversations
     */
    public function registerMediaConversions(?Media $media = null): void
    {
        $this->addMediaConversion('thumb')
            ->width(470)
            ->height(345)
            ->fit(Manipulations::FIT_CONTAIN, 470, 345);
    }

    /**
     * Thumbnail url
     */
    public function thumbnail(): string
    {
        return $this->getFirstMediaUrl('main', 'thumb');
    }

    /**
     * Scope for visable galleries
     *
     * @param  Builder  $query
     */
    public function scopeEnabled($query): void
    {
        $query->where('is_visible', true);
    }
}
