<?php

namespace App\Models\Ecommerce\Product\Product\Concerns;

use Spatie\Image\Manipulations;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

trait ProductMedia
{
    /**
     * Media collections
     */
    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('uploads')
            ->useFallbackUrl(url('/assets/web/images/05.jpg'));
    }

    /**
     * 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);
    }

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

    /**
     * Get image when hovered (returns second image)
     */
    public function getHoverImage(string $size = '400x400'): string
    {
        $media = $this->getMedia('uploads');
        $image_count = $media->count();

        if ($image_count == 0) {
            return '';
        }

        return ($image_count == 1)
            ? $media[0]->getUrl('thumb'.$size)
            : $media[1]->getUrl('thumb'.$size);
    }
}
