<?php

namespace App\Models;

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

class Category 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(CategoryTranslation::class);
    }

    // ✅ FIX: تحديد الـ foreign keys بشكل صريح
    public function countryStores()
    {
        return $this->belongsToMany(
            CountryStore::class,
            'category_country_store',      // pivot table name
            'category_id',                  // foreign key في الـ pivot table
            'country_store_id'              // related key في الـ pivot table
        );
    }

    public function offers()
    {
        return $this->belongsToMany(Offer::class, 'category_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');
    }

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

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

    public function getDescription($languageId = null)
    {
        if ($languageId) {
            $translation = $this->getTranslation($languageId);
            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('cover')
              ->singleFile()
              ->acceptsMimeTypes(['image/jpeg', 'image/png', 'image/webp']);
    }
}