<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Storage;

class ReservationService extends Model
{
    protected $fillable = ['name', 'description', 'image', 'duration_minutes', 'price', 'order', 'translations'];

    protected $casts = [
        'price' => 'decimal:2',
        'translations' => 'array',
    ];

    public function getTranslatedName(string $locale, string $defaultLocale = 'fr'): string
    {
        if ($locale === $defaultLocale) {
            return $this->name;
        }
        $tr = $this->translations[$locale] ?? [];
        return is_array($tr) && ! empty($tr['name']) ? $tr['name'] : $this->name;
    }

    public function getTranslatedDescription(string $locale, string $defaultLocale = 'fr'): ?string
    {
        if ($locale === $defaultLocale) {
            return $this->description;
        }
        $tr = $this->translations[$locale] ?? [];
        return is_array($tr) && isset($tr['description']) && $tr['description'] !== '' ? $tr['description'] : $this->description;
    }

    public function getImageUrlAttribute(): ?string
    {
        return $this->image ? Storage::url($this->image) : null;
    }

    public function slots(): HasMany
    {
        return $this->hasMany(ReservationSlot::class, 'reservation_service_id');
    }

    public function reservations(): HasMany
    {
        return $this->hasManyThrough(Reservation::class, ReservationSlot::class, 'reservation_service_id', 'reservation_slot_id');
    }
}
