<?php

namespace App\Traits;

use App\Models\Files;
use App\Models\Image;
use App\Models\ImageSetting;

trait ImagenesGetterTrait
{

    public function getImageSmallAttribute()
    {
        if ($this->id && $this->image_small_getter)
            return $this->getRecorte();
    }

    public function imagen($recorte = 'large')
    {
        return $this->getRecorte($recorte, true);
    }

    public function getImageLargeAttribute()
    {
        if ($this->id && $this->image_large_getter)
            return $this->getRecorte('large', true);
    }

    private function getRecorte($type = 'small', $nullable = false)
    {

        $image = Image::where('imageable_type', get_class($this))
            ->where('imageable_id', $this->id)
            ->latest()
            ->first();

        $settings = ImageSetting::where('type', get_class($this))
            ->latest()
            ->first();

        if ($image && $settings)
            return asset('storage/' . $settings->upload_to . '/' . $image->name . '@' . $type . '.' . $image->ext);
        else if (!$nullable)
            return 'https://ui-avatars.com/api/?background=random&size=500&name=' . urlencode($this->titulo);
    }

    public function getImagenesAttribute()
    {
        if (!$this->id)
            return [];

        $type = 'large';
        $images = Image::where('imageable_type', get_class($this))
            ->where('imageable_id', $this->id)
            ->latest()
            ->get();

        $settings = ImageSetting::where('type', get_class($this))
            ->latest()
            ->first();

        $imagenes = [];
        foreach ($images as $image) {
            $imagenes[] = asset('storage/' . $settings->upload_to . '/' . $image->name . '@' . $type . '.' . $image->ext);
        }

        return $imagenes;
    }
}
