<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Hub extends Model
{
    use HasFactory;

    // ── Fillable ───────────────────────────────────────────────
    protected $fillable = [
        'slug',
        'name_en',
        'name_ar',
        'description_en',
        'description_ar',
        'icon',
        'color',
        'sort_order',
        'is_active',
    ];

    // ── Casts ─────────────────────────────────────────────────
    protected $casts = [
        'is_active'  => 'boolean',
        'sort_order' => 'integer',
    ];

    // ── Helpers ───────────────────────────────────────────────

    // Returns the correct name based on current app locale
    public function getNameAttribute(): string
    {
        return app()->getLocale() === 'ar'
            ? ($this->name_ar ?? $this->name_en)
            : $this->name_en;
    }

    public function getDescriptionAttribute(): ?string
    {
        return app()->getLocale() === 'ar'
            ? ($this->description_ar ?? $this->description_en)
            : $this->description_en;
    }

    // ── Scopes ────────────────────────────────────────────────

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    public function scopeOrdered(Builder $query): Builder
    {
        return $query->orderBy('sort_order');
    }

    // ── Relationships ─────────────────────────────────────────

    public function members(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'user_hubs')
                    ->withPivot('is_primary', 'joined_at');
    }

    public function cases(): HasMany
    {
        return $this->hasMany(Cases::class);
    }

    public function forumPosts(): HasMany
    {
        return $this->hasMany(ForumPost::class);
    }

    public function documents(): HasMany
    {
        return $this->hasMany(Document::class);
    }

    public function freelanceProfiles(): HasMany
    {
        return $this->hasMany(FreelanceProfile::class);
    }

    public function freelanceBriefs(): HasMany
    {
        return $this->hasMany(FreelanceBrief::class);
    }

    public function surveys(): HasMany
    {
        return $this->hasMany(Survey::class);
    }
}
