<?php

namespace App\Models;

use App\Enums\MenuType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Menu extends Model
{
    protected $fillable = [
        'parent_id', 'name', 'path', 'component', 'icon',
        'permission_code', 'type', 'visible', 'sort', 'status',
    ];

    protected $casts = [
        'type' => MenuType::class,
        'visible' => 'integer',
        'status' => 'integer',
    ];

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

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

    /**
     * 获取完整菜单树
     */
    public static function tree(): array
    {
        $all = self::where('status', 1)->orderBy('sort')->get()->toArray();
        return self::buildTree($all);
    }

    private static function buildTree(array $items, int $parentId = 0): array
    {
        $tree = [];
        foreach ($items as $item) {
            if ($item['parent_id'] == $parentId) {
                $children = self::buildTree($items, $item['id']);
                if ($children) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }
}
