<?php
/**
 * Admin Menus
 *
 * Manages Admin Menus.
 *
 * @author Florin Radica <florin.radica@mtcmedia.co.uk>
 * @since 04/07/2017
 */

namespace Mtc\Core;

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

/**
 * Class AdminMenu
 */
class AdminMenu extends Model
{
    /**
     * @var string $table The table name to use with the model
     */
    protected $table = 'admin_menu';

        /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'sub_id',
        'title',
        'path',
        'activePath',
        'constant',
        'icon',
        'new_window',
        'order',
    ];

    /**
     * indicates if the model should be timestamped
     */
    public $timestamps = false;

    /**
     * Gets the sub admin menus for this menu
     *
     * @return HasMany The query builder instance
     */
    public function submenus()
    {
        return $this->hasMany(AdminMenu::class, 'sub_id')->orderBy('order');
    }

    /**
     * Gets the parent admin menu for this menu
     *
     * @return BelongsTo The query builder instance
     */
    public function parentMenu()
    {
        return $this->belongsTo(AdminMenu::class, 'sub_id');
    }


    public static function getNavTreePermissions(int $admin_id = null)
    {
        $nav_items = [];

        $temp_items = self::all();
        foreach ($temp_items as $temp_item) {
            $nav_items[$temp_item->id] = $temp_item;
        }

        if ($nav_items) {
            foreach ($nav_items as $child) {
                if (\AdminUser::can($child->id, $admin_id)) {
                    $child->is_allowed = true;

                    if ($child->sub_id) {
                        if (isset($nav_items[$child->sub_id])) {
                            $nav_items[$child->sub_id]->is_allowed = true;
                        }
                    }
                }
            }
        }

        return $nav_items;
    }
}
