<?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('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);
    }

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

    /**
     * Get image when hovered (returns second image)
     */
    public function getHoverImage(string $size = '270x350'): 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);
    }
}
