<?php

namespace App\Models;

use App\Traits\HasTranslations;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Kalnoy\Nestedset\NodeTrait;

class Navigation extends Model
{
    use HasFactory, HasTranslations, NodeTrait;

    protected $fillable = [
        'title',
        'title_translations',
        'url',
        'location',
        'type',
        'target',
        'parent_id',
        'page_id',
        'package_id',
        'sort_order',
        'is_active',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'title_translations' => 'array',
    ];

    /**
     * Title in the current locale (from title_translations or fallback to title).
     */
    public function getTranslatedTitleAttribute(): string
    {
        $locale = app()->getLocale();
        $translations = $this->title_translations;

        if (is_string($translations)) {
            $translations = json_decode($translations, true);
        }

        // Check for the requested locale in translations JSON
        if (is_array($translations) && !empty($translations[$locale])) {
            return (string) $translations[$locale];
        }

        // For Arabic: fall back to the base `title` column
        // (old records stored Arabic in title, not in title_translations.ar)
        if ($locale === 'ar' && !empty($this->attributes['title'])) {
            return (string) $this->attributes['title'];
        }

        // Fallback to other locale in translations
        if (is_array($translations)) {
            $fallback = $locale === 'ar' ? 'en' : 'ar';
            if (!empty($translations[$fallback])) {
                return (string) $translations[$fallback];
            }
        }

        // Last resort: base title column
        return (string) ($this->attributes['title'] ?? '');
    }

    protected $table = 'navigations';

    public function page()
    {
        return $this->belongsTo(Page::class);
    }

    public function package()
    {
        return $this->belongsTo(Package::class);
    }

    public function parent()
    {
        return $this->belongsTo(Navigation::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(Navigation::class, 'parent_id')->orderBy('sort_order');
    }

    public function scopeHeader($query)
    {
        return $query->where('location', 'header');
    }

    public function scopeFooter($query)
    {
        return $query->where('location', 'footer');
    }

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

    public function getUrlAttribute($value)
    {
        if ($this->type === 'page' && $this->page_id) {
            return route('page.show', $this->page->slug ?? '#');
        }

        if ($this->type === 'package' && $this->package_id) {
            return route('package.show', $this->package->slug ?? '#');
        }

        return $value ?? '#';
    }
}
