<?php

namespace App\Models\Ecommerce\Product\Category;

use App\Events\Ecommerce\Product\Category\CategoryTaxChanged;
use App\Models\Concerns\HasSchemalessAttributes;
use App\Models\Ecommerce\Product\Product\Product;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
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 Category extends Model implements HasMedia, Sortable
{
    use HasEagerLimitAndRecursiveRelationships;
    use HasFactory;
    use HasSchemalessAttributes;
    use HasSlug;
    use HasTranslations;
    use InteractsWithMedia;
    use SortableTrait;

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

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

    /**
     * Sortable attributes
     *
     * @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');
    }

    /**
     * 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('thumb200x200')
            ->fit(Manipulations::FIT_CONTAIN, 200, 200);

        $this->addMediaConversion('thumb400x400')
            ->fit(Manipulations::FIT_CONTAIN, 400, 400);

        $this->addMediaConversion('thumb720x720')
            ->fit(Manipulations::FIT_CONTAIN, 720, 720);

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

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

        $this->addMediaConversion('thumb288x431')
            ->fit(Manipulations::FIT_CONTAIN, 288, 431);

        $this->addMediaConversion('thumb270x350')
            ->fit(Manipulations::FIT_CONTAIN, 270, 350);

        $this->addMediaConversion('thumb657x230')
            ->fit(Manipulations::FIT_CROP, 657, 230);
    }

    /**
     * Brand thumbnail
     */
    public function thumbnail(string $size = '200x200'): string
    {
        return $this->getFirstMediaUrl('uploads', 'thumb'.$size);
    }

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::updated(function ($category) {
            if ($category->wasChanged('tax_percentage')) {
                CategoryTaxChanged::dispatch($category);
            }
        });
    }

    /**
     * Attributes (properties) of Category
     */
    public function properties(): BelongsToMany
    {
        return $this->belongsToMany(Attribute::class, 'attributes');
    }

    /**
     * Category Products
     */
    public function products(): MorphToMany
    {
        return $this->morphToMany(Product::class, 'productable', 'product_has_relations');
    }

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

    /**
     * Color attribute
     */
    public function color(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->options->get('color'),
        );
    }

    /**
     * Category's Parent name
     *
     * @return ?string
     */
    public function parentName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->parent?->name
        );
    }

    /**
     * Check if model belongs to Market
     */
    public function isMarketCategory(): bool
    {
        return $this->type === 'market';
    }

    /**
     * Category's Products webpage
     */
    public function productsPage(): string
    {
        return route('web.categories.products', ['category' => $this->slug]);
    }
}
