<?php

namespace App\Models;

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

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

    protected $fillable = [
        'carousel_id',
        'linkable_type',
        'linkable_id',
    ];

    // Relations
    public function carousel()
    {
        return $this->belongsTo(Carousel::class);
    }

    public function linkable()
    {
        return $this->morphTo();
    }

    public function translations()
    {
        return $this->hasMany(CarouselSlideTranslation::class);
    }

    // Scopes
    public function scopeByCarousel($query, $carouselId)
    {
        return $query->where('carousel_id', $carouselId);
    }

    public function scopeByLinkable($query, $type, $id = null)
    {
        $query->where('linkable_type', $type);
        if ($id) {
            $query->where('linkable_id', $id);
        }
        return $query;
    }

    // Helper Methods
    public function getTranslation($localeId)
    {
        return $this->translations()->where('locale_id', $localeId)->first();
    }

    public function getTitle($localeId = null)
    {
        if ($localeId) {
            $translation = $this->getTranslation($localeId);
            return $translation ? $translation->title : 'Slide #' . $this->id;
        }
        return 'Slide #' . $this->id;
    }

    public function getDescription($localeId = null)
    {
        if ($localeId) {
            $translation = $this->getTranslation($localeId);
            return $translation ? $translation->description : null;
        }
        return null;
    }

    public function getButtonText($localeId = null)
    {
        if ($localeId) {
            $translation = $this->getTranslation($localeId);
            return $translation ? $translation->button_text : null;
        }
        return null;
    }

    public function getButtonLink($localeId = null)
    {
        if ($localeId) {
            $translation = $this->getTranslation($localeId);
            return $translation ? $translation->button_link : null;
        }
        return null;
    }

    // Media Collections
    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('image')
              ->singleFile()
              ->acceptsMimeTypes(['image/jpeg', 'image/png', 'image/webp']);
    }
}