<?php

namespace App\Domain\Website\Models;

use App\Domain\Shared\Traits\BelongsToAcademy;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class WebsiteMenuItem extends Model
{
    use BelongsToAcademy;

    protected $fillable = [
        'academy_id', 'website_menu_id', 'parent_id',
        'label', 'label_en',
        'link_type', 'website_page_id', 'url', 'anchor', 'route_name',
        'icon', 'open_in_new_tab', 'is_visible', 'highlight', 'sort_order',
    ];

    protected $casts = [
        'open_in_new_tab' => 'boolean',
        'is_visible' => 'boolean',
        'highlight' => 'boolean',
        'sort_order' => 'integer',
    ];

    public function menu(): BelongsTo
    {
        return $this->belongsTo(WebsiteMenu::class, 'website_menu_id');
    }

    public function page(): BelongsTo
    {
        return $this->belongsTo(WebsitePage::class, 'website_page_id');
    }

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

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

    public function childrenRecursive(): HasMany
    {
        return $this->children()->with('childrenRecursive');
    }

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

    public function localizedLabel(?string $locale = null): string
    {
        $locale ??= app()->getLocale();

        return $locale === 'ar'
            ? ($this->label ?: $this->label_en ?: '')
            : ($this->label_en ?: $this->label ?: '');
    }

    /**
     * Resolves the item to an href.
     *
     * A missing or unsafe target yields null so the caller skips rendering the
     * link entirely. External URLs pass through safe_url(), because this value
     * is written straight into an href and menu items are editor-supplied.
     */
    public function href(): ?string
    {
        return match ($this->link_type) {
            'page' => $this->page?->url(),
            'url' => safe_url($this->url),
            'anchor' => $this->anchor ? '#'.ltrim($this->anchor, '#') : null,
            'route' => $this->route_name && \Illuminate\Support\Facades\Route::has($this->route_name)
                ? route($this->route_name)
                : null,
            default => null,
        };
    }

    /** A parent with children but no target is a dropdown trigger, not a dead link. */
    public function isDropdownParent(): bool
    {
        return $this->link_type === 'none' && $this->children->isNotEmpty();
    }
}
