<?php

namespace Modules\LandingPage\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Cviebrock\EloquentSluggable\Sluggable; // Import the Sluggable trait
use Cviebrock\EloquentSluggable\SluggableScopeHelpers; // Optional: for helper methods like findBySlug()

class Menu extends Model
{
    use HasFactory, Sluggable, SluggableScopeHelpers; // Add Sluggable and SluggableScopeHelpers

    protected $table = 'lp_menus'; // Explicitly define table name
    protected $fillable = ['name', 'slug', 'location'];

    /**
     * Return the sluggable configuration array for this model.
     *
     * @return array
     */
    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'name' // Slug will be generated from the 'name' attribute
            ]
        ];
    }

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted(): void
    {
        static::deleting(function ($menu) {
            // If you don't have ON DELETE CASCADE in your database schema for menu_items,
            // this will ensure items are deleted when a menu is deleted.
            $menu->items()->delete();
        });
    }

    protected static function newFactory()
    {
        // If you create a factory, you can uncomment and point to it:
        // return \Modules\LandingPage\Database\factories\MenuFactory::new();
        return null;
    }

    /**
     * Get all menu items for the menu, ordered by 'order'.
     */
    public function items()
    {
        return $this->hasMany(MenuItem::class, 'menu_id')->orderBy('sort_order');
    }

    /**
     * Get only the root menu items (those without a parent_id), ordered by 'order'.
     */
    public function rootItems()
    {
        return $this->hasMany(MenuItem::class, 'menu_id')->whereNull('parent_id')->orderBy('sort_order');
    }
}
