<?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 Promo extends Model implements HasMedia
{
    use HasFactory;
    use InteractsWithMedia;
    
    protected $guarded = [];
    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
    ];

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

    public function creator()
    {
        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');
    }
    
}