<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class Menu extends Model
{
    use HasFactory;

    protected $fillable = ['parent_id','order','title','icon','uri','permission'];

    protected static function booted()
    {
        static::created(function ($user) {
            static::removeMenuFromCache();
        });
        static::updated(function ($user) {
            static::removeMenuFromCache();
        });
        static::deleted(function ($user) {
            static::removeMenuFromCache();
        });
    }
      public function parent()
    {
        return $this->belongsTo(Menu::class, 'parent_id', 'id');
    }

    public function children() {

        return $this->hasMany(Menu::class, 'parent_id', 'id')->with('children');

    } 

    public static function display($type=false)
    {
        
        // GET THE MENU - sort collection in blade
        // dd(\Carbon\Carbon::now()->addDays(30));
        $menu = Cache::remember('menu', \Carbon\Carbon::now()->addDays(30), function () {
            return static::whereNull('parent_id')->orderBy('order')->with(['children' => function ($q) {
                $q->orderBy('order');
            }])->get();
        });
        $items = $menu->sortBy('order');
        $items = static::processItems($items,$type);
        return $items;
    }


    protected static function processItems($items,$type)
    {
        $items = $items->transform(function ($item) use($type) {
            $item->href = $item->uri;

            if ($item->children->count() > 0) {
                $item->setRelation('children', static::processItems($item->children,$type));
            }
            return $item;
        });

        $items = $items->filter(function ($item) use($type) {
            return $type||$item->permission=="" || Auth::user()->can($item->permission);
        })->filter(function ($item) {
            // Filter out empty menu-items
            if ($item->uri == '' && $item->children->count() == 0) {
                return false;
            }
            return true;
        });
        return $items->values();
    }

    public static function removeMenuFromCache()
    {
        Cache::forget('menu');
    }

    public static function highestOrderMenuItem($parent = null)
    {
        $order = 1;

        $item = static::where('parent_id', '=', $parent)
            ->orderBy('order', 'DESC')
            ->first();

        if (!is_null($item)) {
            $order = intval($item->order) + 1;
        }

        return $order;
    }
}
