<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Service extends Model implements HasMedia
{
    use HasFactory;
    use InteractsWithMedia;

    protected $guarded = [];

    // Otomatis isi created_by & updated_by
    protected static function booted(): void
    {
        static::creating(fn ($model) => $model->created_by = Auth::id());
        static::updating(fn ($model) => $model->updated_by = Auth::id());
    }

    // Relasi ke User
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('images')
            ->useDisk('public')
            ->singleFile();
    }

    public function getImageUrlAttribute(): string
    {
        if ($this->getFirstMediaUrl('images')) {
            return $this->getFirstMediaUrl('images');
        }

        if (!empty($this->image)) {
            return asset('storage/' . ltrim($this->image, '/'));
        }

        return asset('images/default.png');
    }
}