<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Permission;

class Menu extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'permission_name',
        'parent_id',
        'route',
        'icon',
        'order',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
        ];
    }

    /**
     * Parent menu (for dropdowns).
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(Menu::class, 'parent_id');
    }

    /**
     * Child menu items.
     */
    public function children(): HasMany
    {
        return $this->hasMany(Menu::class, 'parent_id')->orderBy('order');
    }

    /**
     * Active children only.
     */
    public function activeChildren(): HasMany
    {
        return $this->children()->where('is_active', true);
    }

    /**
     * Check if current user can access this menu.
     */
    public function userCanAccess(): bool
    {
        // If no permission required, allow access
        if (empty($this->permission_name)) {
            return true;
        }

        $user = Auth::user();
        if (!$user) {
            return false;
        }

        return $user->can($this->permission_name);
    }

    /**
     * Get menu tree for current user.
     * Returns only menus the user has permission to access.
     */
    public static function getForUser(): Collection
    {
        $user = Auth::user();
        if (!$user) {
            return collect();
        }

        // Get all user permissions
        $userPermissions = $user->getAllPermissions()->pluck('name')->toArray();
        
        // Super Admin has all permissions
        $isSuperAdmin = $user->hasRole('Super Admin');

        // Get top-level menus
        $menus = static::whereNull('parent_id')
            ->where('is_active', true)
            ->orderBy('order')
            ->with(['activeChildren'])
            ->get();

        // Filter based on permissions
        return $menus->filter(function ($menu) use ($userPermissions, $isSuperAdmin) {
            // Check if user can access this menu
            if (!$isSuperAdmin && $menu->permission_name && !in_array($menu->permission_name, $userPermissions)) {
                return false;
            }

            // If menu has children, filter them too
            if ($menu->activeChildren->isNotEmpty()) {
                $menu->setRelation('activeChildren', $menu->activeChildren->filter(function ($child) use ($userPermissions, $isSuperAdmin) {
                    if ($isSuperAdmin) return true;
                    if (empty($child->permission_name)) return true;
                    return in_array($child->permission_name, $userPermissions);
                }));

                // If parent has no accessible children and requires permission itself, hide it
                if ($menu->activeChildren->isEmpty() && $menu->permission_name) {
                    return false;
                }
            }

            return true;
        })->values();
    }

    /**
     * Check if any user has any permissions at all.
     */
    public static function userHasAnyPermission(): bool
    {
        $user = Auth::user();
        if (!$user) {
            return false;
        }

        // Super Admin always has permissions
        if ($user->hasRole('Super Admin')) {
            return true;
        }

        return $user->getAllPermissions()->isNotEmpty();
    }
}
