<?php

namespace App\Modules\System\Models;

use Illuminate\Database\Eloquent\Model;
use DB;
class Menu extends Model
{
    protected $table = 'menus';
    public function save_menu(){
        DB::table($this->table)->insert(['name' => $this->name, 'slug' => $this->slug,'parent'=>$this->parent,'order'=>$this->order,'enabled'=>$this->enabled,'nivel'=>$this->nivel,'icon_text'=>$this->icon_text]);
        $id = DB::getPdo()->lastInsertId();
        return $id;
    }
    public function save_menu_recursive($elemento,$parent = 0,$order =0){
        foreach ($elemento as $c) {
            $menu = New Menu();
            $sort = $menu::where('parent',$parent)->count();
            //$parent = $this->table::where('parent',$val['id'])->get()->last();

            $sort_order = ($parent == 0) ? $sort+1 : $order+0.1;
            $menu->name =  $c->title;
            $menu->slug =  $c->slug;
            $menu->parent = $parent;
            $menu->order = $sort_order;
            $menu->enabled = 1;
            $menu->save();
            $id = $menu->id;
            if (isset($c->children)) {
                $this->save_menu_recursive($c->children,$id, $sort_order);
            }
        }

    }
    public function getChildren($data, $line)
    {
        $children = [];
        foreach ($data as $line1) {
            if ($line['id'] == $line1['parent']) {
                $children = array_merge($children, [ array_merge($line1, ['submenu' => $this->getChildren($data, $line1) ]) ]);
            }
        }
        return $children;
    }
    public function optionsMenu()
    {
        return $this->where('enabled', 1)
            ->orderby('parent')
            ->orderby('id')
            ->orderby('name')
            ->get()
            ->toArray();
    }
    public static function menus()
    {
        $menus = new Menu();
        $data = $menus->optionsMenu();
        $menuAll = [];
        foreach ($data as $line) {
            $item = [ array_merge($line, ['submenu' => $menus->getChildren($data, $line) ]) ];
            $menuAll = array_merge($menuAll, $item);
        }
        return $menus->menuAll = $menuAll;
    }
}
