<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Menu extends Model
{
    use HasFactory;

    protected $guarded = [];

    /**
     * Sitemap cache auto refresh (Menu change হলে)
     */
    protected static function booted()
    {
        static::saved(function () {
            cache()->forget('sef_sitemap_xml_v1');
        });

        static::deleted(function () {
            cache()->forget('sef_sitemap_xml_v1');
        });
    }

    /**
     * Get submenus for a menu (ordered).
     */
    public function submenus()
    {
        return $this->hasMany(Menu::class, 'parent_id')
            ->orderBy('order');
    }

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

    public function products()
    {
        return $this->belongsToMany(Product::class, 'menu_product')
            ->withTimestamps();
    }
}
