<?php

namespace App\Traits\Model;

use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Spatie\Image\Manipulations;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

trait Imageable
{
    use InteractsWithMedia;

    public function images(): HasMany
    {
        return $this->hasMany(Media::class, 'model_id')->where('model_type', get_class($this));
    }

    public function image(): HasOne
    {
        return $this->hasOne(Media::class, 'model_id')->where('model_type', get_class($this))->latest();
    }

    public function registerMediaConversions(?Media $media = null): void
    {
        $watermark = public_path('img/watermark.png');

        $this->addMediaConversion('thumb')->fit(Manipulations::FIT_CROP, 32, 32)
            ->watermark($watermark)
            ->watermarkHeight(100, Manipulations::UNIT_PERCENT)
            ->watermarkWidth(100, Manipulations::UNIT_PERCENT)
            ->watermarkFit(Manipulations::FIT_FILL);
        $this->addMediaConversion('mini')->fit(Manipulations::FIT_CROP, 96, 96)
            ->watermark($watermark)
            ->watermarkHeight(100, Manipulations::UNIT_PERCENT)
            ->watermarkWidth(100, Manipulations::UNIT_PERCENT)
            ->watermarkFit(Manipulations::FIT_FILL);
        $this->addMediaConversion('preview')->fit(Manipulations::FIT_CROP, 160, 160)
            ->watermark($watermark)
            ->watermarkHeight(100, Manipulations::UNIT_PERCENT)
            ->watermarkWidth(100, Manipulations::UNIT_PERCENT)
            ->watermarkFit(Manipulations::FIT_FILL);
        $this->addMediaConversion('normal')->fit(Manipulations::FIT_CROP, 480, 480)
            ->watermark($watermark)
            ->watermarkHeight(100, Manipulations::UNIT_PERCENT)
            ->watermarkWidth(100, Manipulations::UNIT_PERCENT)
            ->watermarkFit(Manipulations::FIT_FILL);
        $this->addMediaConversion('zoom')->fit(Manipulations::FIT_CROP, 1200, 1200)
            ->watermark($watermark)
            ->watermarkHeight(100, Manipulations::UNIT_PERCENT)
            ->watermarkWidth(100, Manipulations::UNIT_PERCENT)
            ->watermarkFit(Manipulations::FIT_FILL);

        // $this->addMediaConversion('zoom')->fit(Manipulations::FIT_CROP, 1200, 1200)->withResponsiveImages();
    }
}
