<?php

namespace App\Models\Ecommerce\Product\Collection;

use App\Models\Ecommerce\Product\Product\Product;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;
use Spatie\Image\Manipulations;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
use Spatie\Translatable\HasTranslations;
use Staudenmeir\EloquentEagerLimitXLaravelAdjacencyList\Eloquent\HasEagerLimitAndRecursiveRelationships;

class Collection extends Model implements HasMedia, Sortable
{
    use HasEagerLimitAndRecursiveRelationships;
    use HasFactory;
    use HasSlug;
    use HasTranslations;
    use InteractsWithMedia;
    use SortableTrait;

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'name',
        'slug',
        'description',
        'sort_order',
        'seo_title',
        'seo_description',
        'is_visible',
    ];

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

    /**
     * Translatable fields
     *
     * @var array<string, mixed>
     */
    public $sortable = [
        'order_column_name' => 'sort_order',
        'sort_when_creating' => true,
    ];

    /**
     * Get the options for generating the slug.
     */
    public function getSlugOptions(): SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('name')
            ->saveSlugsTo('slug');
    }

    /**
     * Register Media Collections
     */
    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('uploads')
            ->singleFile()
            ->acceptsMimeTypes(['image/jpg', 'image/jpeg', 'image/png'])
            ->useFallbackUrl(
                sprintf('%s/logo-space.png', config('app.url'))
            );
    }

    /**
     * Register Media Conversions
     */
    public function registerMediaConversions(?Media $media = null): void
    {
        $this->addMediaConversion('thumb400x400')
            ->fit(Manipulations::FIT_CONTAIN, 400, 400);

        $this->addMediaConversion('thumb800x800')
            ->fit(Manipulations::FIT_CONTAIN, 800, 800);

        $this->addMediaConversion('thumb1200x1200')
            ->fit(Manipulations::FIT_CONTAIN, 1200, 1200);
    }

    /**
     * Products
     */
    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class, 'collection_product');
    }

    /**
     * Brand's Products web page
     */
    public function productsPage(): string
    {
        return route('web.collections.products', ['collection' => $this->slug]);
    }
}
