<?php

namespace App\Models;

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

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

    protected $fillable = [
        'is_featured',
        'order',
        'status',
    ];

    protected $casts = [
        'is_featured' => 'boolean',
        'order' => 'integer',
    ];

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

    public function countries()
    {
        return $this->belongsToMany(Country::class, 'country_occasion');
    }

    public function offers()
    {
        return $this->belongsToMany(Offer::class, 'occasion_offer');
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('order')->orderBy('id');
    }

    public function scopeByCountry($query, $countryId)
    {
        return $query->whereHas('countries', function ($q) use ($countryId) {
            $q->where('countries.id', $countryId);
        });
    }

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

    public function getName($localeId = null)  // ✅
    {
        if ($localeId) {
            $translation = $this->getTranslation($localeId);
            return $translation ? $translation->name : 'Occasion #' . $this->id;
        }
        return 'Occasion #' . $this->id;
    }

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

    // Accessors
    public function getIsActiveAttribute()
    {
        return $this->status === 'active';
    }

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

        $this->addMediaCollection('banner')
            ->singleFile()
            ->acceptsMimeTypes(['image/jpeg', 'image/png', 'image/webp']);
    }
}
