<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Route;

class Menu extends Model
{
    protected $fillable = [
        'parent_id', 'name', 'url', 'route_name',
        'icon', 'target', 'location', 'order', 'is_active',
    ];

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

    public function children()
    {
        return $this->hasMany(Menu::class, 'parent_id')->ordered();
    }

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

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

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

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

    public function scopeParents($query)
    {
        return $query->whereNull('parent_id');
    }

    public function getResolvedUrl(): string
    {
        if ($this->url) {
            if (str_starts_with($this->url, 'http://') || str_starts_with($this->url, 'https://') || str_starts_with($this->url, '/')) {
                return $this->url;
            }
            return url($this->url);
        }
        if ($this->route_name && Route::has($this->route_name)) {
            try {
                return route($this->route_name);
            } catch (\Exception) {
                return '#';
            }
        }
        return '#';
    }

    public function isActive(): bool
    {
        if ($this->route_name && request()->routeIs($this->route_name)) {
            return true;
        }
        if ($this->route_name && request()->routeIs($this->route_name . '*')) {
            return true;
        }
        return false;
    }
}
