<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Menu dinamis (RPD §12.2 menu). Hierarki parent-child.
 *
 * @property int $id
 * @property string $label
 * @property string|null $route named route (mis. campaigns.index)
 * @property string|null $link URL absolut bila tanpa named route
 * @property string|null $icon nama Lucide
 * @property string $section
 * @property int $menu_type_id
 * @property int|null $parent_id
 * @property int $sort_order
 * @property bool $status
 *
 * @method static Builder|self active()
 */
class Menu extends Model
{
    protected $fillable = [
        'label', 'route', 'link', 'icon', 'section',
        'menu_type_id', 'parent_id', 'sort_order', 'status',
    ];

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

    public function menuType(): BelongsTo
    {
        return $this->belongsTo(MenuType::class);
    }

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

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

    public function groups(): BelongsToMany
    {
        return $this->belongsToMany(Group::class, 'menu_groups');
    }

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