<?php

namespace App\Models;

use App\Traits\Auditable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;

class Service extends Model
{
    use HasFactory, Auditable;

    protected $fillable = [
        'title',
        'slug',
        'category',
        'tags',
        'sort_order',
        'short_description',
        'long_description',
        'hero_title',
        'benefits',
        'image',
        'image_media_id',
        'icon',
        'icon_media_id',
        'seo_title',
        'seo_description',
    ];

    protected $casts = [
        'tags' => 'array',
    ];

    public function mediaUsages(): MorphMany
    {
        return $this->morphMany(MediaUsage::class, 'usable');
    }

    public function imageMedia(): BelongsTo
    {
        return $this->belongsTo(Media::class, 'image_media_id');
    }

    public function iconMedia(): BelongsTo
    {
        return $this->belongsTo(Media::class, 'icon_media_id');
    }

    public function getBenefitItemsAttribute(): array
    {
        if (blank($this->benefits)) {
            return [];
        }

        return array_values(array_filter(array_map(
            static fn (string $item): string => trim($item),
            preg_split('/[\r\n,]+/', (string) $this->benefits) ?: []
        )));
    }

    public function getImageUrlAttribute(): string
    {
        $media = $this->relationLoaded('imageMedia') ? $this->imageMedia : $this->imageMedia()->first();

        if ($media) {
            return $media->url;
        }

        return asset($this->image ?: 'uploads/placeholders/default-service.jpg');
    }

    public function getIconUrlAttribute(): string
    {
        $media = $this->relationLoaded('iconMedia') ? $this->iconMedia : $this->iconMedia()->first();

        if ($media) {
            return $media->url;
        }

        return asset($this->icon ?: 'uploads/placeholders/default-logo.png');
    }

    public function getBenefitsTextAttribute(): string
    {
        return implode("\n", $this->benefit_items);
    }
}
