<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Testimonial extends Model implements HasMedia
{
    use HasFactory , InteractsWithMedia;

    protected $fillable = [
        
        'name',
        'description',
        'storage_disk',
        'designation',
        'image',
    ];

    protected $guarded = ['id']; 

    
    protected static function booted()
    {
        // Use retrieved event to automatically set the "image" attribute when loading an existing model

        static::updating(function ($model) {
            if ($model['profileimage']) {
                unset($model['profileimage']);
            }
            return;
        });
        static::retrieved(function ($model) {
            $model->setImageValAttribute();
        });
    }

    // Define a method to set the "image" attribute
    protected function setImageValAttribute()
    {
        if ($this->image) {
            $storage_disk = $this->storage_disk ?? 'public';
            $provider = existprovider($storage_disk)->provider;
            // $imageUrl = $provider::getImageUrl($this->image);
            $imageUrl = $provider::getImageUrl('uploads/testimonial' . '/' . $this->image);
            // Only set the "image" attribute if it's not already set
            if ($this['profileimage'] !== $imageUrl) {
                $this['profileimage'] = $imageUrl;
            }
        }else{
            $this['profileimage'] = asset('./uploads/profile/user-profile.png');
        }
    }
}
