<?php

namespace App\Models;

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

class NavigationMenu extends Model
{
    protected $fillable = [
        'location',
        'label',
        'route_name',
        'url',
        'icon',
        'sort_order',
        'is_visible',
        'open_in_new_tab',
        'badge_key',
        'permission_key',
    ];

    protected function casts(): array
    {
        return [
            'is_visible' => 'boolean',
            'open_in_new_tab' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

    public static function forLocation(string $location): Collection
    {
        $rows = Cache::remember("nav_menus_{$location}", 60, function () use ($location) {
            return static::query()
                ->where('location', $location)
                ->where('is_visible', true)
                ->orderBy('sort_order')
                ->orderBy('label')
                ->get()
                ->map(fn (self $item) => $item->getAttributes())
                ->all();
        });

        // Hydrate from cached attributes to avoid __PHP_Incomplete_Class from serialized models.
        return static::hydrate(is_array($rows) ? $rows : []);
    }

    public static function flushCache(): void
    {
        Cache::forget('nav_menus_admin');
        Cache::forget('nav_menus_portal');
    }

    public function href(): string
    {
        if ($this->route_name && Route::has($this->route_name)) {
            return route($this->route_name);
        }

        return $this->url ?: '#';
    }

    public function isActive(string $currentRoute): bool
    {
        if (! $this->route_name) {
            return false;
        }

        if ($currentRoute === $this->route_name) {
            return true;
        }

        // Match resource prefixes e.g. admin.customers.index → admin.customers.*
        $parts = explode('.', $this->route_name);
        if (count($parts) >= 2) {
            $prefix = $parts[0].'.'.$parts[1];
            return str_starts_with($currentRoute, $prefix);
        }

        return str_starts_with($currentRoute, $this->route_name);
    }
}
